@renanlido/tia-openness-mcp 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1751 -1250
  2. package/package.json +6 -1
package/dist/index.js CHANGED
@@ -8,7 +8,11 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
8
8
  var __getProtoOf = Object.getPrototypeOf;
9
9
  var __hasOwnProp = Object.prototype.hasOwnProperty;
10
10
  var __commonJS = (cb, mod) => function __require() {
11
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ try {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ } catch (e) {
14
+ throw mod = 0, e;
15
+ }
12
16
  };
13
17
  var __export = (target, all) => {
14
18
  for (var name in all)
@@ -3107,9 +3111,28 @@ var require_utils = __commonJS({
3107
3111
  "use strict";
3108
3112
  var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
3109
3113
  var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
3114
+ var isPort = RegExp.prototype.test.bind(/^\d*$/u);
3110
3115
  var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
3111
3116
  var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
3112
- var isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);
3117
+ var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u);
3118
+ var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u);
3119
+ var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u);
3120
+ var BYTE_HEX = new Array(256);
3121
+ {
3122
+ const HEX_DIGITS = "0123456789ABCDEF";
3123
+ for (let i = 0; i < 256; i++) {
3124
+ BYTE_HEX[i] = "%" + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 15];
3125
+ }
3126
+ }
3127
+ function percentEncodeNonAscii(cp) {
3128
+ if (cp < 2048) {
3129
+ return BYTE_HEX[192 | cp >> 6] + BYTE_HEX[128 | cp & 63];
3130
+ }
3131
+ if (cp < 65536) {
3132
+ return BYTE_HEX[224 | cp >> 12] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63];
3133
+ }
3134
+ return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63];
3135
+ }
3113
3136
  function stringArrayToHexStripped(input) {
3114
3137
  let acc = "";
3115
3138
  let code = 0;
@@ -3134,91 +3157,105 @@ var require_utils = __commonJS({
3134
3157
  }
3135
3158
  return acc;
3136
3159
  }
3160
+ var isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/);
3161
+ var isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/);
3162
+ var isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/);
3137
3163
  var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
3138
- function consumeIsZone(buffer) {
3139
- buffer.length = 0;
3140
- return true;
3141
- }
3142
- function consumeHextets(buffer, address, output) {
3143
- if (buffer.length) {
3144
- const hex3 = stringArrayToHexStripped(buffer);
3145
- if (hex3 !== "") {
3146
- address.push(hex3);
3147
- } else {
3148
- output.error = true;
3149
- return false;
3164
+ function isZoneIdentifier(zone) {
3165
+ if (zone.length === 0) return false;
3166
+ for (let i = 0; i < zone.length; i++) {
3167
+ if (isZoneCharacter(zone[i])) continue;
3168
+ if (zone[i] === "%" && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {
3169
+ i += 2;
3170
+ continue;
3150
3171
  }
3151
- buffer.length = 0;
3172
+ return false;
3152
3173
  }
3153
3174
  return true;
3154
3175
  }
3155
- function getIPV6(input) {
3156
- let tokenCount = 0;
3157
- const output = { error: false, address: "", zone: "" };
3158
- const address = [];
3159
- const buffer = [];
3160
- let endipv6Encountered = false;
3161
- let endIpv6 = false;
3162
- let consume = consumeHextets;
3163
- for (let i = 0; i < input.length; i++) {
3164
- const cursor = input[i];
3165
- if (cursor === "[" || cursor === "]") {
3166
- continue;
3167
- }
3168
- if (cursor === ":") {
3169
- if (endipv6Encountered === true) {
3170
- endIpv6 = true;
3171
- }
3172
- if (!consume(buffer, address, output)) {
3173
- break;
3174
- }
3175
- if (++tokenCount > 7) {
3176
- output.error = true;
3177
- break;
3178
- }
3179
- if (i > 0 && input[i - 1] === ":") {
3180
- endipv6Encountered = true;
3181
- }
3182
- address.push(":");
3183
- continue;
3184
- } else if (cursor === "%") {
3185
- if (!consume(buffer, address, output)) {
3186
- break;
3176
+ function compressIPv6ZeroRun(hextets) {
3177
+ let bestStart = -1;
3178
+ let bestLength = 0;
3179
+ let runStart = -1;
3180
+ let runLength = 0;
3181
+ for (let i = 0; i < hextets.length; i++) {
3182
+ if (hextets[i] === "0") {
3183
+ if (runStart === -1) runStart = i;
3184
+ runLength++;
3185
+ if (runLength > bestLength) {
3186
+ bestLength = runLength;
3187
+ bestStart = runStart;
3187
3188
  }
3188
- consume = consumeIsZone;
3189
3189
  } else {
3190
- buffer.push(cursor);
3190
+ runStart = -1;
3191
+ runLength = 0;
3192
+ }
3193
+ }
3194
+ if (bestLength < 2) return hextets.join(":");
3195
+ const head = hextets.slice(0, bestStart).join(":");
3196
+ const tail = hextets.slice(bestStart + bestLength).join(":");
3197
+ return head + "::" + tail;
3198
+ }
3199
+ function normalizeIPv6Address(input) {
3200
+ const compression = input.indexOf("::");
3201
+ if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0;
3202
+ const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":");
3203
+ const right = compression === -1 ? [] : input.slice(compression + 2).split(":");
3204
+ if (compression !== -1) {
3205
+ if (left.length === 1 && left[0] === "") left.length = 0;
3206
+ if (right.length === 1 && right[0] === "") right.length = 0;
3207
+ }
3208
+ const parts = left.concat(right);
3209
+ let hextetCount = 0;
3210
+ for (let i = 0; i < parts.length; i++) {
3211
+ const part = parts[i];
3212
+ if (part === "") return void 0;
3213
+ if (part.indexOf(".") !== -1) {
3214
+ if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv4(part)) return void 0;
3215
+ hextetCount += 2;
3191
3216
  continue;
3192
3217
  }
3218
+ if (!isHextet(part)) return void 0;
3219
+ parts[i] = parseInt(part, 16).toString(16);
3220
+ hextetCount++;
3193
3221
  }
3194
- if (buffer.length) {
3195
- if (consume === consumeIsZone) {
3196
- output.zone = buffer.join("");
3197
- } else if (endIpv6) {
3198
- address.push(buffer.join(""));
3199
- } else {
3200
- address.push(stringArrayToHexStripped(buffer));
3201
- }
3222
+ if (compression === -1) {
3223
+ if (hextetCount !== 8) return void 0;
3224
+ return compressIPv6ZeroRun(parts);
3202
3225
  }
3203
- output.address = address.join("");
3204
- return output;
3226
+ if (hextetCount >= 8) return void 0;
3227
+ const expanded = parts.slice(0, left.length);
3228
+ for (let i = hextetCount; i < 8; i++) expanded.push("0");
3229
+ for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]);
3230
+ return compressIPv6ZeroRun(expanded);
3205
3231
  }
3206
3232
  function normalizeIPv6(host) {
3207
- if (findToken(host, ":") < 2) {
3208
- return { host, isIPV6: false };
3209
- }
3210
- const ipv63 = getIPV6(host);
3211
- if (!ipv63.error) {
3212
- let newHost = ipv63.address;
3213
- let escapedHost = ipv63.address;
3214
- if (ipv63.zone) {
3215
- newHost += "%" + ipv63.zone;
3216
- escapedHost += "%25" + ipv63.zone;
3217
- }
3218
- return { host: newHost, isIPV6: true, escapedHost };
3219
- } else {
3220
- return { host, isIPV6: false };
3221
- }
3233
+ const bracketed = host[0] === "[" && host[host.length - 1] === "]";
3234
+ const hasBracket = host[0] === "[" || host[host.length - 1] === "]";
3235
+ if (hasBracket && !bracketed) return { host, isIPV6: false, error: true };
3236
+ let input = bracketed ? host.slice(1, -1) : host;
3237
+ if (bracketed && isIPvFuture(input)) {
3238
+ input = input.toLowerCase();
3239
+ return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true };
3240
+ }
3241
+ if (findToken(input, ":") < 2) {
3242
+ return { host, isIPV6: false, error: bracketed };
3243
+ }
3244
+ let zoneIdentifier = "";
3245
+ const zoneSeparator = input.indexOf("%");
3246
+ if (zoneSeparator !== -1) {
3247
+ const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1;
3248
+ zoneIdentifier = input.slice(zoneSeparator + separatorLength);
3249
+ if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true };
3250
+ input = input.slice(0, zoneSeparator);
3251
+ }
3252
+ const address = normalizeIPv6Address(input);
3253
+ if (address === void 0) return { host, isIPV6: false, error: true };
3254
+ return {
3255
+ host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""),
3256
+ escapedHost: address + (zoneIdentifier ? "%25" + zoneIdentifier : ""),
3257
+ isIPV6: true
3258
+ };
3222
3259
  }
3223
3260
  function findToken(str, token) {
3224
3261
  let ind = 0;
@@ -3337,7 +3374,8 @@ var require_utils = __commonJS({
3337
3374
  function normalizePathEncoding(input) {
3338
3375
  let output = "";
3339
3376
  for (let i = 0; i < input.length; i++) {
3340
- if (input[i] === "%" && i + 2 < input.length) {
3377
+ const ch = input[i];
3378
+ if (ch === "%" && i + 2 < input.length) {
3341
3379
  const hex3 = input.slice(i + 1, i + 3);
3342
3380
  if (isHexPair(hex3)) {
3343
3381
  const normalizedHex = hex3.toUpperCase();
@@ -3351,10 +3389,152 @@ var require_utils = __commonJS({
3351
3389
  continue;
3352
3390
  }
3353
3391
  }
3354
- if (isPathCharacter(input[i])) {
3355
- output += input[i];
3392
+ if (isPathCharacter(ch)) {
3393
+ output += ch;
3394
+ } else {
3395
+ const code = input.charCodeAt(i);
3396
+ if (code < 128) {
3397
+ output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
3398
+ } else if (code < 55296 || code > 57343) {
3399
+ output += percentEncodeNonAscii(code);
3400
+ } else if (code <= 56319 && i + 1 < input.length) {
3401
+ const low = input.charCodeAt(i + 1);
3402
+ if (low >= 56320 && low <= 57343) {
3403
+ output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
3404
+ i++;
3405
+ } else {
3406
+ output += percentEncodeNonAscii(65533);
3407
+ }
3408
+ } else {
3409
+ output += percentEncodeNonAscii(65533);
3410
+ }
3411
+ }
3412
+ }
3413
+ return output;
3414
+ }
3415
+ function serializePathEncoding(input, pathNoScheme = false) {
3416
+ let output = "";
3417
+ let firstSegment = pathNoScheme && input[0] !== "/";
3418
+ for (let i = 0; i < input.length; i++) {
3419
+ const ch = input[i];
3420
+ if (ch === "%" && i + 2 < input.length) {
3421
+ const hex3 = input.slice(i + 1, i + 3);
3422
+ if (isHexPair(hex3)) {
3423
+ output += "%" + hex3.toUpperCase();
3424
+ i += 2;
3425
+ continue;
3426
+ }
3427
+ }
3428
+ if (ch === "/") {
3429
+ firstSegment = false;
3430
+ }
3431
+ if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) {
3432
+ output += ch;
3433
+ } else {
3434
+ const code = input.charCodeAt(i);
3435
+ if (code < 128) {
3436
+ output += BYTE_HEX[code];
3437
+ } else if (code < 55296 || code > 57343) {
3438
+ output += percentEncodeNonAscii(code);
3439
+ } else if (code <= 56319 && i + 1 < input.length) {
3440
+ const low = input.charCodeAt(i + 1);
3441
+ if (low >= 56320 && low <= 57343) {
3442
+ output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
3443
+ i++;
3444
+ } else {
3445
+ output += percentEncodeNonAscii(65533);
3446
+ }
3447
+ } else {
3448
+ output += percentEncodeNonAscii(65533);
3449
+ }
3450
+ }
3451
+ }
3452
+ return output;
3453
+ }
3454
+ function encodeComponent(input, isAllowed) {
3455
+ let output = "";
3456
+ for (let i = 0; i < input.length; i++) {
3457
+ const ch = input[i];
3458
+ if (ch === "%" && i + 2 < input.length) {
3459
+ const hex3 = input.slice(i + 1, i + 3);
3460
+ if (isHexPair(hex3)) {
3461
+ output += "%" + hex3.toUpperCase();
3462
+ i += 2;
3463
+ continue;
3464
+ }
3465
+ }
3466
+ if (isAllowed(ch)) {
3467
+ output += ch;
3468
+ } else {
3469
+ const code = input.charCodeAt(i);
3470
+ if (code < 128) {
3471
+ output += BYTE_HEX[code];
3472
+ } else if (code < 55296 || code > 57343) {
3473
+ output += percentEncodeNonAscii(code);
3474
+ } else if (code <= 56319 && i + 1 < input.length) {
3475
+ const low = input.charCodeAt(i + 1);
3476
+ if (low >= 56320 && low <= 57343) {
3477
+ output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
3478
+ i++;
3479
+ } else {
3480
+ output += percentEncodeNonAscii(65533);
3481
+ }
3482
+ } else {
3483
+ output += percentEncodeNonAscii(65533);
3484
+ }
3485
+ }
3486
+ }
3487
+ return output;
3488
+ }
3489
+ function encodeUserinfo(input) {
3490
+ return encodeComponent(input, isUserinfoCharacter);
3491
+ }
3492
+ function encodeQuery(input) {
3493
+ return encodeComponent(input, isQueryFragmentCharacter);
3494
+ }
3495
+ function encodeFragment(input) {
3496
+ return encodeComponent(input, isQueryFragmentCharacter);
3497
+ }
3498
+ function isEscapeSafe(cp) {
3499
+ return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95;
3500
+ }
3501
+ function normalizeQueryFragmentEncoding(input) {
3502
+ let output = "";
3503
+ for (let i = 0; i < input.length; i++) {
3504
+ const ch = input[i];
3505
+ if (ch === "%" && i + 2 < input.length) {
3506
+ const hex3 = input.slice(i + 1, i + 3);
3507
+ if (isHexPair(hex3)) {
3508
+ const normalizedHex = hex3.toUpperCase();
3509
+ const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
3510
+ if (isUnreserved(decoded)) {
3511
+ output += decoded;
3512
+ } else {
3513
+ output += "%" + normalizedHex;
3514
+ }
3515
+ i += 2;
3516
+ continue;
3517
+ }
3518
+ }
3519
+ if (isQueryFragmentCharacter(ch)) {
3520
+ output += ch;
3356
3521
  } else {
3357
- output += escape(input[i]);
3522
+ const code = input.charCodeAt(i);
3523
+ if (code < 128) {
3524
+ output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
3525
+ } else if (code < 55296 || code > 57343) {
3526
+ output += percentEncodeNonAscii(code);
3527
+ } else if (code <= 56319 && i + 1 < input.length) {
3528
+ const low = input.charCodeAt(i + 1);
3529
+ if (low >= 56320 && low <= 57343) {
3530
+ output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
3531
+ i++;
3532
+ } else {
3533
+ output += percentEncodeNonAscii(65533);
3534
+ }
3535
+ } else {
3536
+ output += percentEncodeNonAscii(65533);
3537
+ }
3358
3538
  }
3359
3539
  }
3360
3540
  return output;
@@ -3377,14 +3557,18 @@ var require_utils = __commonJS({
3377
3557
  function recomposeAuthority(component) {
3378
3558
  const uriTokens = [];
3379
3559
  if (component.userinfo !== void 0) {
3380
- uriTokens.push(component.userinfo);
3560
+ uriTokens.push(encodeUserinfo(component.userinfo));
3381
3561
  uriTokens.push("@");
3382
3562
  }
3383
3563
  if (component.host !== void 0) {
3384
- let host = unescape(component.host);
3564
+ let host = component.host;
3385
3565
  if (!isIPv4(host)) {
3386
- const ipV6res = normalizeIPv6(host);
3387
- if (ipV6res.isIPV6 === true) {
3566
+ let ipV6res = normalizeIPv6(host);
3567
+ if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
3568
+ host = normalizePercentEncoding(host, true);
3569
+ ipV6res = normalizeIPv6(host);
3570
+ }
3571
+ if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {
3388
3572
  host = `[${ipV6res.escapedHost}]`;
3389
3573
  } else {
3390
3574
  host = reescapeHostDelimiters(host, false);
@@ -3393,8 +3577,12 @@ var require_utils = __commonJS({
3393
3577
  uriTokens.push(host);
3394
3578
  }
3395
3579
  if (typeof component.port === "number" || typeof component.port === "string") {
3580
+ const port = String(component.port);
3581
+ if (!isPort(port)) {
3582
+ throw new TypeError("URI port is malformed.");
3583
+ }
3396
3584
  uriTokens.push(":");
3397
- uriTokens.push(String(component.port));
3585
+ uriTokens.push(port);
3398
3586
  }
3399
3587
  return uriTokens.length ? uriTokens.join("") : void 0;
3400
3588
  }
@@ -3404,6 +3592,11 @@ var require_utils = __commonJS({
3404
3592
  reescapeHostDelimiters,
3405
3593
  normalizePercentEncoding,
3406
3594
  normalizePathEncoding,
3595
+ serializePathEncoding,
3596
+ normalizeQueryFragmentEncoding,
3597
+ encodeUserinfo,
3598
+ encodeQuery,
3599
+ encodeFragment,
3407
3600
  escapePreservingEscapes,
3408
3601
  removeDotSegments,
3409
3602
  isIPv4,
@@ -3419,7 +3612,7 @@ var require_schemes = __commonJS({
3419
3612
  "node_modules/fast-uri/lib/schemes.js"(exports, module) {
3420
3613
  "use strict";
3421
3614
  var { isUUID } = require_utils();
3422
- var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
3615
+ var URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu;
3423
3616
  var supportedSchemeNames = (
3424
3617
  /** @type {const} */
3425
3618
  [
@@ -3480,9 +3673,10 @@ var require_schemes = __commonJS({
3480
3673
  wsComponent.secure = void 0;
3481
3674
  }
3482
3675
  if (wsComponent.resourceName) {
3483
- const [path, query] = wsComponent.resourceName.split("?");
3676
+ const queryIndex = wsComponent.resourceName.indexOf("?");
3677
+ const path = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
3484
3678
  wsComponent.path = path && path !== "/" ? path : void 0;
3485
- wsComponent.query = query;
3679
+ wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
3486
3680
  wsComponent.resourceName = void 0;
3487
3681
  }
3488
3682
  wsComponent.fragment = void 0;
@@ -3494,7 +3688,7 @@ var require_schemes = __commonJS({
3494
3688
  return urnComponent;
3495
3689
  }
3496
3690
  const matches = urnComponent.path.match(URN_REG);
3497
- if (matches) {
3691
+ if (matches && matches[0] === urnComponent.path) {
3498
3692
  const scheme = options.scheme || urnComponent.scheme || "urn";
3499
3693
  urnComponent.nid = matches[1].toLowerCase();
3500
3694
  urnComponent.nss = matches[2];
@@ -3628,8 +3822,17 @@ var require_schemes = __commonJS({
3628
3822
  var require_fast_uri = __commonJS({
3629
3823
  "node_modules/fast-uri/index.js"(exports, module) {
3630
3824
  "use strict";
3631
- var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
3825
+ var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
3632
3826
  var { SCHEMES, getSchemeHandler } = require_schemes();
3827
+ var VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
3828
+ var MALFORMED_SCHEME_ERROR = "URI scheme is malformed.";
3829
+ function decodeValidScheme(scheme) {
3830
+ const decodedScheme = unescape(String(scheme));
3831
+ if (!VALID_SCHEME.test(decodedScheme)) {
3832
+ throw new TypeError(MALFORMED_SCHEME_ERROR);
3833
+ }
3834
+ return decodedScheme;
3835
+ }
3633
3836
  function normalize(uri, options) {
3634
3837
  if (typeof uri === "string") {
3635
3838
  uri = /** @type {T} */
@@ -3642,7 +3845,34 @@ var require_fast_uri = __commonJS({
3642
3845
  }
3643
3846
  function resolve(baseURI, relativeURI, options) {
3644
3847
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3645
- const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true);
3848
+ const {
3849
+ parsed: baseParsed,
3850
+ malformedAuthorityOrPort: baseMalformed,
3851
+ malformedPercentEncoding: baseMalformedPercentEncoding,
3852
+ malformedSchemeSpecific: baseMalformedSchemeSpecific,
3853
+ malformedHost: baseMalformedHost,
3854
+ malformedScheme: baseMalformedScheme
3855
+ } = parseWithStatus(baseURI, schemelessOptions);
3856
+ const {
3857
+ parsed: relativeParsed,
3858
+ malformedAuthorityOrPort: relativeMalformed,
3859
+ malformedPercentEncoding: relativeMalformedPercentEncoding,
3860
+ malformedSchemeSpecific: relativeMalformedSchemeSpecific,
3861
+ malformedHost: relativeMalformedHost,
3862
+ malformedScheme: relativeMalformedScheme
3863
+ } = parseWithStatus(relativeURI, schemelessOptions);
3864
+ if (baseMalformed || relativeMalformed || baseMalformedPercentEncoding || relativeMalformedPercentEncoding || baseMalformedSchemeSpecific || relativeMalformedSchemeSpecific || baseMalformedHost || relativeMalformedHost || baseMalformedScheme || relativeMalformedScheme) {
3865
+ throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");
3866
+ }
3867
+ const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
3868
+ const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme);
3869
+ const resolvedHost = resolved.host;
3870
+ const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
3871
+ canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
3872
+ const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !new RegExp("\\P{ASCII}", "u").test(resolvedHost);
3873
+ if (resolved.error && !encodedASCIIHost) {
3874
+ throw new Error(resolved.error);
3875
+ }
3646
3876
  schemelessOptions.skipEscape = true;
3647
3877
  return serialize(resolved, schemelessOptions);
3648
3878
  }
@@ -3702,7 +3932,7 @@ var require_fast_uri = __commonJS({
3702
3932
  function equal(uriA, uriB, options) {
3703
3933
  const normalizedA = normalizeComparableURI(uriA, options);
3704
3934
  const normalizedB = normalizeComparableURI(uriB, options);
3705
- return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA.toLowerCase() === normalizedB.toLowerCase();
3935
+ return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB;
3706
3936
  }
3707
3937
  function serialize(cmpts, opts) {
3708
3938
  const component = {
@@ -3723,19 +3953,22 @@ var require_fast_uri = __commonJS({
3723
3953
  };
3724
3954
  const options = Object.assign({}, opts);
3725
3955
  const uriTokens = [];
3956
+ if (component.scheme) {
3957
+ component.scheme = decodeValidScheme(component.scheme);
3958
+ }
3726
3959
  const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
3727
3960
  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
3961
+ const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0;
3962
+ const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority;
3728
3963
  if (component.path !== void 0) {
3729
3964
  if (!options.skipEscape) {
3730
- component.path = escapePreservingEscapes(component.path);
3731
- if (component.scheme !== void 0) {
3732
- component.path = component.path.split("%3A").join(":");
3733
- }
3965
+ component.path = serializePathEncoding(component.path, pathNoScheme);
3734
3966
  } else {
3735
3967
  component.path = normalizePercentEncoding(component.path);
3736
3968
  }
3737
3969
  }
3738
3970
  if (options.reference !== "suffix" && component.scheme) {
3971
+ component.scheme = decodeValidScheme(component.scheme);
3739
3972
  uriTokens.push(component.scheme, ":");
3740
3973
  }
3741
3974
  const authority = recomposeAuthority(component);
@@ -3753,20 +3986,25 @@ var require_fast_uri = __commonJS({
3753
3986
  if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
3754
3987
  s = removeDotSegments(s);
3755
3988
  }
3989
+ if (pathNoScheme) {
3990
+ s = serializePathEncoding(s, true);
3991
+ }
3756
3992
  if (authority === void 0 && s[0] === "/" && s[1] === "/") {
3757
3993
  s = "/%2F" + s.slice(2);
3758
3994
  }
3759
3995
  uriTokens.push(s);
3760
3996
  }
3761
3997
  if (component.query !== void 0) {
3762
- uriTokens.push("?", component.query);
3998
+ uriTokens.push("?", encodeQuery(component.query));
3763
3999
  }
3764
4000
  if (component.fragment !== void 0) {
3765
- uriTokens.push("#", component.fragment);
4001
+ uriTokens.push("#", encodeFragment(component.fragment));
3766
4002
  }
3767
4003
  return uriTokens.join("");
3768
4004
  }
3769
4005
  var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
4006
+ var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
4007
+ var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
3770
4008
  function getParseError(parsed, matches) {
3771
4009
  if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {
3772
4010
  return 'URI path must start with "/" when authority is present.';
@@ -3776,6 +4014,35 @@ var require_fast_uri = __commonJS({
3776
4014
  }
3777
4015
  return void 0;
3778
4016
  }
4017
+ function hasMalformedPercentEncoding(component) {
4018
+ if (component === void 0) return false;
4019
+ let percent = component.indexOf("%");
4020
+ while (percent !== -1) {
4021
+ if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {
4022
+ return true;
4023
+ }
4024
+ percent = component.indexOf("%", percent + 3);
4025
+ }
4026
+ return false;
4027
+ }
4028
+ function isIPLiteral(host) {
4029
+ return host[0] === "[" && host[host.length - 1] === "]";
4030
+ }
4031
+ function hasMalformedComponentPercentEncoding(matches) {
4032
+ const host = matches[4];
4033
+ return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !isIPLiteral(host) && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]);
4034
+ }
4035
+ function canonicalizeHost(parsed, options, schemeHandler, isIP) {
4036
+ if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
4037
+ try {
4038
+ parsed.host = new URL("http://" + parsed.host).hostname;
4039
+ } catch (e) {
4040
+ parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
4041
+ return true;
4042
+ }
4043
+ }
4044
+ return false;
4045
+ }
3779
4046
  function parseWithStatus(uri, opts) {
3780
4047
  const options = Object.assign({}, opts);
3781
4048
  const parsed = {
@@ -3788,6 +4055,11 @@ var require_fast_uri = __commonJS({
3788
4055
  fragment: void 0
3789
4056
  };
3790
4057
  let malformedAuthorityOrPort = false;
4058
+ let malformedPercentEncoding = false;
4059
+ let malformedSchemeSpecific = false;
4060
+ let malformedHost = false;
4061
+ let malformedIPLiteral = false;
4062
+ let malformedScheme = false;
3791
4063
  let isIP = false;
3792
4064
  if (options.reference === "suffix") {
3793
4065
  if (options.scheme) {
@@ -3796,6 +4068,25 @@ var require_fast_uri = __commonJS({
3796
4068
  uri = "//" + uri;
3797
4069
  }
3798
4070
  }
4071
+ const authorityMatch = uri.match(AUTHORITY_PREFIX);
4072
+ if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) {
4073
+ parsed.error = "URI authority must not contain a literal backslash.";
4074
+ malformedAuthorityOrPort = true;
4075
+ }
4076
+ const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
4077
+ if (introducerMatch !== null) {
4078
+ const region = introducerMatch[1];
4079
+ const normalizedRegion = region.replace(/[\t\n\r]/g, "");
4080
+ if (normalizedRegion.length >= 2) {
4081
+ if (normalizedRegion.slice(0, 2) !== "//") {
4082
+ parsed.error = parsed.error || "URI authority must not contain a literal backslash.";
4083
+ malformedAuthorityOrPort = true;
4084
+ } else if (region.length !== normalizedRegion.length) {
4085
+ parsed.error = parsed.error || "URI authority introducer must not contain whitespace.";
4086
+ malformedAuthorityOrPort = true;
4087
+ }
4088
+ }
4089
+ }
3799
4090
  const matches = uri.match(URI_PARSE);
3800
4091
  if (matches) {
3801
4092
  parsed.scheme = matches[1];
@@ -3805,6 +4096,19 @@ var require_fast_uri = __commonJS({
3805
4096
  parsed.path = matches[6] || "";
3806
4097
  parsed.query = matches[7];
3807
4098
  parsed.fragment = matches[8];
4099
+ if (parsed.scheme !== void 0) {
4100
+ const decodedScheme = unescape(parsed.scheme);
4101
+ if (VALID_SCHEME.test(decodedScheme)) {
4102
+ parsed.scheme = decodedScheme.toLowerCase();
4103
+ } else {
4104
+ parsed.error = parsed.error || MALFORMED_SCHEME_ERROR;
4105
+ malformedScheme = true;
4106
+ }
4107
+ }
4108
+ malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches);
4109
+ if (malformedPercentEncoding) {
4110
+ parsed.error = parsed.error || "URI contains malformed percent-encoding.";
4111
+ }
3808
4112
  if (isNaN(parsed.port)) {
3809
4113
  parsed.port = matches[5];
3810
4114
  }
@@ -3816,9 +4120,16 @@ var require_fast_uri = __commonJS({
3816
4120
  if (parsed.host) {
3817
4121
  const ipv4result = isIPv4(parsed.host);
3818
4122
  if (ipv4result === false) {
4123
+ const bracketedIPLiteral = isIPLiteral(parsed.host);
4124
+ const hasIPLiteralBracket = parsed.host.indexOf("[") !== -1 || parsed.host.indexOf("]") !== -1;
3819
4125
  const ipv6result = normalizeIPv6(parsed.host);
3820
- parsed.host = ipv6result.host.toLowerCase();
3821
- isIP = ipv6result.isIPV6;
4126
+ isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true;
4127
+ malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true);
4128
+ parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
4129
+ if (malformedIPLiteral) {
4130
+ parsed.error = parsed.error || "URI host is malformed.";
4131
+ malformedAuthorityOrPort = true;
4132
+ }
3822
4133
  } else {
3823
4134
  isIP = true;
3824
4135
  }
@@ -3836,42 +4147,37 @@ var require_fast_uri = __commonJS({
3836
4147
  parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
3837
4148
  }
3838
4149
  const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
3839
- if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
3840
- if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
3841
- try {
3842
- parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
3843
- } catch (e) {
3844
- parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
3845
- }
4150
+ if (!malformedIPLiteral) {
4151
+ malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
4152
+ }
4153
+ if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) {
4154
+ let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
4155
+ if (!isIP) {
4156
+ host = normalizePercentEncoding(host.toLowerCase());
3846
4157
  }
4158
+ parsed.host = reescapeHostDelimiters(host, isIP);
3847
4159
  }
3848
4160
  if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
3849
- if (uri.indexOf("%") !== -1) {
3850
- if (parsed.scheme !== void 0) {
3851
- parsed.scheme = unescape(parsed.scheme);
3852
- }
3853
- if (parsed.host !== void 0) {
3854
- parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);
3855
- }
3856
- }
3857
4161
  if (parsed.path) {
3858
4162
  parsed.path = normalizePathEncoding(parsed.path);
3859
4163
  }
4164
+ if (parsed.query) {
4165
+ parsed.query = normalizeQueryFragmentEncoding(parsed.query);
4166
+ }
3860
4167
  if (parsed.fragment) {
3861
- try {
3862
- parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
3863
- } catch {
3864
- parsed.error = parsed.error || "URI malformed";
3865
- }
4168
+ parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment);
3866
4169
  }
3867
4170
  }
3868
4171
  if (schemeHandler && schemeHandler.parse) {
3869
4172
  schemeHandler.parse(parsed, options);
4173
+ if (schemeHandler === SCHEMES.urn && parsed.nid === void 0) {
4174
+ malformedSchemeSpecific = true;
4175
+ }
3870
4176
  }
3871
4177
  } else {
3872
4178
  parsed.error = parsed.error || "URI can not be parsed.";
3873
4179
  }
3874
- return { parsed, malformedAuthorityOrPort };
4180
+ return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme };
3875
4181
  }
3876
4182
  function parse3(uri, opts) {
3877
4183
  return parseWithStatus(uri, opts).parsed;
@@ -3880,20 +4186,28 @@ var require_fast_uri = __commonJS({
3880
4186
  return normalizeStringWithStatus(uri, opts).normalized;
3881
4187
  }
3882
4188
  function normalizeStringWithStatus(uri, opts) {
3883
- const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts);
4189
+ const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts);
3884
4190
  return {
3885
- normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),
3886
- malformedAuthorityOrPort
4191
+ normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
4192
+ malformedAuthorityOrPort,
4193
+ malformedPercentEncoding,
4194
+ malformedSchemeSpecific,
4195
+ malformedHost,
4196
+ malformedScheme
3887
4197
  };
3888
4198
  }
3889
4199
  function normalizeComparableURI(uri, opts) {
3890
- if (typeof uri === "string") {
3891
- const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts);
3892
- return malformedAuthorityOrPort ? void 0 : normalized;
4200
+ if (typeof uri !== "string" && typeof uri !== "object") {
4201
+ return void 0;
3893
4202
  }
3894
- if (typeof uri === "object") {
3895
- return serialize(uri, opts);
4203
+ let value;
4204
+ try {
4205
+ value = typeof uri === "string" ? uri : serialize(uri, opts);
4206
+ } catch {
4207
+ return void 0;
3896
4208
  }
4209
+ const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts);
4210
+ return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? void 0 : normalized;
3897
4211
  }
3898
4212
  var fastUri = {
3899
4213
  SCHEMES,
@@ -4321,8 +4635,8 @@ var require_core = __commonJS({
4321
4635
  for (const jsonPointer of keywordsJsonPointers) {
4322
4636
  const segments = jsonPointer.split("/").slice(1);
4323
4637
  let keywords = metaSchema;
4324
- for (const seg6 of segments)
4325
- keywords = keywords[seg6];
4638
+ for (const seg2 of segments)
4639
+ keywords = keywords[seg2];
4326
4640
  for (const key in rules) {
4327
4641
  const rule = rules[key];
4328
4642
  if (typeof rule != "object")
@@ -11927,18 +12241,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
11927
12241
  }
11928
12242
  function toDotPath(_path) {
11929
12243
  const segs = [];
11930
- const path = _path.map((seg6) => typeof seg6 === "object" ? seg6.key : seg6);
11931
- for (const seg6 of path) {
11932
- if (typeof seg6 === "number")
11933
- segs.push(`[${seg6}]`);
11934
- else if (typeof seg6 === "symbol")
11935
- segs.push(`[${JSON.stringify(String(seg6))}]`);
11936
- else if (/[^\w$]/.test(seg6))
11937
- segs.push(`[${JSON.stringify(seg6)}]`);
12244
+ const path = _path.map((seg2) => typeof seg2 === "object" ? seg2.key : seg2);
12245
+ for (const seg2 of path) {
12246
+ if (typeof seg2 === "number")
12247
+ segs.push(`[${seg2}]`);
12248
+ else if (typeof seg2 === "symbol")
12249
+ segs.push(`[${JSON.stringify(String(seg2))}]`);
12250
+ else if (/[^\w$]/.test(seg2))
12251
+ segs.push(`[${JSON.stringify(seg2)}]`);
11938
12252
  else {
11939
12253
  if (segs.length)
11940
12254
  segs.push(".");
11941
- segs.push(seg6);
12255
+ segs.push(seg2);
11942
12256
  }
11943
12257
  }
11944
12258
  return segs.join("");
@@ -23040,17 +23354,33 @@ function normalizeObjectSchema(schema) {
23040
23354
  }
23041
23355
  return void 0;
23042
23356
  }
23357
+ function getDotPath(path) {
23358
+ if (path.length === 0) {
23359
+ return "object root";
23360
+ }
23361
+ return path.reduce((acc, seg2, index) => {
23362
+ if (index === 0) {
23363
+ return String(seg2);
23364
+ }
23365
+ if (typeof seg2 === "number") {
23366
+ return `${acc}[${seg2}]`;
23367
+ }
23368
+ return `${acc}.${seg2}`;
23369
+ }, "");
23370
+ }
23043
23371
  function getParseErrorMessage(error51) {
23044
23372
  if (error51 && typeof error51 === "object") {
23373
+ if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
23374
+ return error51.issues.map((i) => {
23375
+ if (!i.path?.length) {
23376
+ return i.message;
23377
+ }
23378
+ return `${i.message} at ${getDotPath(i.path)}`;
23379
+ }).join("\n");
23380
+ }
23045
23381
  if ("message" in error51 && typeof error51.message === "string") {
23046
23382
  return error51.message;
23047
23383
  }
23048
- if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
23049
- const firstIssue = error51.issues[0];
23050
- if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) {
23051
- return String(firstIssue.message);
23052
- }
23053
- }
23054
23384
  try {
23055
23385
  return JSON.stringify(error51);
23056
23386
  } catch {
@@ -28370,6 +28700,9 @@ var Protocol = class {
28370
28700
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
28371
28701
  const handleTaskResult = async () => {
28372
28702
  const taskId = request.params.taskId;
28703
+ if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
28704
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
28705
+ }
28373
28706
  if (this._taskMessageQueue) {
28374
28707
  let queuedMessage;
28375
28708
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
@@ -28400,12 +28733,12 @@ var Protocol = class {
28400
28733
  throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
28401
28734
  }
28402
28735
  if (!isTerminal(task.status)) {
28403
- await this._waitForTaskUpdate(taskId, extra.signal);
28736
+ await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
28404
28737
  return await handleTaskResult();
28405
28738
  }
28406
28739
  if (isTerminal(task.status)) {
28407
28740
  const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
28408
- this._clearTaskQueue(taskId);
28741
+ this._clearTaskQueue(taskId, extra.sessionId);
28409
28742
  return {
28410
28743
  ...result,
28411
28744
  _meta: {
@@ -28442,7 +28775,7 @@ var Protocol = class {
28442
28775
  throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
28443
28776
  }
28444
28777
  await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
28445
- this._clearTaskQueue(request.params.taskId);
28778
+ this._clearTaskQueue(request.params.taskId, extra.sessionId);
28446
28779
  const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
28447
28780
  if (!cancelledTask) {
28448
28781
  throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
@@ -28570,6 +28903,19 @@ var Protocol = class {
28570
28903
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
28571
28904
  const capturedTransport = this._transport;
28572
28905
  const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
28906
+ const sessionId = capturedTransport?.sessionId;
28907
+ const store = this._taskStore;
28908
+ let relatedTaskFound = true;
28909
+ let relatedTaskLookup;
28910
+ if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
28911
+ relatedTaskFound = false;
28912
+ relatedTaskLookup = (async () => {
28913
+ if (!await store.getTask(relatedTaskId, sessionId)) {
28914
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
28915
+ }
28916
+ relatedTaskFound = true;
28917
+ })();
28918
+ }
28573
28919
  if (handler === void 0) {
28574
28920
  const errorResponse = {
28575
28921
  jsonrpc: "2.0",
@@ -28579,7 +28925,10 @@ var Protocol = class {
28579
28925
  message: "Method not found"
28580
28926
  }
28581
28927
  };
28582
- if (relatedTaskId && this._taskMessageQueue) {
28928
+ if (relatedTaskId && relatedTaskLookup) {
28929
+ const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
28930
+ relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error51) => this._onerror(new Error(`Failed to send an error response: ${error51}`)));
28931
+ } else if (relatedTaskId && this._taskMessageQueue) {
28583
28932
  this._enqueueTaskMessage(relatedTaskId, {
28584
28933
  type: "error",
28585
28934
  message: errorResponse,
@@ -28630,7 +28979,10 @@ var Protocol = class {
28630
28979
  closeSSEStream: extra?.closeSSEStream,
28631
28980
  closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
28632
28981
  };
28633
- Promise.resolve().then(() => {
28982
+ (relatedTaskLookup ?? Promise.resolve()).then(() => {
28983
+ if (relatedTaskLookup && abortController.signal.aborted) {
28984
+ throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
28985
+ }
28634
28986
  if (taskCreationParams) {
28635
28987
  this.assertTaskHandlerCapability(request.method);
28636
28988
  }
@@ -28665,7 +29017,7 @@ var Protocol = class {
28665
29017
  ...error51["data"] !== void 0 && { data: error51["data"] }
28666
29018
  }
28667
29019
  };
28668
- if (relatedTaskId && this._taskMessageQueue) {
29020
+ if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
28669
29021
  await this._enqueueTaskMessage(relatedTaskId, {
28670
29022
  type: "error",
28671
29023
  message: errorResponse,
@@ -29145,7 +29497,7 @@ var Protocol = class {
29145
29497
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
29146
29498
  }
29147
29499
  const maxQueueSize = this._options?.maxTaskQueueSize;
29148
- await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
29500
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
29149
29501
  }
29150
29502
  /**
29151
29503
  * Clears the message queue for a task and rejects any pending request resolvers.
@@ -29174,12 +29526,13 @@ var Protocol = class {
29174
29526
  * Uses polling to check for updates at the task's configured poll interval.
29175
29527
  * @param taskId The task ID to wait for
29176
29528
  * @param signal Abort signal to cancel the wait
29529
+ * @param sessionId Session of the request that waits, passed to the task store
29177
29530
  * @returns Promise that resolves when an update occurs or rejects if aborted
29178
29531
  */
29179
- async _waitForTaskUpdate(taskId, signal) {
29532
+ async _waitForTaskUpdate(taskId, signal, sessionId) {
29180
29533
  let interval = this._options?.defaultTaskPollInterval ?? 1e3;
29181
29534
  try {
29182
- const task = await this._taskStore?.getTask(taskId);
29535
+ const task = await this._taskStore?.getTask(taskId, sessionId);
29183
29536
  if (task?.pollInterval) {
29184
29537
  interval = task.pollInterval;
29185
29538
  }
@@ -29665,16 +30018,7 @@ var Server = class extends Protocol {
29665
30018
  if (!methodSchema) {
29666
30019
  throw new Error("Schema is missing a method literal");
29667
30020
  }
29668
- let methodValue;
29669
- if (isZ4Schema(methodSchema)) {
29670
- const v4Schema = methodSchema;
29671
- const v4Def = v4Schema._zod?.def;
29672
- methodValue = v4Def?.value ?? v4Schema.value;
29673
- } else {
29674
- const v3Schema = methodSchema;
29675
- const legacyDef = v3Schema._def;
29676
- methodValue = legacyDef?.value ?? v3Schema.value;
29677
- }
30021
+ const methodValue = getLiteralValue(methodSchema);
29678
30022
  if (typeof methodValue !== "string") {
29679
30023
  throw new Error("Schema method literal must be a string");
29680
30024
  }
@@ -30067,6 +30411,42 @@ var ExperimentalMcpServerTasks = class {
30067
30411
  };
30068
30412
 
30069
30413
  // node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
30414
+ function toolInputElementCount(value, max) {
30415
+ let count = 0;
30416
+ const stack = [value];
30417
+ while (stack.length > 0) {
30418
+ const node = stack.pop();
30419
+ if (node === null || typeof node !== "object")
30420
+ continue;
30421
+ if (Array.isArray(node)) {
30422
+ for (const child of node) {
30423
+ if (++count > max)
30424
+ return count;
30425
+ if (child !== null && typeof child === "object")
30426
+ stack.push(child);
30427
+ }
30428
+ } else {
30429
+ for (const key in node) {
30430
+ if (!Object.prototype.hasOwnProperty.call(node, key))
30431
+ continue;
30432
+ if (++count > max)
30433
+ return count;
30434
+ const child = node[key];
30435
+ if (child !== null && typeof child === "object")
30436
+ stack.push(child);
30437
+ }
30438
+ }
30439
+ }
30440
+ return count;
30441
+ }
30442
+ function resolveMaxToolInputElements(value) {
30443
+ if (value === void 0 || value === Infinity)
30444
+ return void 0;
30445
+ if (typeof value !== "number" || Number.isNaN(value) || value < 1) {
30446
+ throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);
30447
+ }
30448
+ return value;
30449
+ }
30070
30450
  var McpServer = class {
30071
30451
  constructor(serverInfo, options) {
30072
30452
  this._registeredResources = {};
@@ -30078,6 +30458,7 @@ var McpServer = class {
30078
30458
  this._resourceHandlersInitialized = false;
30079
30459
  this._promptHandlersInitialized = false;
30080
30460
  this.server = new Server(serverInfo, options);
30461
+ this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements);
30081
30462
  }
30082
30463
  /**
30083
30464
  * Access experimental features.
@@ -30208,12 +30589,15 @@ var McpServer = class {
30208
30589
  * Validates tool input arguments against the tool's input schema.
30209
30590
  */
30210
30591
  async validateToolInput(tool, args, toolName) {
30592
+ if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) {
30593
+ throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
30594
+ }
30211
30595
  if (!tool.inputSchema) {
30212
30596
  return void 0;
30213
30597
  }
30214
30598
  const inputObj = normalizeObjectSchema(tool.inputSchema);
30215
30599
  const schemaToParse = inputObj ?? tool.inputSchema;
30216
- const parseResult = await safeParseAsync2(schemaToParse, args);
30600
+ const parseResult = await safeParseAsync2(schemaToParse, args ?? {});
30217
30601
  if (!parseResult.success) {
30218
30602
  const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
30219
30603
  const errorMessage = getParseErrorMessage(error51);
@@ -30451,7 +30835,7 @@ var McpServer = class {
30451
30835
  }
30452
30836
  if (prompt.argsSchema) {
30453
30837
  const argsObj = normalizeObjectSchema(prompt.argsSchema);
30454
- const parseResult = await safeParseAsync2(argsObj, request.params.arguments);
30838
+ const parseResult = await safeParseAsync2(argsObj, request.params.arguments ?? {});
30455
30839
  if (!parseResult.success) {
30456
30840
  const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
30457
30841
  const errorMessage = getParseErrorMessage(error51);
@@ -30862,8 +31246,17 @@ var EMPTY_COMPLETION_RESULT = {
30862
31246
  import process3 from "node:process";
30863
31247
 
30864
31248
  // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
31249
+ var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
30865
31250
  var ReadBuffer = class {
31251
+ constructor(options) {
31252
+ this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
31253
+ }
30866
31254
  append(chunk) {
31255
+ const newSize = (this._buffer?.length ?? 0) + chunk.length;
31256
+ if (newSize > this._maxBufferSize) {
31257
+ this.clear();
31258
+ throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
31259
+ }
30867
31260
  this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
30868
31261
  }
30869
31262
  readMessage() {
@@ -30891,18 +31284,24 @@ function serializeMessage(message) {
30891
31284
 
30892
31285
  // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
30893
31286
  var StdioServerTransport = class {
30894
- constructor(_stdin = process3.stdin, _stdout = process3.stdout) {
31287
+ constructor(_stdin = process3.stdin, _stdout = process3.stdout, options) {
30895
31288
  this._stdin = _stdin;
30896
31289
  this._stdout = _stdout;
30897
- this._readBuffer = new ReadBuffer();
30898
31290
  this._started = false;
30899
31291
  this._ondata = (chunk) => {
30900
- this._readBuffer.append(chunk);
30901
- this.processReadBuffer();
31292
+ try {
31293
+ this._readBuffer.append(chunk);
31294
+ this.processReadBuffer();
31295
+ } catch (error51) {
31296
+ this.onerror?.(error51);
31297
+ this.close().catch(() => {
31298
+ });
31299
+ }
30902
31300
  };
30903
31301
  this._onerror = (error51) => {
30904
31302
  this.onerror?.(error51);
30905
31303
  };
31304
+ this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
30906
31305
  }
30907
31306
  /**
30908
31307
  * Starts listening for messages on stdin.
@@ -30954,11 +31353,14 @@ var StdioServerTransport = class {
30954
31353
  import { AsyncLocalStorage } from "node:async_hooks";
30955
31354
  import { createHash, randomBytes } from "node:crypto";
30956
31355
  var SOFT_DEADLINE_CAP_MS = 25e3;
30957
- function parseSoftDeadline(raw) {
30958
- if (raw === void 0) return 2e4;
31356
+ function parsePositiveInt(raw, fallback) {
31357
+ if (raw === void 0 || !/^\d+$/.test(raw)) return fallback;
30959
31358
  const n = Number(raw);
30960
- if (!Number.isSafeInteger(n) || n <= 0) return 2e4;
30961
- return Math.min(n, SOFT_DEADLINE_CAP_MS);
31359
+ if (!Number.isSafeInteger(n) || n <= 0 || n > 2147483647) return fallback;
31360
+ return n;
31361
+ }
31362
+ function parseSoftDeadline(raw) {
31363
+ return Math.min(parsePositiveInt(raw, 2e4), SOFT_DEADLINE_CAP_MS);
30962
31364
  }
30963
31365
  var SOFT_DEADLINE_MS = parseSoftDeadline(process.env.TIA_SOFT_DEADLINE_MS);
30964
31366
  var MAX_STATUS_WAIT_MS = 25e3;
@@ -31186,9 +31588,9 @@ var jobs = new JobRunner();
31186
31588
 
31187
31589
  // src/client.ts
31188
31590
  var BASE = (process.env.TIA_API_BASE ?? "http://localhost:5000").replace(/\/+$/, "");
31189
- var TIMEOUT_MS = Number.parseInt(process.env.TIA_API_TIMEOUT_MS ?? "15000", 10) || 15e3;
31190
- var CONNECT_TIMEOUT_MS = Number.parseInt(process.env.TIA_CONNECT_TIMEOUT_MS ?? "180000", 10) || 18e4;
31191
- var SLOW_TIMEOUT_MS = Number.parseInt(process.env.TIA_SLOW_TIMEOUT_MS ?? "120000", 10) || 12e4;
31591
+ var TIMEOUT_MS = parsePositiveInt(process.env.TIA_API_TIMEOUT_MS, 15e3);
31592
+ var CONNECT_TIMEOUT_MS = parsePositiveInt(process.env.TIA_CONNECT_TIMEOUT_MS, 18e4);
31593
+ var SLOW_TIMEOUT_MS = parsePositiveInt(process.env.TIA_SLOW_TIMEOUT_MS, 12e4);
31192
31594
  var TiaApiError = class extends Error {
31193
31595
  status;
31194
31596
  kind;
@@ -31260,6 +31662,7 @@ async function tiaFetch(path, init = {}, opts = {}) {
31260
31662
  }
31261
31663
  return body;
31262
31664
  }
31665
+ var INSTALLING_HINT = "The serve host is installing a TIAOpenness app update: this call was refused BEFORE any operation ran (nothing changed). Wait until the update finishes, then retry the same call (GET /status stays available while draining \u2014 retry once it reports draining:false).";
31263
31666
  function hintFor(err) {
31264
31667
  switch (err.kind) {
31265
31668
  case "timeout":
@@ -31284,28 +31687,145 @@ function hintFor(err) {
31284
31687
  return "Update the TIAOpenness app (serve) on the host to v1.6.0 or later; this MCP refuses unverified downloads.";
31285
31688
  case "route_not_found":
31286
31689
  return "This serve does not know this route \u2014 update the TIAOpenness app on the host to the version the tool requires.";
31690
+ case "installing":
31691
+ return INSTALLING_HINT;
31287
31692
  }
31288
31693
  if (err.status === 403) return "Server not activated \u2014 configure the license in the TIAOpenness GUI.";
31289
31694
  return null;
31290
31695
  }
31291
- function textResult(payload, isError = false) {
31292
- return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }], isError };
31293
- }
31294
31696
  function asTiaError(e) {
31295
31697
  return e instanceof TiaApiError ? e : new TiaApiError(String(e));
31296
31698
  }
31297
31699
 
31298
- // src/tools/readonly.ts
31700
+ // src/tools/results.ts
31701
+ function textResult(payload, isError = false) {
31702
+ return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }], isError };
31703
+ }
31704
+ var seg = (v) => encodeURIComponent(v);
31705
+ var JSON_HEADERS = { "Content-Type": "application/json; charset=utf-8" };
31706
+ function jsonBody(obj) {
31707
+ const out = {};
31708
+ for (const [k, v] of Object.entries(obj)) if (v !== void 0 && v !== null) out[k] = v;
31709
+ return out;
31710
+ }
31711
+ var isObject2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
31712
+ function isInstallingError(err) {
31713
+ return err.kind === "installing";
31714
+ }
31715
+ function installingResult(err, hintOverride) {
31716
+ return textResult(
31717
+ {
31718
+ error: "The serve host is installing a TIAOpenness app update (draining): this call was refused BEFORE any operation ran \u2014 nothing changed. Wait until the update finishes, then retry the same call.",
31719
+ kind: err.kind,
31720
+ status: err.status,
31721
+ type: err.type,
31722
+ inner: err.inner ?? null,
31723
+ details: err.details ?? null,
31724
+ hint: hintOverride ?? hintFor(err)
31725
+ },
31726
+ true
31727
+ );
31728
+ }
31729
+ function errorResult(err, hintOverride) {
31730
+ if (isInstallingError(err)) return installingResult(err, hintOverride);
31731
+ return textResult(
31732
+ { error: err.message, kind: err.kind, status: err.status, type: err.type, inner: err.inner ?? null, details: err.details ?? null, hint: hintOverride ?? hintFor(err) },
31733
+ true
31734
+ );
31735
+ }
31299
31736
  async function getResult(path, timeoutMs) {
31300
31737
  try {
31301
31738
  const data = await tiaFetch(path, {}, { timeoutMs });
31302
31739
  return textResult(data);
31740
+ } catch (e) {
31741
+ return errorResult(asTiaError(e));
31742
+ }
31743
+ }
31744
+ async function postResult(path, body, opts) {
31745
+ try {
31746
+ const data = await tiaFetch(
31747
+ path,
31748
+ { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body ?? {}) },
31749
+ { timeoutMs: opts?.timeoutMs ?? SLOW_TIMEOUT_MS }
31750
+ );
31751
+ return textResult(data);
31303
31752
  } catch (e) {
31304
31753
  const err = asTiaError(e);
31305
- return textResult({ error: err.message, kind: err.kind, status: err.status, details: err.details ?? null, hint: hintFor(err) }, true);
31754
+ if (opts?.mapError) return opts.mapError(err);
31755
+ return errorResult(err);
31306
31756
  }
31307
31757
  }
31308
- var seg = (v) => encodeURIComponent(v);
31758
+ async function send(method, path, body, timeoutMs) {
31759
+ try {
31760
+ const init = { method, headers: JSON_HEADERS };
31761
+ if (body !== void 0) init.body = JSON.stringify(body);
31762
+ return textResult(await tiaFetch(path, init, { timeoutMs: timeoutMs ?? SLOW_TIMEOUT_MS }));
31763
+ } catch (e) {
31764
+ return errorResult(asTiaError(e));
31765
+ }
31766
+ }
31767
+
31768
+ // src/tools/diagnostics.ts
31769
+ function registerDiagnosticTools(server2) {
31770
+ server2.registerTool(
31771
+ "tia_ping",
31772
+ {
31773
+ title: "TIA \u2014 connection diagnostics",
31774
+ description: "Diagnoses connectivity to the TIA Openness `serve` API and whether the server is ACTIVATED. Tests GET /health (reachability) and GET /readiness (license activation). Ideal for the MCP-on-Mac-pointing-at-a-`serve`-on-a-Windows-VM scenario. Read-only. Returns { base, reachable, activated, latencyMs, hint }.",
31775
+ inputSchema: {}
31776
+ },
31777
+ async () => {
31778
+ const report = {
31779
+ base: BASE,
31780
+ timeoutMs: TIMEOUT_MS,
31781
+ reachable: false,
31782
+ activated: null,
31783
+ latencyMs: null,
31784
+ detail: null,
31785
+ hint: null
31786
+ };
31787
+ const start = Date.now();
31788
+ try {
31789
+ await tiaFetch("/health");
31790
+ report.reachable = true;
31791
+ report.latencyMs = Date.now() - start;
31792
+ } catch (e) {
31793
+ const err = asTiaError(e);
31794
+ report.detail = err.message;
31795
+ report.hint = hintFor(err);
31796
+ return textResult(report);
31797
+ }
31798
+ try {
31799
+ await tiaFetch("/readiness");
31800
+ report.activated = true;
31801
+ } catch (e) {
31802
+ const err = asTiaError(e);
31803
+ report.activated = err.kind === "license_required" || err.status === 403 ? false : null;
31804
+ report.detail = err.message;
31805
+ report.hint = hintFor(err);
31806
+ }
31807
+ return textResult(report);
31808
+ }
31809
+ );
31810
+ server2.registerTool(
31811
+ "tia_readiness",
31812
+ {
31813
+ title: "TIA \u2014 environment readiness",
31814
+ description: "Readiness diagnostic for the TIA Openness V21 environment ON THE SERVE HOST (x64 process, Windows 'Siemens TIA Openness' group, PublicAPI, 21.0 registry key, and TIA instances). Call BEFORE connecting. Maps to GET /readiness. Read-only (class R). Returns { ready, checks:[{ name, status, detail, remediation }] }.",
31815
+ inputSchema: {}
31816
+ },
31817
+ async () => {
31818
+ try {
31819
+ const data = await tiaFetch("/readiness");
31820
+ return textResult(data);
31821
+ } catch (e) {
31822
+ return errorResult(asTiaError(e));
31823
+ }
31824
+ }
31825
+ );
31826
+ }
31827
+
31828
+ // src/tools/readonly.ts
31309
31829
  async function pgInterfacesFlow(plc) {
31310
31830
  return getResult(`/plcs/${seg(plc)}/pginterfaces`);
31311
31831
  }
@@ -31566,7 +32086,7 @@ function registerJobTools(server2) {
31566
32086
  "tia_job_status",
31567
32087
  {
31568
32088
  title: "TIA \u2014 long-operation status",
31569
- description: 'Waits (up to waitSeconds, default 20, max 25) for a background job started by a long tool that answered status:"running" (tia_connect, tia_start, tia_show_ui, tia_project_create/save/close/archive, tia_compile, tia_download, tia_upload, tia_export_xml, tia_export_block, tia_block_compare, tia_spec_apply) and returns its FINAL result with job:{id,tool,state,durationMs} \u2014 including a gate handoff if the operation ended in one. While a job runs, every other serve-bound tool answers kind:"busy" (with details.jobId): call this instead of polling tia_status, and never repeat the original call. If a tia_connect/tia_start/tia_show_ui job stays running for minutes, a trust dialog (GATE G1) may be waiting on the serve host \u2014 ask a human to look. Does not call serve. Class R.',
32089
+ description: 'Waits (up to waitSeconds, default 20, max 25) for a background job started by a long tool that answered status:"running" (tia_connect, tia_start, tia_show_ui, tia_project_create/save/saveas/close/archive, tia_compile, tia_source_put, tia_download, tia_upload, tia_export_xml, tia_export_block, tia_block_compare, tia_spec_apply) and returns its FINAL result with job:{id,tool,state,durationMs} \u2014 including a gate handoff if the operation ended in one. While a job runs, every other serve-bound tool answers kind:"busy" (with details.jobId): call this instead of polling tia_status, and never repeat the original call. If a tia_connect/tia_start/tia_show_ui job stays running for minutes, a trust dialog (GATE G1) may be waiting on the serve host \u2014 ask a human to look. Does not call serve. Class R.',
31570
32090
  inputSchema: {
31571
32091
  jobId: external_exports.string().describe("jobId returned by the long tool (or by a busy error's details.jobId)"),
31572
32092
  waitSeconds: external_exports.number().int().min(0).max(25).optional().describe("how long this call may wait (default 20, max 25)")
@@ -31577,13 +32097,6 @@ function registerJobTools(server2) {
31577
32097
  }
31578
32098
 
31579
32099
  // src/tools/lifecycle.ts
31580
- function jsonBody(obj) {
31581
- const out = {};
31582
- for (const [k, v] of Object.entries(obj)) {
31583
- if (v !== void 0 && v !== null) out[k] = v;
31584
- }
31585
- return out;
31586
- }
31587
32100
  function startToolNextSteps(tool) {
31588
32101
  if (tool === "tia_project_create") {
31589
32102
  return [
@@ -31598,33 +32111,18 @@ function startToolNextSteps(tool) {
31598
32111
  `3. Re-call ${tool} with the SAME arguments after the human confirms.`
31599
32112
  ];
31600
32113
  }
31601
- async function postResult(path, body, opts) {
31602
- try {
31603
- const data = await tiaFetch(
31604
- path,
31605
- {
31606
- method: "POST",
31607
- headers: { "Content-Type": "application/json; charset=utf-8" },
31608
- body: JSON.stringify(body ?? {})
31609
- },
31610
- { timeoutMs: opts?.timeoutMs ?? SLOW_TIMEOUT_MS }
31611
- );
31612
- return textResult(data);
31613
- } catch (e) {
31614
- const err = asTiaError(e);
31615
- if (err.kind === "tia_start_failed") return tiaStartFailedResult(err, opts?.trustDeniedTool ?? path);
31616
- const tool = opts?.trustDeniedTool;
31617
- if (tool !== void 0 && err.kind === "timeout" && await serveAlive()) {
31618
- return waitingForTrustHandoff(tool, tool, startToolNextSteps(tool), err);
32114
+ async function postResult2(path, body, opts) {
32115
+ return postResult(path, body, {
32116
+ timeoutMs: opts?.timeoutMs,
32117
+ mapError: async (err) => {
32118
+ if (err.kind === "tia_start_failed") return tiaStartFailedResult(err, opts?.trustDeniedTool ?? path);
32119
+ const tool = opts?.trustDeniedTool;
32120
+ if (tool !== void 0 && err.kind === "timeout" && await serveAlive()) {
32121
+ return waitingForTrustHandoff(tool, tool, startToolNextSteps(tool), err);
32122
+ }
32123
+ return errorResult(err);
31619
32124
  }
31620
- return errorResult(err);
31621
- }
31622
- }
31623
- function errorResult(err) {
31624
- return textResult(
31625
- { error: err.message, kind: err.kind, status: err.status, type: err.type, details: err.details ?? null, hint: hintFor(err) },
31626
- true
31627
- );
32125
+ });
31628
32126
  }
31629
32127
  function looksLikeTrustGate(err) {
31630
32128
  if (err.type === "EngineeringSecurityException") return true;
@@ -31711,12 +32209,13 @@ async function connectFlow(args) {
31711
32209
  try {
31712
32210
  const data = await tiaFetch(
31713
32211
  "/connect",
31714
- { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8" }, body: JSON.stringify(body) },
32212
+ { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) },
31715
32213
  { timeoutMs: CONNECT_TIMEOUT_MS }
31716
32214
  );
31717
32215
  return textResult(resumeToken ? { resumed: true, project: data } : data);
31718
32216
  } catch (e) {
31719
32217
  const err = asTiaError(e);
32218
+ if (isInstallingError(err)) return errorResult(err);
31720
32219
  if (err.kind === "tia_start_failed") return tiaStartFailedResult(err, `connect ${projectPath}`);
31721
32220
  if (looksLikeTrustGate(err)) return trustHandoff(projectPath, err);
31722
32221
  if (err.kind === "timeout" && await serveAlive()) return trustHandoff(projectPath, err);
@@ -31733,7 +32232,7 @@ function registerLifecycleTools(server2) {
31733
32232
  headless: external_exports.boolean().optional().describe("true = no window (fast offline authoring); false (default) = with window. Only when creating a new instance.")
31734
32233
  }
31735
32234
  },
31736
- async ({ headless }) => jobs.run("tia_start", { headless }, () => postResult("/tia/start", jsonBody({ headless }), { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_start" }))
32235
+ async ({ headless }) => jobs.run("tia_start", { headless }, () => postResult2("/tia/start", jsonBody({ headless }), { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_start" }))
31737
32236
  );
31738
32237
  server2.registerTool(
31739
32238
  "tia_show_ui",
@@ -31743,7 +32242,7 @@ function registerLifecycleTools(server2) {
31743
32242
  inputSchema: {}
31744
32243
  },
31745
32244
  // Sem args: chave de dedupe = {} literal (nunca o `extra` do SDK, que muda a cada chamada).
31746
- async () => jobs.run("tia_show_ui", {}, () => postResult("/tia/show-ui", void 0, { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_show_ui" }))
32245
+ async () => jobs.run("tia_show_ui", {}, () => postResult2("/tia/show-ui", void 0, { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_show_ui" }))
31747
32246
  );
31748
32247
  server2.registerTool(
31749
32248
  "tia_connect",
@@ -31769,7 +32268,7 @@ function registerLifecycleTools(server2) {
31769
32268
  description: "Disconnects from TIA. This is the explicit teardown for the TIA instance the serve itself created (an instance we merely ATTACHED to is only detached, never killed) \u2014 but not the only path that can end an owned instance: tia_show_ui (relaunch visible), tia_project_create, and a tia_connect needing a fresh connect also end/replace it. WARNING (Gd3): on an ATTACHED instance, /disconnect does NOT close the project \u2014 to RELEASE the project lock while KEEPING the TIA process alive (so the next tia_connect reuses it) use tia_project_close instead. Maps to POST /disconnect.",
31770
32269
  inputSchema: {}
31771
32270
  },
31772
- async () => postResult("/disconnect")
32271
+ async () => postResult2("/disconnect")
31773
32272
  );
31774
32273
  server2.registerTool(
31775
32274
  "tia_project_create",
@@ -31785,7 +32284,7 @@ function registerLifecycleTools(server2) {
31785
32284
  async ({ directory, name, withUserInterface }) => jobs.run(
31786
32285
  "tia_project_create",
31787
32286
  { directory, name, withUserInterface },
31788
- () => postResult("/project/create", jsonBody({ directory, name, withUserInterface }), { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_project_create" })
32287
+ () => postResult2("/project/create", jsonBody({ directory, name, withUserInterface }), { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_project_create" })
31789
32288
  )
31790
32289
  );
31791
32290
  server2.registerTool(
@@ -31795,18 +32294,18 @@ function registerLifecycleTools(server2) {
31795
32294
  description: `Saves the open project. Maps to POST /project/save. ${LONG_OPERATION_NOTE}`,
31796
32295
  inputSchema: {}
31797
32296
  },
31798
- async () => jobs.run("tia_project_save", {}, () => postResult("/project/save"))
32297
+ async () => jobs.run("tia_project_save", {}, () => postResult2("/project/save"))
31799
32298
  );
31800
32299
  server2.registerTool(
31801
32300
  "tia_project_saveas",
31802
32301
  {
31803
32302
  title: "TIA \u2014 save project as",
31804
- description: "Saves the open project to another directory. Maps to POST /project/saveas.",
32303
+ description: `Saves the open project to another directory. Maps to POST /project/saveas. ${LONG_OPERATION_NOTE}`,
31805
32304
  inputSchema: {
31806
32305
  directory: external_exports.string().optional().describe("target directory for 'save as'")
31807
32306
  }
31808
32307
  },
31809
- async ({ directory }) => postResult("/project/saveas", jsonBody({ directory }))
32308
+ async ({ directory }) => jobs.run("tia_project_saveas", { directory }, () => postResult2("/project/saveas", jsonBody({ directory })))
31810
32309
  );
31811
32310
  server2.registerTool(
31812
32311
  "tia_project_close",
@@ -31815,7 +32314,7 @@ function registerLifecycleTools(server2) {
31815
32314
  description: "Closes the open project and RELEASES the lock (Gd3: use this, not tia_disconnect, to release the project). KEEPS the TIA process alive (response `portalKept`/`pid`) \u2014 the next tia_connect reuses it instead of paying the 40-80s cold start. Nothing is saved: call tia_project_save first if needed. Maps to POST /project/close. " + LONG_OPERATION_NOTE,
31816
32315
  inputSchema: {}
31817
32316
  },
31818
- async () => jobs.run("tia_project_close", {}, () => postResult("/project/close"))
32317
+ async () => jobs.run("tia_project_close", {}, () => postResult2("/project/close"))
31819
32318
  );
31820
32319
  server2.registerTool(
31821
32320
  "tia_project_archive",
@@ -31828,197 +32327,11 @@ function registerLifecycleTools(server2) {
31828
32327
  mode: external_exports.string().optional().describe("archive mode (e.g., Compressed)")
31829
32328
  }
31830
32329
  },
31831
- async ({ directory, name, mode }) => jobs.run("tia_project_archive", { directory, name, mode }, () => postResult("/project/archive", jsonBody({ directory, name, mode })))
32330
+ async ({ directory, name, mode }) => jobs.run("tia_project_archive", { directory, name, mode }, () => postResult2("/project/archive", jsonBody({ directory, name, mode })))
31832
32331
  );
31833
32332
  }
31834
32333
 
31835
- // src/planStore.ts
31836
- import { randomBytes as randomBytes2 } from "node:crypto";
31837
- var PLAN_TTL_MS = Number.parseInt(process.env.TIA_PLAN_TTL_MS ?? "900000", 10) || 9e5;
31838
- function canonicalPlan(plan) {
31839
- for (const [k, v] of Object.entries(plan)) {
31840
- if (v !== null && typeof v === "object") {
31841
- throw new Error(`canonicalPlan: nested value at key '${k}' is not allowed (the G3 plan must be flat)`);
31842
- }
31843
- }
31844
- return JSON.stringify(plan, Object.keys(plan).sort());
31845
- }
31846
- var PlanStore = class {
31847
- constructor(ttlMs = PLAN_TTL_MS, now = Date.now, prefix = "g3_") {
31848
- this.ttlMs = ttlMs;
31849
- this.now = now;
31850
- this.prefix = prefix;
31851
- }
31852
- ttlMs;
31853
- now;
31854
- prefix;
31855
- issued = /* @__PURE__ */ new Map();
31856
- consumed = /* @__PURE__ */ new Set();
31857
- issue(plan, fingerprint) {
31858
- if (!fingerprint) throw new Error("planStore.issue: fingerprint is required");
31859
- canonicalPlan(plan);
31860
- const t = this.now();
31861
- const entry = {
31862
- token: `${this.prefix}${randomBytes2(12).toString("base64url")}`,
31863
- plan: { ...plan },
31864
- fingerprint,
31865
- issuedAt: t,
31866
- expiresAt: t + this.ttlMs
31867
- };
31868
- this.issued.set(entry.token, entry);
31869
- return entry;
31870
- }
31871
- check(token, plan) {
31872
- if (!token) return { ok: false, reason: "unknown" };
31873
- if (this.consumed.has(token)) return { ok: false, reason: "consumed" };
31874
- const entry = this.issued.get(token);
31875
- if (!entry) return { ok: false, reason: "unknown" };
31876
- if (this.now() > entry.expiresAt) return { ok: false, reason: "expired" };
31877
- if (canonicalPlan(entry.plan) !== canonicalPlan(plan)) return { ok: false, reason: "plan_mismatch" };
31878
- return { ok: true, issued: entry };
31879
- }
31880
- /** Marca como usado ANTES de chamar o serve: um retry após timeout do cliente é recusado (sem download duplicado). */
31881
- consume(token) {
31882
- this.issued.delete(token);
31883
- this.consumed.add(token);
31884
- }
31885
- };
31886
- var planStore = new PlanStore();
31887
- var uploadPlanStore = new PlanStore(PLAN_TTL_MS, Date.now, "g4_");
31888
-
31889
- // src/tools/verification.ts
31890
- var seg2 = (v) => encodeURIComponent(v);
31891
- var JSON_HEADERS = { "Content-Type": "application/json; charset=utf-8" };
31892
- function jsonBody2(obj) {
31893
- const out = {};
31894
- for (const [k, v] of Object.entries(obj)) if (v !== void 0 && v !== null) out[k] = v;
31895
- return out;
31896
- }
31897
- function errorResult2(err, hintOverride) {
31898
- return textResult(
31899
- { error: err.message, kind: err.kind, status: err.status, type: err.type, details: err.details ?? null, hint: hintOverride ?? hintFor(err) },
31900
- true
31901
- );
31902
- }
31903
- async function send(method, path, body, timeoutMs) {
31904
- try {
31905
- const init = { method, headers: JSON_HEADERS };
31906
- if (body !== void 0) init.body = JSON.stringify(body);
31907
- return textResult(await tiaFetch(path, init, { timeoutMs: timeoutMs ?? SLOW_TIMEOUT_MS }));
31908
- } catch (e) {
31909
- return errorResult2(asTiaError(e));
31910
- }
31911
- }
31912
- var GATE_INSTRUCTION = {
31913
- download_approval: "A human must APPROVE the download: it STOPS the physical CPU (StopAll), OVERWRITES system data, and RESTARTS the CPU. Review the plan AND its software fingerprint (what exactly goes to the CPU). The serve auto-confirms Stop/Reset(DeleteAll, when the loaded program is replaced)/Overwrite/Consistent-blocks/Start (listed in 'configurations' after the download).",
31914
- go_online: "Going ONLINE connects to the PHYSICAL PLC over the network. Confirm with a human that it is safe to connect to the target machine.",
31915
- station_upload: "GATE G4: a station upload goes ONLINE to the PHYSICAL CPU and reads its hardware configuration and program into the OPEN project as a new station (it reads the CPU and does not write or stop it \u2014 observed on hardware: the CPU stayed in RUN). Confirm with a human that it is safe to connect to this machine AND that the open project shown here is a dedicated backup project \u2014 never the working project.",
31916
- upload_password: "GATE G6: the CPU is read-protected. Ask the human for its read-access password \u2014 NEVER invent, guess or reuse one. The approval token is spent: call tia_upload without confirm for a fresh confirmation, then confirm:true with the new planHash and the password.",
31917
- net_scan: "A network scan (accessible devices) probes the local network via the PG/PC adapter. Confirm before scanning."
31918
- };
31919
- var DOWNLOAD_REASON = {
31920
- not_approved: "No human approval yet: the real download needs approved:true plus the planHash of a reviewed dryRun.",
31921
- unknown: "No valid approval token: this planHash was not issued by this MCP process (or the MCP restarted). Approval tokens are random, single-use and live only in the MCP process that issued them.",
31922
- expired: "This planHash expired (TIA_PLAN_TTL_MS). Approvals do not carry over to later sessions.",
31923
- consumed: "This planHash was already used (single-use). If the previous call timed out, check the CPU and tia_job_status BEFORE anything else \u2014 the download may have happened.",
31924
- plan_mismatch: "The parameters differ from the approved plan (plc / interface / options / allowUpgradeTargetDevice). The approval covers exactly the reviewed plan.",
31925
- // P3 fix round 1 (#1): cause-neutral on purpose — this same reason now covers transport failures (a network or
31926
- // timeout issue) AND a serve error (5xx/403/404/409 not_connected/etc.) AND an unreadable response, so the
31927
- // text must not single out one cause (the old text named only "a network/timeout error", which read as if it
31928
- // ruled out the other causes — deliberately NOT reusing that exact joined phrase here).
31929
- outcome_unknown: "The /download call did not return a usable answer (a network or timeout issue, a serve error, or an unreadable response) AFTER the single-use token was already consumed \u2014 the token is SPENT and cannot be reused. The download may still be running on the CPU, or it may already have completed. Check the CPU state directly and tia_status (and tia_job_status if a job id is known) BEFORE requesting a new plan. Do NOT retry this same call \u2014 the token is gone and a retry cannot resume it."
31930
- };
31931
- function downloadResumeSteps(reason) {
31932
- if (reason === "outcome_unknown") {
31933
- return [
31934
- "1. The approval token is SPENT and cannot be used again \u2014 do NOT call tia_download with approved:true and this same planHash.",
31935
- "2. Check the CPU state directly, then tia_status (and tia_job_status if a job id is known), BEFORE anything else.",
31936
- "3. Only once the real outcome is known, run tia_download with dryRun:true for a FRESH plan and a NEW token.",
31937
- "4. Get a new explicit human approval before calling tia_download with approved:true again."
31938
- ];
31939
- }
31940
- if (reason === "consumed") {
31941
- return [
31942
- "1. This planHash was already used (single-use) \u2014 do NOT call tia_download with approved:true and this same planHash again.",
31943
- "2. Check the CPU state directly, then tia_status (and tia_job_status if a job id is known), BEFORE anything else \u2014 the download may already have happened.",
31944
- "3. Only once the real outcome is known, run tia_download with dryRun:true for a FRESH plan and a NEW token.",
31945
- "4. Get a new explicit human approval before calling tia_download with approved:true again."
31946
- ];
31947
- }
31948
- return [
31949
- "1. Run tia_download with dryRun:true to get a FRESH plan, its software fingerprint and a new single-use planHash.",
31950
- "2. Show the plan + fingerprint to the line's responsible person and get an explicit yes.",
31951
- "3. Re-call with approved:true and that NEW planHash, before it expires."
31952
- ];
31953
- }
31954
- var UPLOAD_REASON = {
31955
- unknown: "No valid approval token: this planHash was not issued by this MCP process (or the MCP restarted). Approval tokens are random, single-use and live only in the MCP process that issued them. Call tia_upload without confirm for a fresh plan.",
31956
- expired: "This planHash expired (TIA_PLAN_TTL_MS). Approvals do not carry over to later sessions.",
31957
- consumed: "This planHash was already used (single-use). If the previous call timed out, check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the station may already have been added.",
31958
- plan_mismatch: "The parameters differ from the approved plan (ip / connection). The approval covers exactly the reviewed plan.",
31959
- outcome_unknown: "The /stations/upload call did not return a usable answer (a network or timeout issue, a serve error, or an unreadable response) AFTER the single-use token was already consumed \u2014 the token is SPENT and cannot be reused. The station may still be uploading or may already have been added as a new station. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE requesting a new plan. Do NOT repeat this call \u2014 the token is gone and a retry cannot resume it.",
31960
- password_required: "The CPU is read-protected and no accepted password was provided (G6): the approval token is SPENT. Ask the human for the read-access password \u2014 never invent one \u2014 then call tia_upload without confirm for a fresh confirmation and confirm:true with the new planHash and the password.",
31961
- password_rejected: "The CPU rejected the provided read-access password (G6): the approval token is SPENT. Confirm the password with the human \u2014 never invent one \u2014 then call tia_upload without confirm for a fresh confirmation and confirm:true with the new planHash and the corrected password."
31962
- };
31963
- function uploadResumeSteps(reason) {
31964
- if (reason === "outcome_unknown") {
31965
- return [
31966
- "1. The approval token is SPENT and cannot be used again \u2014 do NOT call tia_upload with confirm:true and this same planHash.",
31967
- "2. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else.",
31968
- "3. Only once the real outcome is known, run tia_upload without confirm for a FRESH plan and a NEW token.",
31969
- "4. Get a new explicit human approval before calling tia_upload with confirm:true again."
31970
- ];
31971
- }
31972
- if (reason === "password_required" || reason === "password_rejected") {
31973
- return [
31974
- "1. Ask the human for the CPU read-access password (G6 \u2014 never invent, guess or reuse one).",
31975
- "2. Run tia_upload without confirm for a FRESH plan and a NEW token (the old token is SPENT).",
31976
- "3. Show the plan to the human and get an explicit yes.",
31977
- "4. Re-call with confirm:true, that NEW planHash and the human-provided password, before it expires."
31978
- ];
31979
- }
31980
- if (reason === "consumed") {
31981
- return [
31982
- "1. This planHash was already used (single-use) \u2014 do NOT call tia_upload with confirm:true and this same planHash again.",
31983
- "2. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the station may already have been added.",
31984
- "3. Only once the real outcome is known, run tia_upload without confirm for a FRESH plan and a NEW token.",
31985
- "4. Get a new explicit human approval before calling tia_upload with confirm:true again."
31986
- ];
31987
- }
31988
- if (reason) {
31989
- return [
31990
- "1. Run tia_upload without confirm to get a FRESH plan and a new single-use planHash.",
31991
- "2. Show the plan to the human and get an explicit yes.",
31992
- "3. Re-call with confirm:true and that NEW planHash, before it expires."
31993
- ];
31994
- }
31995
- return [
31996
- "1. Show the plan + project to the human and get an explicit yes.",
31997
- "2. Re-call tia_upload with confirm:true and this SAME planHash, before it expires."
31998
- ];
31999
- }
32000
- var YOUMUSTDO_OUTCOME_UNKNOWN = "Check the CPU state directly (and tia_status / tia_job_status) BEFORE anything else \u2014 the approval token is ALREADY SPENT. Do NOT repeat this call: get a fresh dryRun plan and a new human approval only once the real outcome is known.";
32001
- var YOUMUSTDO_UPLOAD_OUTCOME_UNKNOWN = "Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the approval token is ALREADY SPENT. Do NOT repeat this call: get a fresh plan and a new human approval only once the real outcome is known.";
32002
- function gateHandoff(gate, ctx) {
32003
- const reasonTable = gate === "download_approval" ? DOWNLOAD_REASON : UPLOAD_REASON;
32004
- const resume = gate === "download_approval" ? downloadResumeSteps(ctx.reason) : uploadResumeSteps(ctx.reason);
32005
- const youMustDo = ctx.youMustDo !== void 0 ? ctx.youMustDo : gate === "download_approval" && ctx.reason === "outcome_unknown" ? YOUMUSTDO_OUTCOME_UNKNOWN : gate === "station_upload" && ctx.reason === "outcome_unknown" ? YOUMUSTDO_UPLOAD_OUTCOME_UNKNOWN : GATE_INSTRUCTION[gate] ?? "Human confirmation required.";
32006
- return textResult(
32007
- {
32008
- status: "requires_human_action",
32009
- gate,
32010
- canDo: ctx.plc ? `${gate} on ${ctx.plc}` : gate,
32011
- youMustDo,
32012
- reasonCode: ctx.reason ?? null,
32013
- reason: ctx.reason ? reasonTable[ctx.reason] ?? ctx.reason : null,
32014
- plan: ctx.plan ?? null,
32015
- planHash: ctx.planHash ?? null,
32016
- ...ctx.extra ?? {},
32017
- nextSteps: resume
32018
- },
32019
- false
32020
- );
32021
- }
32334
+ // src/tools/compile.ts
32022
32335
  var COMPILE_GUI_GATE_SIGNATURES = [
32023
32336
  {
32024
32337
  contains: "OPC UA license is not sufficient",
@@ -32093,571 +32406,53 @@ function summarizeCompile(compileDto) {
32093
32406
  const exportable = changes.filter((c) => c.change !== "removed");
32094
32407
  if (exportable.length > 0) {
32095
32408
  const errors = typeof d.errors === "number" ? d.errors : null;
32096
- const notClean = errors !== null && errors > 0;
32097
- hints.push(
32098
- notClean ? `This compile changed these block(s): ${exportable.map(describe3).join(", ")}. Fix the ${errors} compile ERROR(s) FIRST (tia_export_block requires a CONSISTENT block), THEN export these blocks with tia_export_block and commit them \u2014 a later compile will NOT list them again.` : `This compile changed these block(s): ${exportable.map(describe3).join(", ")}. Export them (tia_export_block) and commit them, or version control silently drifts from the project.`
32099
- );
32100
- }
32101
- if (removed.length > 0) {
32102
- const names = removed.map((c) => typeof c.name === "string" && c.name.trim() ? c.name.trim() : "?").join(", ");
32103
- hints.push(`This compile REMOVED these block(s): ${names}. Nothing to export \u2014 update version control (delete them there too) instead.`);
32104
- }
32105
- }
32106
- if (typeof d.blockChangesError === "string" && d.blockChangesError.trim()) {
32107
- hints.push(
32108
- `blockChangesError: the serve could not determine which blocks this compile changed (${d.blockChangesError.trim()}) \u2014 the compile result itself is still valid. Consider exporting and comparing (tia_export_block / tia_block_compare) to be safe.`
32109
- );
32110
- }
32111
- return { located, hints };
32112
- }
32113
- async function compileFlow(plc) {
32114
- try {
32115
- const data = await tiaFetch(`/plcs/${seg2(plc)}/compile`, { method: "POST", headers: JSON_HEADERS, body: "{}" }, { timeoutMs: 12e4 });
32116
- const d = data ?? {};
32117
- const errors = typeof d.errors === "number" ? d.errors : null;
32118
- const clean = errors !== null ? errors === 0 : d.state === "Success";
32119
- const nextHints = clean ? ["Compile CLEAN (Gd8: warnings don't block). Ready for gated download (tia_download) or S7 connection."] : [`Compile with ${errors ?? "?"} ERROR(s) \u2014 fix BEFORE download/S7 (Gd9 forbids a non-clean deploy). See 'messages' (tree).`];
32120
- const guiGateHints = detectGuiGateHints(d.messages);
32121
- const { located, hints } = summarizeCompile(d);
32122
- nextHints.push(...hints);
32123
- return textResult({
32124
- ...d,
32125
- verification: { compiled: clean ? "clean" : "error", errors, warnings: d.warnings ?? null },
32126
- nextHints,
32127
- ...guiGateHints.length > 0 ? { guiGateHints } : {},
32128
- ...located.length > 0 ? { located } : {}
32129
- });
32130
- } catch (e) {
32131
- return errorResult2(asTiaError(e));
32132
- }
32133
- }
32134
- var isObject2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
32135
- function buildPlan(args) {
32136
- return {
32137
- plc: args.plc,
32138
- connectionMode: args.connectionMode ?? null,
32139
- pcInterfaceName: args.pcInterfaceName ?? null,
32140
- pcInterfaceNumber: args.pcInterfaceNumber ?? 1,
32141
- targetInterfaceName: args.targetInterfaceName ?? null,
32142
- hardware: args.hardware ?? false,
32143
- software: args.software ?? true,
32144
- // Sempre booleano: ausente ≡ false, para "ausente" e "false" nunca darem plan_mismatch.
32145
- allowUpgradeTargetDevice: args.allowUpgradeTargetDevice === true
32146
- };
32147
- }
32148
- function connectionBody(args) {
32149
- return jsonBody2({
32150
- connectionMode: args.connectionMode,
32151
- pcInterfaceName: args.pcInterfaceName,
32152
- pcInterfaceNumber: args.pcInterfaceNumber,
32153
- targetInterfaceName: args.targetInterfaceName,
32154
- hardware: args.hardware,
32155
- software: args.software
32156
- });
32157
- }
32158
- function bodyFromApprovedPlan(issued) {
32159
- const plan = issued.plan;
32160
- return {
32161
- ...jsonBody2({
32162
- connectionMode: plan.connectionMode,
32163
- pcInterfaceName: plan.pcInterfaceName,
32164
- pcInterfaceNumber: plan.pcInterfaceNumber,
32165
- targetInterfaceName: plan.targetInterfaceName,
32166
- hardware: plan.hardware,
32167
- software: plan.software
32168
- }),
32169
- expectedFingerprint: issued.fingerprint,
32170
- allowUpgradeTargetDevice: plan.allowUpgradeTargetDevice === true
32171
- };
32172
- }
32173
- async function planDownload(args, plan, store) {
32174
- let raw;
32175
- try {
32176
- raw = await tiaFetch(
32177
- `/plcs/${seg2(args.plc)}/download/plan`,
32178
- { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(connectionBody(args)) },
32179
- { timeoutMs: SLOW_TIMEOUT_MS }
32180
- );
32181
- } catch (e) {
32182
- const err = asTiaError(e);
32183
- if (err.status === 404 && err.kind === "route_not_found") {
32184
- return errorResult2(
32185
- new TiaApiError(
32186
- "This serve does not support verified download plans (POST /plcs/{plc}/download/plan \u2192 404). Update the TIAOpenness app to v1.6.0 or later. Nothing was downloaded.",
32187
- { status: 404, kind: "serve_too_old" }
32188
- )
32189
- );
32190
- }
32191
- return errorResult2(err);
32192
- }
32193
- const data = isObject2(raw) ? raw : {};
32194
- const compile = { state: data.compile?.state ?? null, errors: data.compile?.errors ?? null, warnings: data.compile?.warnings ?? null };
32195
- const fingerprint = typeof data.fingerprint === "string" ? data.fingerprint : "";
32196
- const hasFingerprint = fingerprint.trim().length > 0;
32197
- if (data.ready !== true || !hasFingerprint) {
32198
- const blockers = Array.isArray(data.blockers) ? [...data.blockers] : [];
32199
- if (!isObject2(raw)) blockers.push("invalid_plan_response");
32200
- const fingerprintMissing = data.ready === true && !hasFingerprint;
32201
- if (fingerprintMissing) blockers.push("fingerprint_missing");
32202
- return textResult(
32203
- {
32204
- dryRun: true,
32205
- status: "plan_blocked",
32206
- gate: "download_approval",
32207
- plan,
32208
- blockers,
32209
- compile,
32210
- connection: data.connection ?? null,
32211
- note: fingerprintMissing ? "NO approval token was issued: serve reported ready but returned no software fingerprint, and this MCP never approves a download it cannot verify. Update the TIAOpenness app (serve) to v1.6.0 or later and run dryRun again." : "NO approval token was issued. Fix the blockers (compile errors \u2192 tia_compile; interface \u2192 tia_pg_interfaces) and run dryRun again."
32212
- },
32213
- false
32214
- );
32215
- }
32216
- const issued = store.issue(plan, fingerprint);
32217
- return textResult(
32218
- {
32219
- dryRun: true,
32220
- status: "plan_ok",
32221
- gate: "download_approval",
32222
- plan,
32223
- planHash: issued.token,
32224
- expiresAt: new Date(issued.expiresAt).toISOString(),
32225
- fingerprint,
32226
- fingerprintItems: data.fingerprintItems ?? [],
32227
- coverage: data.coverage ?? null,
32228
- warnings: data.warnings ?? [],
32229
- compile,
32230
- connection: data.connection ?? null,
32231
- loadPreview: {
32232
- // Emenda #4: espelha TODAS as auto-confirmações reais de PlcDeployService.cs (PreDownload/PostDownload),
32233
- // não só as 3 mais óbvias — inclusive as que não param/reiniciam a CPU, mas ainda alteram o conteúdo dela.
32234
- willConfirm: [
32235
- "StopModules = StopAll \u2014 STOPS the physical CPU (pre phase)",
32236
- "ResetModule = DeleteAll \u2014 if the CPU already holds a DIFFERENT program, it is deleted before this one loads (pre and/or post phase)",
32237
- "OverwriteSystemData = Overwrite \u2014 overwrites system data (pre phase for a hardware download, and again in the post phase)",
32238
- "ConsistentBlocksDownload = ConsistentDownload \u2014 downloads all blocks consistently (pre phase)",
32239
- "AlarmTextLibrariesDownload = ConsistentDownload \u2014 downloads alarm text libraries consistently (pre phase)",
32240
- "StartModules = StartModule \u2014 RESTARTS the CPU at the end (post phase)",
32241
- plan.allowUpgradeTargetDevice ? "UpgradeTargetDevice = Checked \u2014 upgrades the target device (explicitly allowed)" : "UpgradeTargetDevice = NOT confirmed unless allowUpgradeTargetDevice:true \u2014 if the CPU requires it the download is refused, but the CPU may already have been stopped.",
32242
- "Any OTHER configuration dialog serve does not recognize is left UNTOUCHED, which can abort the load."
32243
- ],
32244
- note: "Openness has no preview-without-downloading; these are the selections serve's delegates will make. The real download returns 'configurations' with what was actually confirmed."
32245
- },
32246
- note: "Plan verified by serve. NOTHING was downloaded. After a human approves THIS plan and fingerprint, call tia_download with approved:true and this planHash (single-use, expires at expiresAt)."
32247
- },
32248
- false
32249
- );
32250
- }
32251
- async function downloadFlow(args, store = planStore) {
32252
- const plan = buildPlan(args);
32253
- if (args.dryRun) return planDownload(args, plan, store);
32254
- if (args.approved !== true) return gateHandoff("download_approval", { plc: args.plc, plan, reason: "not_approved" });
32255
- const check2 = store.check(args.planHash, plan);
32256
- if (!check2.ok) return gateHandoff("download_approval", { plc: args.plc, plan, reason: check2.reason });
32257
- store.consume(check2.issued.token);
32258
- let raw;
32259
- try {
32260
- raw = await tiaFetch(
32261
- `/plcs/${seg2(args.plc)}/download`,
32262
- { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(bodyFromApprovedPlan(check2.issued)) },
32263
- { timeoutMs: 18e4 }
32264
- );
32265
- } catch (e) {
32266
- const err = asTiaError(e);
32267
- const knownRefusal = err.status === 409 && (err.kind === "plan_stale" || err.kind === "upgrade_target_device_required");
32268
- if (knownRefusal) return errorResult2(err);
32269
- const isTransport = err.kind === "timeout" || err.kind === "connection_refused";
32270
- return gateHandoff("download_approval", {
32271
- plc: args.plc,
32272
- plan,
32273
- reason: "outcome_unknown",
32274
- extra: {
32275
- approvedPlanHash: check2.issued.token,
32276
- ...isTransport ? { transportKind: err.kind, transportDiagnostics: err.message } : {
32277
- serveErrorStatus: err.status,
32278
- serveErrorKind: err.kind,
32279
- serveErrorType: err.type ?? null,
32280
- serveErrorInner: err.inner ?? null,
32281
- serveErrorDetails: err.details ?? null,
32282
- serveErrorDiagnostics: err.message
32283
- }
32284
- }
32285
- });
32286
- }
32287
- const data = isObject2(raw) ? raw : {};
32288
- const state = typeof data.state === "string" ? data.state : null;
32289
- const errors = typeof data.errors === "number" ? data.errors : null;
32290
- const stateLower = state !== null ? state.toLowerCase() : null;
32291
- const cleanErrors = errors === 0;
32292
- const loadOutcome = stateLower === "success" && cleanErrors ? "success" : (stateLower === "warning" || stateLower === "information") && cleanErrors ? "success_with_warnings" : "failed";
32293
- const downloaded = loadOutcome !== "failed";
32294
- const fingerprintVerified = data.fingerprintVerified === true;
32295
- const warnings = [];
32296
- if (loadOutcome === "failed") {
32297
- warnings.push(
32298
- `serve answered the download call, but did not report a clean load (state='${state ?? "unknown"}', errors=${errors ?? "unknown"}). Check 'result.messages' for what happened \u2014 the CPU may be in a partial or unexpected state. Do not treat this as a confirmed successful deploy.`
32299
- );
32300
- }
32301
- if (!fingerprintVerified) {
32302
- warnings.push(
32303
- "serve did NOT confirm the software fingerprint check (fingerprintVerified is not true): it is NOT proven that the CPU received exactly the approved software. The serve may be older than v1.6.0 and have ignored expectedFingerprint. Tell the human and check the CPU before relying on it."
32304
- );
32305
- }
32306
- return textResult({
32307
- downloaded,
32308
- loadOutcome,
32309
- approvedPlanHash: check2.issued.token,
32310
- fingerprint: check2.issued.fingerprint,
32311
- fingerprintVerified,
32312
- state,
32313
- errors,
32314
- ...loadOutcome === "success_with_warnings" ? { note: "The load completed with warnings \u2014 read result.messages." } : {},
32315
- ...warnings.length > 0 ? { warning: warnings.join(" ") } : {},
32316
- result: raw ?? null
32317
- });
32318
- }
32319
- var UPLOAD_TIMEOUT_MS = 24e4;
32320
- function buildUploadPlan(args) {
32321
- return {
32322
- ip: args.ip,
32323
- connectionMode: args.connectionMode ?? null,
32324
- pcInterfaceName: args.pcInterfaceName ?? null,
32325
- pcInterfaceNumber: args.pcInterfaceNumber ?? 1
32326
- };
32327
- }
32328
- function uploadBodyFromApprovedPlan(issued, password) {
32329
- const plan = issued.plan;
32330
- return {
32331
- ...jsonBody2({
32332
- connectionMode: plan.connectionMode,
32333
- pcInterfaceName: plan.pcInterfaceName,
32334
- pcInterfaceNumber: plan.pcInterfaceNumber,
32335
- ip: plan.ip
32336
- }),
32337
- expectedProjectPath: issued.fingerprint,
32338
- ...password !== void 0 ? { password } : {}
32339
- };
32340
- }
32341
- async function planUpload(args, plan, store) {
32342
- let raw;
32343
- try {
32344
- raw = await tiaFetch(
32345
- "/stations/upload/plan",
32346
- {
32347
- method: "POST",
32348
- headers: JSON_HEADERS,
32349
- body: JSON.stringify(
32350
- jsonBody2({
32351
- connectionMode: args.connectionMode,
32352
- pcInterfaceName: args.pcInterfaceName,
32353
- pcInterfaceNumber: args.pcInterfaceNumber,
32354
- ip: args.ip
32355
- })
32356
- )
32357
- },
32358
- { timeoutMs: SLOW_TIMEOUT_MS }
32359
- );
32360
- } catch (e) {
32361
- const err = asTiaError(e);
32362
- if (err.status === 404 && err.kind === "route_not_found") {
32363
- return errorResult2(
32364
- new TiaApiError(
32365
- "This serve does not support station-upload plans (POST /stations/upload/plan \u2192 404). Update the TIAOpenness app to v1.6.0 or later. Nothing was uploaded.",
32366
- { status: 404, kind: "serve_too_old" }
32367
- ),
32368
- "Update the TIAOpenness app to v1.6.0 or later. Nothing was uploaded."
32369
- );
32370
- }
32371
- return errorResult2(err);
32372
- }
32373
- const data = isObject2(raw) ? raw : {};
32374
- const project = isObject2(data.project) ? data.project : {};
32375
- const projectPath = typeof project.path === "string" ? project.path : "";
32376
- const projectName = typeof project.name === "string" ? project.name : "(unnamed)";
32377
- const devices = Array.isArray(data.devices) ? [...data.devices] : [];
32378
- if (data.ready !== true || projectPath.trim().length === 0) {
32379
- const blockers = Array.isArray(data.blockers) ? [...data.blockers] : [];
32380
- if (!isObject2(raw)) blockers.push("invalid_plan_response");
32381
- if (data.ready === true) blockers.push("project_path_missing");
32382
- return textResult(
32383
- {
32384
- status: "plan_blocked",
32385
- gate: "station_upload",
32386
- plan,
32387
- blockers,
32388
- connection: data.connection ?? null,
32389
- project: data.project ?? null,
32390
- devices,
32391
- note: typeof data.note === "string" ? data.note : null
32392
- },
32393
- false
32394
- );
32395
- }
32396
- const issued = store.issue(plan, projectPath);
32397
- const warning = devices.length > 0 ? `The open project already has ${devices.length} device(s); a backup belongs in a dedicated EMPTY project (tia.backup).` : void 0;
32398
- const youMustDo = `GATE G4: upload (read) the hardware configuration and program of the PHYSICAL CPU at ${String(plan.ip)} into the OPEN project "${projectName}" (${projectPath}), which currently holds ${devices.length} device(s) \u2014 it reads the CPU and does not write it. Confirm with a human that it is safe to connect to this machine AND that this is a dedicated backup project, never the working project. After an explicit yes, re-call tia_upload with confirm:true and this planHash.`;
32399
- return gateHandoff("station_upload", {
32400
- plan,
32401
- planHash: issued.token,
32402
- youMustDo,
32403
- extra: {
32404
- expiresAt: new Date(issued.expiresAt).toISOString(),
32405
- project: data.project ?? null,
32406
- devices,
32407
- connection: data.connection ?? null,
32408
- ...warning !== void 0 ? { warning } : {}
32409
- }
32410
- });
32411
- }
32412
- async function uploadFlow(args, store = uploadPlanStore) {
32413
- const plan = buildUploadPlan(args);
32414
- if (args.confirm !== true) return planUpload(args, plan, store);
32415
- const check2 = store.check(args.planHash, plan);
32416
- if (!check2.ok) return gateHandoff("station_upload", { plan, reason: check2.reason });
32417
- store.consume(check2.issued.token);
32418
- let raw;
32419
- try {
32420
- raw = await tiaFetch(
32421
- "/stations/upload",
32422
- { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(uploadBodyFromApprovedPlan(check2.issued, args.password)) },
32423
- { timeoutMs: UPLOAD_TIMEOUT_MS }
32424
- );
32425
- } catch (e) {
32426
- const err = asTiaError(e);
32427
- const knownRefusal = err.status === 400 || err.status === 409 && (err.kind === "project_changed" || err.kind === "upload_provider_unavailable" || err.kind === "connection_unresolved");
32428
- if (knownRefusal) {
32429
- return errorResult2(
32430
- new TiaApiError(`${err.message} The approval token is SPENT (single-use) and cannot be reused; nothing was uploaded.`, {
32431
- status: err.status,
32432
- kind: err.kind,
32433
- type: err.type,
32434
- inner: err.inner,
32435
- details: err.details
32436
- })
32437
- );
32438
- }
32439
- if (err.status === 409 && (err.kind === "upload_password_required" || err.kind === "upload_password_rejected")) {
32440
- const det = isObject2(err.details) ? err.details : {};
32441
- return gateHandoff("upload_password", {
32442
- plan,
32443
- reason: err.kind === "upload_password_required" ? "password_required" : "password_rejected",
32444
- extra: { configurations: det.configurations ?? null }
32445
- });
32446
- }
32447
- const isTransport = err.kind === "timeout" || err.kind === "connection_refused";
32448
- return gateHandoff("station_upload", {
32449
- plan,
32450
- reason: "outcome_unknown",
32451
- extra: {
32452
- approvedPlanHash: check2.issued.token,
32453
- ...isTransport ? { transportKind: err.kind, transportDiagnostics: err.message } : {
32454
- serveErrorStatus: err.status,
32455
- serveErrorKind: err.kind,
32456
- serveErrorType: err.type ?? null,
32457
- serveErrorInner: err.inner ?? null,
32458
- serveErrorDetails: err.details ?? null,
32459
- serveErrorDiagnostics: err.message
32460
- }
32461
- }
32462
- });
32463
- }
32464
- if (!isObject2(raw)) {
32465
- return gateHandoff("station_upload", {
32466
- plan,
32467
- reason: "outcome_unknown",
32468
- extra: {
32469
- approvedPlanHash: check2.issued.token,
32470
- serveErrorStatus: null,
32471
- serveErrorKind: null,
32472
- serveErrorType: null,
32473
- serveErrorInner: null,
32474
- serveErrorDetails: null,
32475
- serveErrorDiagnostics: "POST /stations/upload answered 2xx with an empty or non-JSON body AFTER the single-use token was already consumed \u2014 the upload outcome is unknown."
32476
- }
32477
- });
32478
- }
32479
- const data = raw;
32480
- const state = typeof data.state === "string" ? data.state : null;
32481
- const errors = typeof data.errors === "number" ? data.errors : null;
32482
- const stateLower = state !== null ? state.toLowerCase() : null;
32483
- const cleanErrors = errors === 0;
32484
- const uploadOutcome = stateLower === "success" && cleanErrors ? "success" : (stateLower === "warning" || stateLower === "information") && cleanErrors ? "success_with_warnings" : "failed";
32485
- const uploaded = uploadOutcome !== "failed";
32486
- const createdDevices = Array.isArray(data.createdDevices) ? data.createdDevices : [];
32487
- const warnings = [];
32488
- if (uploadOutcome === "failed") {
32489
- warnings.push(
32490
- `serve answered the upload call, but did not report a clean upload (state='${state ?? "unknown"}', errors=${errors ?? "unknown"}). Do not treat this as a backup \u2014 read result.messages for what happened; the project may hold a partial station.`
32491
- );
32492
- }
32493
- if (uploaded && createdDevices.length === 0) {
32494
- warnings.push("serve reported success but no new device appeared; check tia_devices.");
32495
- }
32496
- return textResult({
32497
- uploaded,
32498
- uploadOutcome,
32499
- approvedPlanHash: check2.issued.token,
32500
- projectPath: check2.issued.fingerprint,
32501
- state,
32502
- errors,
32503
- uploadedStation: typeof data.uploadedStation === "string" ? data.uploadedStation : null,
32504
- createdDevices,
32505
- configurations: data.configurations ?? null,
32506
- ...warnings.length > 0 ? { warning: warnings.join(" ") } : {},
32507
- nextSteps: [
32508
- "1. Save the project with tia_project_save.",
32509
- "2. Archive it with tia_project_archive \u2014 the .zap21 is the backup (the archive name must carry the .zap21 extension).",
32510
- "3. Optionally compile the new PLC with tia_compile (a GUI-gated license message is not a backup failure)."
32511
- ],
32512
- result: raw ?? null
32513
- });
32514
- }
32515
- function registerVerificationTools(server2) {
32516
- server2.registerTool(
32517
- "tia_compile",
32518
- {
32519
- title: "TIA \u2014 compile (verifier)",
32520
- description: "Compiles the PLC and returns the message tree + a verification summary (Gd8: only ERROR blocks, warnings don't) and nextHints. This is the offline VERIFIER: a clean compile is a precondition (Gd9) for download/S7. Maps to POST /plcs/{plc}/compile. M-off. " + LONG_OPERATION_NOTE,
32521
- inputSchema: { plc: external_exports.string().describe("PLC name") }
32522
- },
32523
- async ({ plc }) => jobs.run("tia_compile", { plc }, () => compileFlow(plc))
32524
- );
32525
- server2.registerTool(
32526
- "tia_connection_create",
32527
- {
32528
- title: "TIA \u2014 create S7 connection",
32529
- description: "Creates an S7 connection between two devices. Guard G2: requires \u22652 CONSISTENT CPUs (compile clean) \u2014 a bare CPU fails. On error, the envelope's 'details' carries the diagnostic (or use tia_connections_diagnose). Maps to POST /connections. M-off.",
32530
- inputSchema: {
32531
- localDevice: external_exports.string().describe("local device"),
32532
- partnerDevice: external_exports.string().describe("partner device")
32533
- }
32534
- },
32535
- async ({ localDevice, partnerDevice }) => send("POST", "/connections", jsonBody2({ localDevice, partnerDevice }))
32536
- );
32537
- server2.registerTool(
32538
- "tia_download",
32539
- {
32540
- title: "TIA \u2014 download to the PLC (GATE G3)",
32541
- description: "Downloads hardware/software to the PHYSICAL CPU (STOPS and RESTARTS the CPU). GATE G3: does NOT download without human approval. dryRun:true asks serve for a VERIFIED plan (clean compile, PG/PC interface found, software fingerprint) and returns a single-use planHash that expires (TIA_PLAN_TTL_MS, default 15 min). After a human approves that plan, call with approved:true and the SAME planHash; serve re-checks the fingerprint inside the download and refuses (plan_stale) if the project changed. Pick connectionMode/pcInterfaceName/targetInterfaceName with tia_pg_interfaces (no scan). Requires app \u2265 v1.6.0. Maps to POST /plcs/{plc}/download/plan and POST /plcs/{plc}/download. " + LONG_OPERATION_NOTE,
32542
- inputSchema: {
32543
- plc: external_exports.string().describe("PLC name"),
32544
- connectionMode: external_exports.string().optional().describe(`connection mode (e.g., "PN/IE") \u2014 TIA's LOCALIZED name`),
32545
- pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized name)"),
32546
- pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
32547
- targetInterfaceName: external_exports.string().optional().describe('target CPU interface (e.g., "1 X1")'),
32548
- hardware: external_exports.boolean().optional().describe("download hardware (default false)"),
32549
- software: external_exports.boolean().optional().describe("download software (default true)"),
32550
- allowUpgradeTargetDevice: external_exports.boolean().optional().describe("confirm TIA's 'upgrade the target device' check (default false). Part of the approved plan \u2014 changing it needs a new dryRun + approval"),
32551
- dryRun: external_exports.boolean().optional().describe("Gd11: returns the plan + planHash WITHOUT downloading"),
32552
- approved: external_exports.boolean().optional().describe("G3: only true after explicit HUMAN APPROVAL"),
32553
- planHash: external_exports.string().optional().describe("G3: the single-use approval token returned by dryRun (issued only by this MCP process; expires)")
32554
- }
32555
- },
32556
- // Handler INTEIRO no job e args inteiros na chave (planHash/approved/conexão incluídos): um busy devolve
32557
- // ANTES de downloadFlow rodar, então o token de uso único só é consumido dentro do job, antes da chamada ao serve.
32558
- async (args) => jobs.run("tia_download", args, () => downloadFlow(args))
32559
- );
32560
- server2.registerTool(
32561
- "tia_upload",
32562
- {
32563
- title: "TIA \u2014 station upload (GATE G4)",
32564
- description: "Station upload (GATE G4): goes ONLINE to the PHYSICAL CPU at `ip` and reads its hardware configuration and program into the OPEN project as a new station \u2014 it reads the CPU and does not write or stop it (observed on hardware: the CPU stayed in RUN). Back up into a dedicated EMPTY project, never the working project (skill tia.backup). Without confirm it asks serve for an upload plan (PG/PC interface resolved, the open project's path and devices \u2014 no network access) and returns a single-use planHash bound to that project; after a human confirms, call again with confirm:true and that planHash. A read-protected CPU needs its read-access password from a HUMAN (G6 \u2014 never invented). Needs the deploy license scope (Basic \u2192 403 scope_required) and app \u2265 v1.6.0. Maps to POST /stations/upload/plan and POST /stations/upload. " + LONG_OPERATION_NOTE,
32565
- inputSchema: {
32566
- ip: external_exports.string().describe("IPv4 of the PHYSICAL CPU"),
32567
- connectionMode: external_exports.string().optional().describe(`connection mode (e.g., "PN/IE") \u2014 TIA's LOCALIZED name`),
32568
- pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized name)"),
32569
- pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
32570
- confirm: external_exports.boolean().optional().describe("G4: true only after explicit HUMAN confirmation"),
32571
- planHash: external_exports.string().optional().describe("G4: the single-use approval token returned by the unconfirmed call (issued only by this MCP process; expires)"),
32572
- password: external_exports.string().optional().describe("G6: the CPU read-access password provided by a HUMAN, never invented")
32573
- }
32574
- },
32575
- // Handler INTEIRO no job e args inteiros na chave (como tia_download): um busy devolve ANTES de uploadFlow
32576
- // rodar, então o token de uso único só é consumido dentro do job, antes da chamada ao serve. A chave é um
32577
- // hash sha256 — a senha nunca aparece em texto plano no estado do job.
32578
- async (args) => jobs.run("tia_upload", args, () => uploadFlow(args))
32579
- );
32580
- server2.registerTool(
32581
- "tia_online",
32582
- {
32583
- title: "TIA \u2014 go online (GATE G4)",
32584
- description: "Connects ONLINE to the physical PLC. GATE G4: pass confirm:true (after a human confirms it's safe to connect to the target machine); without it, returns a handoff. Maps to POST /plcs/{plc}/online.",
32585
- inputSchema: {
32586
- plc: external_exports.string().describe("PLC name"),
32587
- connectionMode: external_exports.string().optional().describe("connection mode (localized)"),
32588
- pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized)"),
32589
- pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
32590
- targetInterfaceName: external_exports.string().optional().describe("target CPU interface"),
32591
- confirm: external_exports.boolean().optional().describe("G4: true after human confirmation")
32592
- }
32593
- },
32594
- async ({ plc, connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName, confirm }) => {
32595
- if (confirm !== true) return gateHandoff("go_online", { plc, plan: { plc, connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName } });
32596
- return send("POST", `/plcs/${seg2(plc)}/online`, jsonBody2({ connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName }), 6e4);
32597
- }
32598
- );
32599
- server2.registerTool(
32600
- "tia_offline",
32601
- {
32602
- title: "TIA \u2014 go offline",
32603
- description: "Disconnects the PLC from online mode. Maps to POST /plcs/{plc}/offline.",
32604
- inputSchema: { plc: external_exports.string().describe("PLC name") }
32605
- },
32606
- async ({ plc }) => send("POST", `/plcs/${seg2(plc)}/offline`)
32607
- );
32608
- server2.registerTool(
32609
- "tia_online_state",
32610
- {
32611
- title: "TIA \u2014 online state",
32612
- description: "Reads the PLC's online state (online/offline). Read-only (class R). Maps to GET /plcs/{plc}/online/state.",
32613
- inputSchema: { plc: external_exports.string().describe("PLC name") }
32614
- },
32615
- async ({ plc }) => {
32616
- try {
32617
- return textResult(await tiaFetch(`/plcs/${seg2(plc)}/online/state`));
32618
- } catch (e) {
32619
- return errorResult2(asTiaError(e));
32620
- }
32621
- }
32622
- );
32623
- server2.registerTool(
32624
- "tia_accessible_devices",
32625
- {
32626
- title: "TIA \u2014 accessible devices (GATE G7)",
32627
- description: "Scans the network via the PG/PC adapter and lists accessible devices \u2014 to see which devices answer on the network \u2014 to discover mode/adapter/interface names WITHOUT a scan, use tia_pg_interfaces. GATE G7 (net scan): pass confirm:true. Maps to POST /plcs/{plc}/online/accessibledevices.",
32628
- inputSchema: {
32629
- plc: external_exports.string().describe("PLC name"),
32630
- connectionMode: external_exports.string().optional().describe("connection mode (localized)"),
32631
- pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized)"),
32632
- pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
32633
- confirm: external_exports.boolean().optional().describe("G7: true after human confirmation")
32634
- }
32635
- },
32636
- async ({ plc, connectionMode, pcInterfaceName, pcInterfaceNumber, confirm }) => {
32637
- if (confirm !== true) return gateHandoff("net_scan", { plc, plan: { plc, connectionMode, pcInterfaceName, pcInterfaceNumber } });
32638
- return send("POST", `/plcs/${seg2(plc)}/online/accessibledevices`, jsonBody2({ connectionMode, pcInterfaceName, pcInterfaceNumber }), 6e4);
32639
- }
32640
- );
32641
- server2.registerTool(
32642
- "tia_mastersecret_set",
32643
- {
32644
- title: "TIA \u2014 set master secret (GATE G6)",
32645
- description: "Sets the master secret (password) of a protected CPU, before online/download. GATE G6: the password comes from a HUMAN (or a credential vault) \u2014 the AI NEVER makes it up. (Note: P3.7 questions sending the secret over HTTP in plain text; prefer local entry on the host.) Maps to POST /plcs/{plc}/online/mastersecret.",
32646
- inputSchema: {
32647
- plc: external_exports.string().describe("PLC name"),
32648
- password: external_exports.string().describe("master secret provided by a human (NEVER made up by the AI)")
32649
- }
32650
- },
32651
- async ({ plc, password }) => send("POST", `/plcs/${seg2(plc)}/online/mastersecret`, jsonBody2({ password }))
32652
- );
32409
+ const notClean = errors !== null && errors > 0;
32410
+ hints.push(
32411
+ notClean ? `This compile changed these block(s): ${exportable.map(describe3).join(", ")}. Fix the ${errors} compile ERROR(s) FIRST (tia_export_block requires a CONSISTENT block), THEN export these blocks with tia_export_block and commit them \u2014 a later compile will NOT list them again.` : `This compile changed these block(s): ${exportable.map(describe3).join(", ")}. Export them (tia_export_block) and commit them, or version control silently drifts from the project.`
32412
+ );
32413
+ }
32414
+ if (removed.length > 0) {
32415
+ const names = removed.map((c) => typeof c.name === "string" && c.name.trim() ? c.name.trim() : "?").join(", ");
32416
+ hints.push(`This compile REMOVED these block(s): ${names}. Nothing to export \u2014 update version control (delete them there too) instead.`);
32417
+ }
32418
+ }
32419
+ if (typeof d.blockChangesError === "string" && d.blockChangesError.trim()) {
32420
+ hints.push(
32421
+ `blockChangesError: the serve could not determine which blocks this compile changed (${d.blockChangesError.trim()}) \u2014 the compile result itself is still valid. Consider exporting and comparing (tia_export_block / tia_block_compare) to be safe.`
32422
+ );
32423
+ }
32424
+ return { located, hints };
32425
+ }
32426
+ async function compileFlow(plc) {
32427
+ try {
32428
+ const data = await tiaFetch(`/plcs/${seg(plc)}/compile`, { method: "POST", headers: JSON_HEADERS, body: "{}" }, { timeoutMs: 12e4 });
32429
+ const d = data ?? {};
32430
+ const errors = typeof d.errors === "number" ? d.errors : null;
32431
+ const clean = errors !== null ? errors === 0 : d.state === "Success";
32432
+ const nextHints = clean ? ["Compile CLEAN (Gd8: warnings don't block). Ready for gated download (tia_download) or S7 connection."] : [`Compile with ${errors ?? "?"} ERROR(s) \u2014 fix BEFORE download/S7 (Gd9 forbids a non-clean deploy). See 'messages' (tree).`];
32433
+ const guiGateHints = detectGuiGateHints(d.messages);
32434
+ const { located, hints } = summarizeCompile(d);
32435
+ nextHints.push(...hints);
32436
+ return textResult({
32437
+ ...d,
32438
+ verification: { compiled: clean ? "clean" : "error", errors, warnings: d.warnings ?? null },
32439
+ nextHints,
32440
+ ...guiGateHints.length > 0 ? { guiGateHints } : {},
32441
+ ...located.length > 0 ? { located } : {}
32442
+ });
32443
+ } catch (e) {
32444
+ return errorResult(asTiaError(e));
32445
+ }
32446
+ }
32447
+ function registerCompileTools(server2) {
32653
32448
  server2.registerTool(
32654
- "tia_mastersecret_reset",
32449
+ "tia_compile",
32655
32450
  {
32656
- title: "TIA \u2014 reset master secret",
32657
- description: "Removes/resets the CPU's master secret. Maps to DELETE /plcs/{plc}/online/mastersecret.",
32451
+ title: "TIA \u2014 compile (verifier)",
32452
+ description: "Compiles the PLC and returns the message tree + a verification summary (Gd8: only ERROR blocks, warnings don't) and nextHints. This is the offline VERIFIER: a clean compile is a precondition (Gd9) for download/S7. Maps to POST /plcs/{plc}/compile. M-off. " + LONG_OPERATION_NOTE,
32658
32453
  inputSchema: { plc: external_exports.string().describe("PLC name") }
32659
32454
  },
32660
- async ({ plc }) => send("DELETE", `/plcs/${seg2(plc)}/online/mastersecret`)
32455
+ async ({ plc }) => jobs.run("tia_compile", { plc }, () => compileFlow(plc))
32661
32456
  );
32662
32457
  }
32663
32458
 
@@ -32716,18 +32511,6 @@ function compareSimaticMl(left, right, opts = {}) {
32716
32511
  }
32717
32512
 
32718
32513
  // src/tools/authoring.ts
32719
- var seg3 = (v) => encodeURIComponent(v);
32720
- function jsonBody3(obj) {
32721
- const out = {};
32722
- for (const [k, v] of Object.entries(obj)) if (v !== void 0 && v !== null) out[k] = v;
32723
- return out;
32724
- }
32725
- function errorResult3(err) {
32726
- return textResult(
32727
- { error: err.message, kind: err.kind, status: err.status, type: err.type, details: err.details ?? null, hint: hintFor(err) },
32728
- true
32729
- );
32730
- }
32731
32514
  function gd5Violation(typeIdentifier) {
32732
32515
  if (!typeIdentifier) return null;
32733
32516
  if (/:V\d/.test(typeIdentifier)) {
@@ -32768,13 +32551,13 @@ async function mutate(method, path, body, opts) {
32768
32551
  const data = await tiaFetch(path, init, { timeoutMs: SLOW_TIMEOUT_MS });
32769
32552
  return textResult(data);
32770
32553
  } catch (e) {
32771
- return errorResult3(asTiaError(e));
32554
+ return errorResult(asTiaError(e));
32772
32555
  }
32773
32556
  }
32774
32557
  async function deviceCreateFlow(args) {
32775
32558
  const bad = gd5Violation(args.typeIdentifier);
32776
32559
  if (bad) return guardError("Gd5", bad, { typeIdentifier: args.typeIdentifier });
32777
- return mutate("POST", "/devices", jsonBody3({ typeIdentifier: args.typeIdentifier, deviceItemName: args.deviceItemName, deviceName: args.deviceName }), {
32560
+ return mutate("POST", "/devices", jsonBody({ typeIdentifier: args.typeIdentifier, deviceItemName: args.deviceItemName, deviceName: args.deviceName }), {
32778
32561
  dryRun: args.dryRun,
32779
32562
  summary: `create device "${args.deviceName ?? args.deviceItemName ?? "?"}" (${args.typeIdentifier})`
32780
32563
  });
@@ -32783,7 +32566,7 @@ var FW_CHANGE_RESET_WARNING = `DeviceItem.ChangeType RESETS GUI-gated comm setti
32783
32566
  async function deviceChangeVersionFlow(args) {
32784
32567
  const bad = gd5Violation(args.typeIdentifier);
32785
32568
  if (bad) return guardError("Gd5", bad, { typeIdentifier: args.typeIdentifier });
32786
- const r = await mutate("POST", `/plcs/${seg3(args.plc)}/device/changeversion`, jsonBody3({ typeIdentifier: args.typeIdentifier, dryRun: args.dryRun }), {
32569
+ const r = await mutate("POST", `/plcs/${seg(args.plc)}/device/changeversion`, jsonBody({ typeIdentifier: args.typeIdentifier, dryRun: args.dryRun }), {
32787
32570
  dryRun: args.dryRun,
32788
32571
  summary: `change firmware of CPU "${args.plc}" to ${args.typeIdentifier}`
32789
32572
  });
@@ -32792,7 +32575,7 @@ async function deviceChangeVersionFlow(args) {
32792
32575
  return textResult({ ...data, fwChangeReset: FW_CHANGE_RESET_WARNING });
32793
32576
  }
32794
32577
  async function sourcePutFlow(args) {
32795
- const r = await mutate("POST", `/plcs/${seg3(args.plc)}/source`, jsonBody3({ name: args.name, code: args.code, compile: args.compile }), {
32578
+ const r = await mutate("POST", `/plcs/${seg(args.plc)}/source`, jsonBody({ name: args.name, code: args.code, compile: args.compile }), {
32796
32579
  dryRun: args.dryRun,
32797
32580
  summary: `write SCL ${args.name} on ${args.plc}`
32798
32581
  });
@@ -32805,7 +32588,7 @@ async function sourcePutFlow(args) {
32805
32588
  return textResult({ ...data, ...located.length > 0 ? { located } : {}, ...hints.length > 0 ? { nextHints: hints } : {} });
32806
32589
  }
32807
32590
  async function importXmlFlow(args) {
32808
- const r = await mutate("POST", `/plcs/${seg3(args.plc)}/import`, jsonBody3({ xml: args.xml, path: args.path, override: args.override }), {
32591
+ const r = await mutate("POST", `/plcs/${seg(args.plc)}/import`, jsonBody({ xml: args.xml, path: args.path, override: args.override }), {
32809
32592
  dryRun: args.dryRun,
32810
32593
  summary: `import XML on ${args.plc}`
32811
32594
  });
@@ -32883,7 +32666,7 @@ function registerAuthoringTools(server2) {
32883
32666
  async ({ device, typeIdentifier, name, position, host, dryRun }) => {
32884
32667
  const bad = gd5Violation(typeIdentifier);
32885
32668
  if (bad) return guardError("Gd5", bad, { typeIdentifier });
32886
- return mutate("POST", `/devices/${seg3(device)}/plug`, jsonBody3({ typeIdentifier, name, position, host }), {
32669
+ return mutate("POST", `/devices/${seg(device)}/plug`, jsonBody({ typeIdentifier, name, position, host }), {
32887
32670
  dryRun,
32888
32671
  summary: `plug "${name ?? typeIdentifier}" into ${device}`
32889
32672
  });
@@ -32900,7 +32683,7 @@ function registerAuthoringTools(server2) {
32900
32683
  ...dryRunField
32901
32684
  }
32902
32685
  },
32903
- async ({ device, item, dryRun }) => mutate("DELETE", `/devices/${seg3(device)}/items/${seg3(item)}`, void 0, { dryRun, summary: `unplug ${item} from ${device}` })
32686
+ async ({ device, item, dryRun }) => mutate("DELETE", `/devices/${seg(device)}/items/${seg(item)}`, void 0, { dryRun, summary: `unplug ${item} from ${device}` })
32904
32687
  );
32905
32688
  server2.registerTool(
32906
32689
  "tia_device_group_create",
@@ -32909,7 +32692,7 @@ function registerAuthoringTools(server2) {
32909
32692
  description: "Creates a device group. Maps to POST /devicegroups. M-off.",
32910
32693
  inputSchema: { name: external_exports.string().describe("group name"), ...dryRunField }
32911
32694
  },
32912
- async ({ name, dryRun }) => mutate("POST", "/devicegroups", jsonBody3({ name }), { dryRun, summary: `create device group ${name}` })
32695
+ async ({ name, dryRun }) => mutate("POST", "/devicegroups", jsonBody({ name }), { dryRun, summary: `create device group ${name}` })
32913
32696
  );
32914
32697
  server2.registerTool(
32915
32698
  "tia_subnet_create",
@@ -32925,7 +32708,7 @@ function registerAuthoringTools(server2) {
32925
32708
  async ({ typeIdentifier, name, dryRun }) => {
32926
32709
  const bad = gd5Violation(typeIdentifier);
32927
32710
  if (bad) return guardError("Gd5", bad, { typeIdentifier });
32928
- return mutate("POST", "/subnets", jsonBody3({ typeIdentifier, name }), { dryRun, summary: `create subnet ${name ?? typeIdentifier}` });
32711
+ return mutate("POST", "/subnets", jsonBody({ typeIdentifier, name }), { dryRun, summary: `create subnet ${name ?? typeIdentifier}` });
32929
32712
  }
32930
32713
  );
32931
32714
  server2.registerTool(
@@ -32942,7 +32725,7 @@ function registerAuthoringTools(server2) {
32942
32725
  ...dryRunField
32943
32726
  }
32944
32727
  },
32945
- async ({ device, subnet, ip, createIoSystem, ioSystemName, dryRun }) => mutate("POST", "/network/connect", jsonBody3({ device, subnet, ip, createIoSystem, ioSystemName }), {
32728
+ async ({ device, subnet, ip, createIoSystem, ioSystemName, dryRun }) => mutate("POST", "/network/connect", jsonBody({ device, subnet, ip, createIoSystem, ioSystemName }), {
32946
32729
  dryRun,
32947
32730
  summary: `connect ${device} to subnet ${subnet}${ip ? " @" + ip : ""}`
32948
32731
  })
@@ -32958,7 +32741,7 @@ function registerAuthoringTools(server2) {
32958
32741
  ...dryRunField
32959
32742
  }
32960
32743
  },
32961
- async ({ device, attributes, dryRun }) => mutate("POST", "/network/address", jsonBody3({ device, attributes }), { dryRun, summary: `address ${device}` })
32744
+ async ({ device, attributes, dryRun }) => mutate("POST", "/network/address", jsonBody({ device, attributes }), { dryRun, summary: `address ${device}` })
32962
32745
  );
32963
32746
  server2.registerTool(
32964
32747
  "tia_network_disconnect",
@@ -32967,7 +32750,7 @@ function registerAuthoringTools(server2) {
32967
32750
  description: "Disconnects a device's interface from the subnet. Maps to POST /network/disconnect. M-off.",
32968
32751
  inputSchema: { device: external_exports.string().describe("device name"), ...dryRunField }
32969
32752
  },
32970
- async ({ device, dryRun }) => mutate("POST", "/network/disconnect", jsonBody3({ device }), { dryRun, summary: `disconnect ${device} from the subnet` })
32753
+ async ({ device, dryRun }) => mutate("POST", "/network/disconnect", jsonBody({ device }), { dryRun, summary: `disconnect ${device} from the subnet` })
32971
32754
  );
32972
32755
  server2.registerTool(
32973
32756
  "tia_tagtable_create",
@@ -32976,7 +32759,7 @@ function registerAuthoringTools(server2) {
32976
32759
  description: "Creates a tag table on a PLC. Maps to POST /plcs/{plc}/tagtables. M-off.",
32977
32760
  inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("table name"), ...dryRunField }
32978
32761
  },
32979
- async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/tagtables`, jsonBody3({ name }), { dryRun, summary: `create tag table ${name} on ${plc}` })
32762
+ async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/tagtables`, jsonBody({ name }), { dryRun, summary: `create tag table ${name} on ${plc}` })
32980
32763
  );
32981
32764
  server2.registerTool(
32982
32765
  "tia_tag_create",
@@ -32992,7 +32775,7 @@ function registerAuthoringTools(server2) {
32992
32775
  ...dryRunField
32993
32776
  }
32994
32777
  },
32995
- async ({ plc, table, name, dataType, address, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/tags`, jsonBody3({ table, name, dataType, address }), { dryRun, summary: `create tag ${name}:${dataType} on ${plc}` })
32778
+ async ({ plc, table, name, dataType, address, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/tags`, jsonBody({ table, name, dataType, address }), { dryRun, summary: `create tag ${name}:${dataType} on ${plc}` })
32996
32779
  );
32997
32780
  server2.registerTool(
32998
32781
  "tia_tag_delete",
@@ -33006,7 +32789,7 @@ function registerAuthoringTools(server2) {
33006
32789
  ...dryRunField
33007
32790
  }
33008
32791
  },
33009
- async ({ plc, table, tag, dryRun }) => mutate("DELETE", `/plcs/${seg3(plc)}/tagtables/${seg3(table)}/tags/${seg3(tag)}`, void 0, { dryRun, summary: `delete tag ${tag}` })
32792
+ async ({ plc, table, tag, dryRun }) => mutate("DELETE", `/plcs/${seg(plc)}/tagtables/${seg(table)}/tags/${seg(tag)}`, void 0, { dryRun, summary: `delete tag ${tag}` })
33010
32793
  );
33011
32794
  server2.registerTool(
33012
32795
  "tia_constant_create",
@@ -33022,7 +32805,7 @@ function registerAuthoringTools(server2) {
33022
32805
  ...dryRunField
33023
32806
  }
33024
32807
  },
33025
- async ({ plc, table, name, dataType, value, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/constants`, jsonBody3({ table, name, dataType, value }), { dryRun, summary: `create constant ${name} on ${plc}` })
32808
+ async ({ plc, table, name, dataType, value, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/constants`, jsonBody({ table, name, dataType, value }), { dryRun, summary: `create constant ${name} on ${plc}` })
33026
32809
  );
33027
32810
  server2.registerTool(
33028
32811
  "tia_fb_create",
@@ -33039,7 +32822,7 @@ function registerAuthoringTools(server2) {
33039
32822
  ...dryRunField
33040
32823
  }
33041
32824
  },
33042
- async ({ plc, name, language, autoNumber, number: number4, group, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/fbs`, jsonBody3({ name, language, autoNumber, number: number4, group }), { dryRun, summary: `create FB ${name} on ${plc}` })
32825
+ async ({ plc, name, language, autoNumber, number: number4, group, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/fbs`, jsonBody({ name, language, autoNumber, number: number4, group }), { dryRun, summary: `create FB ${name} on ${plc}` })
33043
32826
  );
33044
32827
  server2.registerTool(
33045
32828
  "tia_instancedb_create",
@@ -33056,7 +32839,7 @@ function registerAuthoringTools(server2) {
33056
32839
  ...dryRunField
33057
32840
  }
33058
32841
  },
33059
- async ({ plc, name, instanceOf, autoNumber, number: number4, group, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/instancedbs`, jsonBody3({ name, instanceOf, autoNumber, number: number4, group }), {
32842
+ async ({ plc, name, instanceOf, autoNumber, number: number4, group, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/instancedbs`, jsonBody({ name, instanceOf, autoNumber, number: number4, group }), {
33060
32843
  dryRun,
33061
32844
  summary: `create iDB ${name} from ${instanceOf} on ${plc}`
33062
32845
  })
@@ -33068,7 +32851,7 @@ function registerAuthoringTools(server2) {
33068
32851
  description: "Deletes a block. Maps to DELETE /plcs/{plc}/blocks/{block}. M-off.",
33069
32852
  inputSchema: { plc: external_exports.string().describe("PLC name"), block: external_exports.string().describe("block name"), ...dryRunField }
33070
32853
  },
33071
- async ({ plc, block, dryRun }) => mutate("DELETE", `/plcs/${seg3(plc)}/blocks/${seg3(block)}`, void 0, { dryRun, summary: `delete block ${block}` })
32854
+ async ({ plc, block, dryRun }) => mutate("DELETE", `/plcs/${seg(plc)}/blocks/${seg(block)}`, void 0, { dryRun, summary: `delete block ${block}` })
33072
32855
  );
33073
32856
  server2.registerTool(
33074
32857
  "tia_block_set_attribute",
@@ -33083,7 +32866,7 @@ function registerAuthoringTools(server2) {
33083
32866
  ...dryRunField
33084
32867
  }
33085
32868
  },
33086
- async ({ plc, block, name, value, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/blocks/${seg3(block)}/attributes`, jsonBody3({ name, value }), {
32869
+ async ({ plc, block, name, value, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/blocks/${seg(block)}/attributes`, jsonBody({ name, value }), {
33087
32870
  dryRun,
33088
32871
  summary: `set ${name} on ${block}`
33089
32872
  })
@@ -33095,7 +32878,7 @@ function registerAuthoringTools(server2) {
33095
32878
  description: "Creates a block group. Maps to POST /plcs/{plc}/blockgroups. M-off.",
33096
32879
  inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("group name"), ...dryRunField }
33097
32880
  },
33098
- async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/blockgroups`, jsonBody3({ name }), { dryRun, summary: `create block group ${name}` })
32881
+ async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/blockgroups`, jsonBody({ name }), { dryRun, summary: `create block group ${name}` })
33099
32882
  );
33100
32883
  server2.registerTool(
33101
32884
  "tia_type_group_create",
@@ -33104,7 +32887,7 @@ function registerAuthoringTools(server2) {
33104
32887
  description: "Creates a type group (UDTs). Maps to POST /plcs/{plc}/typegroups. M-off.",
33105
32888
  inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("group name"), ...dryRunField }
33106
32889
  },
33107
- async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/typegroups`, jsonBody3({ name }), { dryRun, summary: `create type group ${name}` })
32890
+ async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/typegroups`, jsonBody({ name }), { dryRun, summary: `create type group ${name}` })
33108
32891
  );
33109
32892
  server2.registerTool(
33110
32893
  "tia_type_delete",
@@ -33113,230 +32896,958 @@ function registerAuthoringTools(server2) {
33113
32896
  description: "Deletes a type (UDT). Maps to DELETE /plcs/{plc}/types/{type}. M-off.",
33114
32897
  inputSchema: { plc: external_exports.string().describe("PLC name"), type: external_exports.string().describe("type name"), ...dryRunField }
33115
32898
  },
33116
- async ({ plc, type, dryRun }) => mutate("DELETE", `/plcs/${seg3(plc)}/types/${seg3(type)}`, void 0, { dryRun, summary: `delete type ${type}` })
32899
+ async ({ plc, type, dryRun }) => mutate("DELETE", `/plcs/${seg(plc)}/types/${seg(type)}`, void 0, { dryRun, summary: `delete type ${type}` })
32900
+ );
32901
+ server2.registerTool(
32902
+ "tia_source_put",
32903
+ {
32904
+ title: "TIA \u2014 write/compile SCL source",
32905
+ description: `Writes a block from textual SCL source and (optionally) compiles it. Gd6: use THIS for TEXTUAL language (SCL/STL); for graphical (LAD/FBD/GRAPH) use tia_import_xml. With compile:true, the raw compile DTO is nested under 'compile' (same as tia_compile's response), and 'located[]' plus a nextHint are merged at the TOP LEVEL of the result \u2014 same place tia_compile puts them \u2014 when the compile regenerated blocks, e.g. an instance DB after an FB interface change. \`generatedOrUpdated\` lists every block the source created or regenerated (app \u2265 v1.6.0; older serves list only new ones) \u2014 TIA regenerates a block even when the text is identical, so it then needs a compile \u2014 and \`sourceChanges\` gives the per-block change and parts. Maps to POST /plcs/{plc}/source. M-off. ${LONG_OPERATION_NOTE}`,
32906
+ inputSchema: {
32907
+ plc: external_exports.string().describe("PLC name"),
32908
+ name: external_exports.string().describe("block/source name"),
32909
+ code: external_exports.string().describe("SCL source code"),
32910
+ compile: external_exports.boolean().optional().describe("compile after generating (default false)"),
32911
+ ...dryRunField
32912
+ }
32913
+ },
32914
+ // dryRun is pure (never calls serve) and stays outside the runner, like tia_spec_apply.
32915
+ async ({ plc, name, code, compile, dryRun }) => dryRun ? sourcePutFlow({ plc, name, code, compile, dryRun }) : jobs.run("tia_source_put", { plc, name, code, compile }, () => sourcePutFlow({ plc, name, code, compile }))
32916
+ );
32917
+ server2.registerTool(
32918
+ "tia_import_xml",
32919
+ {
32920
+ title: "TIA \u2014 import block (SimaticML XML)",
32921
+ description: "Imports a block in SimaticML XML (the only path for LAD/FBD/GRAPH \u2014 Gd6). PREFER `xml` inline (tested up to ~300 KB: 280 KB imported in 1\u20135 s); use `path` ONLY for a file that is already on the serve host \u2014 never copy files to the host to import them. Gd7: SimaticML version must match V21. Import UDTs FIRST (tia_types_import). Returns, per block, type/number/created/interfaceChanged/affectedInstanceDbs, and \u2014 when `xml` was sent inline \u2014 a transport check (sha256 sent vs received). Requires app \u2265 v1.6.0 for the receipt; with an older serve transport.match is null and there are no per-block fields. An FB whose interface changed makes the next compile regenerate its instance DBs. Maps to POST /plcs/{plc}/import. M-off.",
32922
+ inputSchema: {
32923
+ plc: external_exports.string().describe("PLC name"),
32924
+ xml: external_exports.string().optional().describe("SimaticML XML content (alternative to path)"),
32925
+ path: external_exports.string().optional().describe("path to the .xml on the serve host (alternative to xml)"),
32926
+ override: external_exports.boolean().optional().describe("overwrite if it already exists (default true)"),
32927
+ ...dryRunField
32928
+ }
32929
+ },
32930
+ async ({ plc, xml, path, override, dryRun }) => importXmlFlow({ plc, xml, path, override, dryRun })
32931
+ );
32932
+ server2.registerTool(
32933
+ "tia_types_import",
32934
+ {
32935
+ title: "TIA \u2014 import type/UDT (SimaticML XML)",
32936
+ description: "Imports a UDT in SimaticML XML. Import UDTs BEFORE the blocks that use them (Gd6). Maps to POST /plcs/{plc}/types/import. M-off.",
32937
+ inputSchema: {
32938
+ plc: external_exports.string().describe("PLC name"),
32939
+ xml: external_exports.string().optional().describe("SimaticML XML content of the UDT (alternative to path)"),
32940
+ path: external_exports.string().optional().describe("path to the .xml on the host (alternative to xml)"),
32941
+ override: external_exports.boolean().optional().describe("overwrite if it already exists (default true)"),
32942
+ ...dryRunField
32943
+ }
32944
+ },
32945
+ async ({ plc, xml, path, override, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/types/import`, jsonBody({ xml, path, override }), { dryRun, summary: `import UDT on ${plc}` })
32946
+ );
32947
+ server2.registerTool(
32948
+ "tia_export_xml",
32949
+ {
32950
+ title: "TIA \u2014 export blocks/types (SimaticML XML)",
32951
+ description: "Exports the PLC's blocks and types to SimaticML XML files in a directory (project-as-code). Maps to POST /plcs/{plc}/export. M-off. " + LONG_OPERATION_NOTE,
32952
+ inputSchema: {
32953
+ plc: external_exports.string().describe("PLC name"),
32954
+ directory: external_exports.string().describe("target directory on the serve host"),
32955
+ ...dryRunField
32956
+ }
32957
+ },
32958
+ async ({ plc, directory, dryRun }) => jobs.run(
32959
+ "tia_export_xml",
32960
+ { plc, directory, dryRun },
32961
+ () => mutate("POST", `/plcs/${seg(plc)}/export`, jsonBody({ directory }), { dryRun, summary: `export XML from ${plc} to ${directory}` })
32962
+ )
32963
+ );
32964
+ server2.registerTool(
32965
+ "tia_watchtable_create",
32966
+ {
32967
+ title: "TIA \u2014 create watch table",
32968
+ description: "Creates a watch table. Maps to POST /plcs/{plc}/watchtables. M-off.",
32969
+ inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("watch table name"), ...dryRunField }
32970
+ },
32971
+ async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/watchtables`, jsonBody({ name }), { dryRun, summary: `create watch table ${name}` })
32972
+ );
32973
+ server2.registerTool(
32974
+ "tia_watchtable_delete",
32975
+ {
32976
+ title: "TIA \u2014 delete watch table",
32977
+ description: "Deletes a watch table. Maps to DELETE /plcs/{plc}/watchtables/{wt}. M-off.",
32978
+ inputSchema: { plc: external_exports.string().describe("PLC name"), watchtable: external_exports.string().describe("watch table name"), ...dryRunField }
32979
+ },
32980
+ async ({ plc, watchtable, dryRun }) => mutate("DELETE", `/plcs/${seg(plc)}/watchtables/${seg(watchtable)}`, void 0, { dryRun, summary: `delete watch table ${watchtable}` })
32981
+ );
32982
+ server2.registerTool(
32983
+ "tia_obj_service",
32984
+ {
32985
+ title: "TIA \u2014 acquire service (GetService\u2192handle)",
32986
+ description: "Acquires a service from an object by handle (generic GetService<T>) and returns a service HANDLE, to then invoke methods via tia_obj_invoke. E.g.: PlcMasterSecretConfigurator.Protect \u2014 unlocks a bare CPU (offline confidential-data password; generates the certificate). The acquisition itself does NOT mutate the project. Maps to POST /obj/{handle}/service {type}. M-off.",
32987
+ inputSchema: {
32988
+ handle: external_exports.string().describe("object handle (e.g., the CPU's device item)"),
32989
+ type: external_exports.string().describe("service type name (e.g., Siemens.Engineering.HW.Features.PlcMasterSecretConfigurator)")
32990
+ }
32991
+ },
32992
+ async ({ handle, type }) => mutate("POST", `/obj/${seg(handle)}/service`, jsonBody({ type }), { summary: `acquire service ${type} from obj ${handle}` })
32993
+ );
32994
+ server2.registerTool(
32995
+ "tia_obj_set_attributes",
32996
+ {
32997
+ title: "TIA \u2014 set attributes (generic)",
32998
+ description: "Sets attributes of any model object by handle. Maps to POST /obj/{handle}/attributes. M-off. Use the handles from the read-only obj tools (M1).",
32999
+ inputSchema: {
33000
+ handle: external_exports.string().describe("object handle (from the read-only tia_obj_* tools)"),
33001
+ attributes: external_exports.record(external_exports.string(), external_exports.unknown()).describe("name\u2192value map of attributes to set"),
33002
+ ...dryRunField
33003
+ }
33004
+ },
33005
+ async ({ handle, attributes, dryRun }) => mutate("POST", `/obj/${seg(handle)}/attributes`, jsonBody({ ...attributes }), { dryRun, summary: `set attributes on obj ${handle}` })
33006
+ );
33007
+ server2.registerTool(
33008
+ "tia_obj_invoke",
33009
+ {
33010
+ title: "TIA \u2014 invoke method (generic)",
33011
+ description: 'Invokes a method of a model object by handle (args coerced to the parameter types; {"$handle":N} passes another object). Maps to POST /obj/{handle}/invoke. M-off. Powerful \u2014 combine with tia_obj_info to see the signature.',
33012
+ inputSchema: {
33013
+ handle: external_exports.string().describe("object handle"),
33014
+ name: external_exports.string().describe("name of the method to invoke"),
33015
+ args: external_exports.array(external_exports.unknown()).optional().describe("positional arguments (coerced to the parameter types)"),
33016
+ ...dryRunField
33017
+ }
33018
+ },
33019
+ async ({ handle, name, args, dryRun }) => mutate("POST", `/obj/${seg(handle)}/invoke`, jsonBody({ name, args }), { dryRun, summary: `invoke ${name}() on obj ${handle}` })
33020
+ );
33021
+ server2.registerTool(
33022
+ "tia_obj_create",
33023
+ {
33024
+ title: "TIA \u2014 create object (generic)",
33025
+ description: "Creates an object in a composition of a parent object by handle. Maps to POST /obj/{handle}/create. M-off. See the creatable types in tia_obj_creationinfos.",
33026
+ inputSchema: {
33027
+ handle: external_exports.string().describe("parent object handle"),
33028
+ composition: external_exports.string().describe("composition name (e.g., 'Blocks')"),
33029
+ type: external_exports.string().describe("type to create (Siemens type)"),
33030
+ parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("constructor parameters (name\u2192value)"),
33031
+ ...dryRunField
33032
+ }
33033
+ },
33034
+ async ({ handle, composition, type, parameters, dryRun }) => mutate("POST", `/obj/${seg(handle)}/create`, jsonBody({ composition, type, parameters }), {
33035
+ dryRun,
33036
+ summary: `create ${type} in ${composition} of obj ${handle}`
33037
+ })
33038
+ );
33039
+ }
33040
+
33041
+ // src/tools/asCode.ts
33042
+ async function fetchBlockXml(plc, block, options) {
33043
+ const q = options ? `?options=${encodeURIComponent(options)}` : "";
33044
+ return await tiaFetch(`/plcs/${seg(plc)}/blocks/${seg(block)}/xml${q}`, {}, { timeoutMs: SLOW_TIMEOUT_MS });
33045
+ }
33046
+ async function exportBlockFlow(plc, block, options) {
33047
+ try {
33048
+ const d = await fetchBlockXml(plc, block, options);
33049
+ return textResult({
33050
+ name: d.name,
33051
+ options: d.options,
33052
+ sha256: sha256Utf8(d.xml),
33053
+ normalizedSha256: sha256Utf8(normalizeSimaticMl(d.xml)),
33054
+ bytes: Buffer.byteLength(d.xml, "utf8"),
33055
+ hashNote: "sha256 = SHA-256 of the XML text as UTF-8 without BOM, line endings as TIA wrote them (CRLF). A git checkout (LF/BOM) or another export (<Created>, UIds) differs byte-wise \u2014 prove equality with tia_block_compare.",
33056
+ xml: d.xml
33057
+ });
33058
+ } catch (e) {
33059
+ return errorResult(asTiaError(e));
33060
+ }
33061
+ }
33062
+ async function blockCompareFlow(args) {
33063
+ try {
33064
+ const d = await fetchBlockXml(args.plc, args.block, args.options);
33065
+ const opts = { ignoreFormatting: args.ignoreFormatting };
33066
+ const r = compareSimaticMl(d.xml, args.xml, opts);
33067
+ return textResult({
33068
+ block: d.name,
33069
+ verdict: r.equal ? "equal" : "different",
33070
+ ...r,
33071
+ projectNormalizedSha256: sha256Utf8(normalizeSimaticMl(d.xml, opts)),
33072
+ givenNormalizedSha256: sha256Utf8(normalizeSimaticMl(args.xml, opts)),
33073
+ note: "left = the block exported from the project now; right = the XML you passed (e.g. the file in git)."
33074
+ });
33075
+ } catch (e) {
33076
+ return errorResult(asTiaError(e));
33077
+ }
33078
+ }
33079
+ function registerAsCodeTools(server2) {
33080
+ server2.registerTool(
33081
+ "tia_export_block",
33082
+ {
33083
+ title: "TIA \u2014 export one block (SimaticML, inline)",
33084
+ description: "Exports ONE block as SimaticML XML and returns it INLINE with sha256, normalizedSha256 and bytes \u2014 no file on the serve host. Read-mostly \u2014 it does not change code/data, but the export may compile an inconsistent block first if needed (export requires consistency), which can regenerate its instance DB; treated as read for agent tool policy. Maps to GET /plcs/{plc}/blocks/{block}/xml. " + LONG_OPERATION_NOTE,
33085
+ inputSchema: {
33086
+ plc: external_exports.string().describe("PLC name"),
33087
+ block: external_exports.string().describe("block name"),
33088
+ options: external_exports.string().optional().describe("ExportOptions: None (default), WithDefaults, WithReadOnly (comma-separated)")
33089
+ }
33090
+ },
33091
+ async ({ plc, block, options }) => jobs.run("tia_export_block", { plc, block, options }, () => exportBlockFlow(plc, block, options))
33092
+ );
33093
+ server2.registerTool(
33094
+ "tia_block_compare",
33095
+ {
33096
+ title: "TIA \u2014 compare a block with given SimaticML",
33097
+ description: "Exports the block from the project and compares it with the SimaticML you pass (e.g. the file committed in git). Like tia_export_block, this may compile an inconsistent block first (export requires consistency), which can regenerate its instance DB; read-mostly, treated as read for agent tool policy. Normalized: ignores BOM, line endings, indentation, blank lines, <Created>, <InstalledProducts>, UId attributes and \u2014 unless ignoreFormatting:false \u2014 <NewLine/>/<Blank/> formatting tokens (see the result's `ignored` field for the exact list). Returns verdict equal|different and the first differing line. This is the proof that the project contains what was versioned. Maps to GET /plcs/{plc}/blocks/{block}/xml. " + LONG_OPERATION_NOTE,
33098
+ inputSchema: {
33099
+ plc: external_exports.string().describe("PLC name"),
33100
+ block: external_exports.string().describe("block name"),
33101
+ xml: external_exports.string().describe("SimaticML XML to compare against (e.g. the committed file's content)"),
33102
+ ignoreFormatting: external_exports.boolean().optional().describe("ignore <NewLine/>/<Blank/> code-formatting tokens (default true)"),
33103
+ options: external_exports.string().optional().describe("ExportOptions used for the project side (default None)")
33104
+ }
33105
+ },
33106
+ async (args) => jobs.run("tia_block_compare", args, () => blockCompareFlow(args))
33107
+ );
33108
+ }
33109
+
33110
+ // src/planStore.ts
33111
+ import { randomBytes as randomBytes2 } from "node:crypto";
33112
+ var PLAN_TTL_MS = parsePositiveInt(process.env.TIA_PLAN_TTL_MS, 9e5);
33113
+ function canonicalPlan(plan) {
33114
+ for (const [k, v] of Object.entries(plan)) {
33115
+ if (v !== null && typeof v === "object") {
33116
+ throw new Error(`canonicalPlan: nested value at key '${k}' is not allowed (the G3 plan must be flat)`);
33117
+ }
33118
+ }
33119
+ return JSON.stringify(plan, Object.keys(plan).sort());
33120
+ }
33121
+ var PlanStore = class {
33122
+ constructor(ttlMs = PLAN_TTL_MS, now = Date.now, prefix = "g3_") {
33123
+ this.ttlMs = ttlMs;
33124
+ this.now = now;
33125
+ this.prefix = prefix;
33126
+ }
33127
+ ttlMs;
33128
+ now;
33129
+ prefix;
33130
+ issued = /* @__PURE__ */ new Map();
33131
+ consumed = /* @__PURE__ */ new Set();
33132
+ issue(plan, fingerprint) {
33133
+ if (!fingerprint) throw new Error("planStore.issue: fingerprint is required");
33134
+ canonicalPlan(plan);
33135
+ const t = this.now();
33136
+ const entry = {
33137
+ token: `${this.prefix}${randomBytes2(12).toString("base64url")}`,
33138
+ plan: { ...plan },
33139
+ fingerprint,
33140
+ issuedAt: t,
33141
+ expiresAt: t + this.ttlMs
33142
+ };
33143
+ this.issued.set(entry.token, entry);
33144
+ return entry;
33145
+ }
33146
+ check(token, plan) {
33147
+ if (!token) return { ok: false, reason: "unknown" };
33148
+ if (this.consumed.has(token)) return { ok: false, reason: "consumed" };
33149
+ const entry = this.issued.get(token);
33150
+ if (!entry) return { ok: false, reason: "unknown" };
33151
+ if (this.now() > entry.expiresAt) return { ok: false, reason: "expired" };
33152
+ if (canonicalPlan(entry.plan) !== canonicalPlan(plan)) return { ok: false, reason: "plan_mismatch" };
33153
+ return { ok: true, issued: entry };
33154
+ }
33155
+ /** Marca como usado ANTES de chamar o serve: um retry após timeout do cliente é recusado (sem download duplicado). */
33156
+ consume(token) {
33157
+ this.issued.delete(token);
33158
+ this.consumed.add(token);
33159
+ }
33160
+ };
33161
+ var planStore = new PlanStore();
33162
+ var uploadPlanStore = new PlanStore(PLAN_TTL_MS, Date.now, "g4_");
33163
+
33164
+ // src/tools/gates.ts
33165
+ var GATE_INSTRUCTION = {
33166
+ download_approval: "A human must APPROVE the download: it STOPS the physical CPU (StopAll), OVERWRITES system data, and RESTARTS the CPU. Review the plan AND its software fingerprint (what exactly goes to the CPU). The serve auto-confirms Stop/Reset(DeleteAll, when the loaded program is replaced)/Overwrite/Consistent-blocks/Start (listed in 'configurations' after the download).",
33167
+ go_online: "Going ONLINE connects to the PHYSICAL PLC over the network. Confirm with a human that it is safe to connect to the target machine.",
33168
+ station_upload: "GATE G4: a station upload goes ONLINE to the PHYSICAL CPU and reads its hardware configuration and program into the OPEN project as a new station (it reads the CPU and does not write or stop it \u2014 observed on hardware: the CPU stayed in RUN). Confirm with a human that it is safe to connect to this machine AND that the open project shown here is a dedicated backup project \u2014 never the working project.",
33169
+ upload_password: "GATE G6: the CPU is read-protected. Ask the human for its read-access password \u2014 NEVER invent, guess or reuse one. The approval token is spent: call tia_upload without confirm for a fresh confirmation, then confirm:true with the new planHash and the password.",
33170
+ net_scan: "A network scan (accessible devices) probes the local network via the PG/PC adapter. Confirm before scanning."
33171
+ };
33172
+ var DOWNLOAD_REASON = {
33173
+ not_approved: "No human approval yet: the real download needs approved:true plus the planHash of a reviewed dryRun.",
33174
+ unknown: "No valid approval token: this planHash was not issued by this MCP process (or the MCP restarted). Approval tokens are random, single-use and live only in the MCP process that issued them.",
33175
+ expired: "This planHash expired (TIA_PLAN_TTL_MS). Approvals do not carry over to later sessions.",
33176
+ consumed: "This planHash was already used (single-use). If the previous call timed out, check the CPU and tia_job_status BEFORE anything else \u2014 the download may have happened.",
33177
+ plan_mismatch: "The parameters differ from the approved plan (plc / interface / options / allowUpgradeTargetDevice). The approval covers exactly the reviewed plan.",
33178
+ // P3 fix round 1 (#1): cause-neutral on purpose — this same reason now covers transport failures (a network or
33179
+ // timeout issue) AND a serve error (5xx/403/404/409 not_connected/etc.) AND an unreadable response, so the
33180
+ // text must not single out one cause (the old text named only "a network/timeout error", which read as if it
33181
+ // ruled out the other causes — deliberately NOT reusing that exact joined phrase here).
33182
+ outcome_unknown: "The /download call did not return a usable answer (a network or timeout issue, a serve error, or an unreadable response) AFTER the single-use token was already consumed \u2014 the token is SPENT and cannot be reused. The download may still be running on the CPU, or it may already have completed. Check the CPU state directly and tia_status (and tia_job_status if a job id is known) BEFORE requesting a new plan. Do NOT retry this same call \u2014 the token is gone and a retry cannot resume it."
33183
+ };
33184
+ function downloadResumeSteps(reason) {
33185
+ if (reason === "outcome_unknown") {
33186
+ return [
33187
+ "1. The approval token is SPENT and cannot be used again \u2014 do NOT call tia_download with approved:true and this same planHash.",
33188
+ "2. Check the CPU state directly, then tia_status (and tia_job_status if a job id is known), BEFORE anything else.",
33189
+ "3. Only once the real outcome is known, run tia_download with dryRun:true for a FRESH plan and a NEW token.",
33190
+ "4. Get a new explicit human approval before calling tia_download with approved:true again."
33191
+ ];
33192
+ }
33193
+ if (reason === "consumed") {
33194
+ return [
33195
+ "1. This planHash was already used (single-use) \u2014 do NOT call tia_download with approved:true and this same planHash again.",
33196
+ "2. Check the CPU state directly, then tia_status (and tia_job_status if a job id is known), BEFORE anything else \u2014 the download may already have happened.",
33197
+ "3. Only once the real outcome is known, run tia_download with dryRun:true for a FRESH plan and a NEW token.",
33198
+ "4. Get a new explicit human approval before calling tia_download with approved:true again."
33199
+ ];
33200
+ }
33201
+ return [
33202
+ "1. Run tia_download with dryRun:true to get a FRESH plan, its software fingerprint and a new single-use planHash.",
33203
+ "2. Show the plan + fingerprint to the line's responsible person and get an explicit yes.",
33204
+ "3. Re-call with approved:true and that NEW planHash, before it expires."
33205
+ ];
33206
+ }
33207
+ var UPLOAD_REASON = {
33208
+ unknown: "No valid approval token: this planHash was not issued by this MCP process (or the MCP restarted). Approval tokens are random, single-use and live only in the MCP process that issued them. Call tia_upload without confirm for a fresh plan.",
33209
+ expired: "This planHash expired (TIA_PLAN_TTL_MS). Approvals do not carry over to later sessions.",
33210
+ consumed: "This planHash was already used (single-use). If the previous call timed out, check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the station may already have been added.",
33211
+ plan_mismatch: "The parameters differ from the approved plan (ip / connection). The approval covers exactly the reviewed plan.",
33212
+ outcome_unknown: "The /stations/upload call did not return a usable answer (a network or timeout issue, a serve error, or an unreadable response) AFTER the single-use token was already consumed \u2014 the token is SPENT and cannot be reused. The station may still be uploading or may already have been added as a new station. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE requesting a new plan. Do NOT repeat this call \u2014 the token is gone and a retry cannot resume it.",
33213
+ password_required: "The CPU is read-protected and no accepted password was provided (G6): the approval token is SPENT. Ask the human for the read-access password \u2014 never invent one \u2014 then call tia_upload without confirm for a fresh confirmation and confirm:true with the new planHash and the password.",
33214
+ password_rejected: "The CPU rejected the provided read-access password (G6): the approval token is SPENT. Confirm the password with the human \u2014 never invent one \u2014 then call tia_upload without confirm for a fresh confirmation and confirm:true with the new planHash and the corrected password."
33215
+ };
33216
+ function uploadResumeSteps(reason) {
33217
+ if (reason === "outcome_unknown") {
33218
+ return [
33219
+ "1. The approval token is SPENT and cannot be used again \u2014 do NOT call tia_upload with confirm:true and this same planHash.",
33220
+ "2. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else.",
33221
+ "3. Only once the real outcome is known, run tia_upload without confirm for a FRESH plan and a NEW token.",
33222
+ "4. Get a new explicit human approval before calling tia_upload with confirm:true again."
33223
+ ];
33224
+ }
33225
+ if (reason === "password_required" || reason === "password_rejected") {
33226
+ return [
33227
+ "1. Ask the human for the CPU read-access password (G6 \u2014 never invent, guess or reuse one).",
33228
+ "2. Run tia_upload without confirm for a FRESH plan and a NEW token (the old token is SPENT).",
33229
+ "3. Show the plan to the human and get an explicit yes.",
33230
+ "4. Re-call with confirm:true, that NEW planHash and the human-provided password, before it expires."
33231
+ ];
33232
+ }
33233
+ if (reason === "consumed") {
33234
+ return [
33235
+ "1. This planHash was already used (single-use) \u2014 do NOT call tia_upload with confirm:true and this same planHash again.",
33236
+ "2. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the station may already have been added.",
33237
+ "3. Only once the real outcome is known, run tia_upload without confirm for a FRESH plan and a NEW token.",
33238
+ "4. Get a new explicit human approval before calling tia_upload with confirm:true again."
33239
+ ];
33240
+ }
33241
+ if (reason) {
33242
+ return [
33243
+ "1. Run tia_upload without confirm to get a FRESH plan and a new single-use planHash.",
33244
+ "2. Show the plan to the human and get an explicit yes.",
33245
+ "3. Re-call with confirm:true and that NEW planHash, before it expires."
33246
+ ];
33247
+ }
33248
+ return [
33249
+ "1. Show the plan + project to the human and get an explicit yes.",
33250
+ "2. Re-call tia_upload with confirm:true and this SAME planHash, before it expires."
33251
+ ];
33252
+ }
33253
+ function goOnlineResumeSteps() {
33254
+ return [
33255
+ "1. Confirm with a human that it is safe to connect to the target machine.",
33256
+ "2. Re-call tia_online with confirm:true."
33257
+ ];
33258
+ }
33259
+ function netScanResumeSteps() {
33260
+ return [
33261
+ "1. Confirm with a human that probing the local network is expected.",
33262
+ "2. Re-call tia_accessible_devices with confirm:true."
33263
+ ];
33264
+ }
33265
+ var YOUMUSTDO_DOWNLOAD_CONSUMED = "This planHash was already used (single-use) \u2014 the download may already have happened. Check the CPU state directly (and tia_status / tia_job_status) BEFORE anything else; do NOT repeat the approved call. Only once the real outcome is known, run a fresh dryRun plan and get a new human approval.";
33266
+ var YOUMUSTDO_OUTCOME_UNKNOWN = "Check the CPU state directly (and tia_status / tia_job_status) BEFORE anything else \u2014 the approval token is ALREADY SPENT. Do NOT repeat this call: get a fresh dryRun plan and a new human approval only once the real outcome is known.";
33267
+ var YOUMUSTDO_UPLOAD_OUTCOME_UNKNOWN = "Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the approval token is ALREADY SPENT. Do NOT repeat this call: get a fresh plan and a new human approval only once the real outcome is known.";
33268
+ function gateHandoff(gate, ctx) {
33269
+ const reasonTable = gate === "download_approval" ? DOWNLOAD_REASON : UPLOAD_REASON;
33270
+ const resume = gate === "download_approval" ? downloadResumeSteps(ctx.reason) : gate === "go_online" ? goOnlineResumeSteps() : gate === "net_scan" ? netScanResumeSteps() : uploadResumeSteps(ctx.reason);
33271
+ const youMustDo = ctx.youMustDo !== void 0 ? ctx.youMustDo : gate === "download_approval" && ctx.reason === "consumed" ? YOUMUSTDO_DOWNLOAD_CONSUMED : gate === "download_approval" && ctx.reason === "outcome_unknown" ? YOUMUSTDO_OUTCOME_UNKNOWN : gate === "station_upload" && ctx.reason === "outcome_unknown" ? YOUMUSTDO_UPLOAD_OUTCOME_UNKNOWN : GATE_INSTRUCTION[gate] ?? "Human confirmation required.";
33272
+ return textResult(
33273
+ {
33274
+ status: "requires_human_action",
33275
+ gate,
33276
+ canDo: ctx.plc ? `${gate} on ${ctx.plc}` : gate,
33277
+ youMustDo,
33278
+ reasonCode: ctx.reason ?? null,
33279
+ reason: ctx.reason ? reasonTable[ctx.reason] ?? ctx.reason : null,
33280
+ plan: ctx.plan ?? null,
33281
+ planHash: ctx.planHash ?? null,
33282
+ ...ctx.extra ?? {},
33283
+ nextSteps: resume
33284
+ },
33285
+ false
33286
+ );
33287
+ }
33288
+
33289
+ // src/tools/download.ts
33290
+ function buildPlan(args) {
33291
+ return {
33292
+ plc: args.plc,
33293
+ connectionMode: args.connectionMode ?? null,
33294
+ pcInterfaceName: args.pcInterfaceName ?? null,
33295
+ pcInterfaceNumber: args.pcInterfaceNumber ?? 1,
33296
+ targetInterfaceName: args.targetInterfaceName ?? null,
33297
+ hardware: args.hardware ?? false,
33298
+ software: args.software ?? true,
33299
+ // Always boolean: absent ≡ false, so "absent" and "false" never cause plan_mismatch.
33300
+ allowUpgradeTargetDevice: args.allowUpgradeTargetDevice === true
33301
+ };
33302
+ }
33303
+ function connectionBody(args) {
33304
+ return jsonBody({
33305
+ connectionMode: args.connectionMode,
33306
+ pcInterfaceName: args.pcInterfaceName,
33307
+ pcInterfaceNumber: args.pcInterfaceNumber,
33308
+ targetInterfaceName: args.targetInterfaceName
33309
+ });
33310
+ }
33311
+ function bodyFromApprovedPlan(issued) {
33312
+ const plan = issued.plan;
33313
+ return {
33314
+ ...jsonBody({
33315
+ connectionMode: plan.connectionMode,
33316
+ pcInterfaceName: plan.pcInterfaceName,
33317
+ pcInterfaceNumber: plan.pcInterfaceNumber,
33318
+ targetInterfaceName: plan.targetInterfaceName,
33319
+ hardware: plan.hardware,
33320
+ software: plan.software
33321
+ }),
33322
+ expectedFingerprint: issued.fingerprint,
33323
+ allowUpgradeTargetDevice: plan.allowUpgradeTargetDevice === true
33324
+ };
33325
+ }
33326
+ async function planDownload(args, plan, store) {
33327
+ let raw;
33328
+ try {
33329
+ raw = await tiaFetch(
33330
+ `/plcs/${seg(args.plc)}/download/plan`,
33331
+ { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(connectionBody(args)) },
33332
+ { timeoutMs: SLOW_TIMEOUT_MS }
33333
+ );
33334
+ } catch (e) {
33335
+ const err = asTiaError(e);
33336
+ if (err.status === 404 && err.kind === "route_not_found") {
33337
+ return errorResult(
33338
+ new TiaApiError(
33339
+ "This serve does not support verified download plans (POST /plcs/{plc}/download/plan \u2192 404). Update the TIAOpenness app to v1.6.0 or later. Nothing was downloaded.",
33340
+ { status: 404, kind: "serve_too_old" }
33341
+ )
33342
+ );
33343
+ }
33344
+ return errorResult(err);
33345
+ }
33346
+ const data = isObject2(raw) ? raw : {};
33347
+ const compile = { state: data.compile?.state ?? null, errors: data.compile?.errors ?? null, warnings: data.compile?.warnings ?? null };
33348
+ const fingerprint = typeof data.fingerprint === "string" ? data.fingerprint : "";
33349
+ const hasFingerprint = fingerprint.trim().length > 0;
33350
+ if (data.ready !== true || !hasFingerprint) {
33351
+ const blockers = Array.isArray(data.blockers) ? [...data.blockers] : [];
33352
+ if (!isObject2(raw)) blockers.push("invalid_plan_response");
33353
+ const fingerprintMissing = data.ready === true && !hasFingerprint;
33354
+ if (fingerprintMissing) blockers.push("fingerprint_missing");
33355
+ return textResult(
33356
+ {
33357
+ dryRun: true,
33358
+ status: "plan_blocked",
33359
+ gate: "download_approval",
33360
+ plan,
33361
+ blockers,
33362
+ compile,
33363
+ connection: data.connection ?? null,
33364
+ target: data.target ?? null,
33365
+ note: fingerprintMissing ? "NO approval token was issued: serve reported ready but returned no software fingerprint, and this MCP never approves a download it cannot verify. Update the TIAOpenness app (serve) to v1.6.0 or later and run dryRun again." : "NO approval token was issued. Fix the blockers (compile errors \u2192 tia_compile; interface \u2192 tia_pg_interfaces) and run dryRun again."
33366
+ },
33367
+ false
33368
+ );
33369
+ }
33370
+ const issued = store.issue(plan, fingerprint);
33371
+ return textResult(
33372
+ {
33373
+ dryRun: true,
33374
+ status: "plan_ok",
33375
+ gate: "download_approval",
33376
+ plan,
33377
+ planHash: issued.token,
33378
+ expiresAt: new Date(issued.expiresAt).toISOString(),
33379
+ fingerprint,
33380
+ fingerprintItems: data.fingerprintItems ?? [],
33381
+ coverage: data.coverage ?? null,
33382
+ warnings: data.warnings ?? [],
33383
+ compile,
33384
+ connection: data.connection ?? null,
33385
+ target: data.target ?? null,
33386
+ loadPreview: {
33387
+ // Amendment #4: mirrors EVERY real auto-confirmation of PlcDeployService.cs (PreDownload/PostDownload),
33388
+ // not just the 3 most obvious — including ones that don't stop/restart the CPU but still change its content.
33389
+ willConfirm: [
33390
+ "StopModules = StopAll \u2014 STOPS the physical CPU (pre phase)",
33391
+ "ResetModule = DeleteAll \u2014 if the CPU already holds a DIFFERENT program, it is deleted before this one loads (pre and/or post phase)",
33392
+ "OverwriteSystemData = Overwrite \u2014 overwrites system data (pre phase for a hardware download, and again in the post phase)",
33393
+ "ConsistentBlocksDownload = ConsistentDownload \u2014 downloads all blocks consistently (pre phase)",
33394
+ "AlarmTextLibrariesDownload = ConsistentDownload \u2014 downloads alarm text libraries consistently (pre phase)",
33395
+ "StartModules = StartModule \u2014 RESTARTS the CPU at the end (post phase)",
33396
+ plan.allowUpgradeTargetDevice ? "UpgradeTargetDevice = Checked \u2014 upgrades the target device (explicitly allowed)" : "UpgradeTargetDevice = NOT confirmed unless allowUpgradeTargetDevice:true \u2014 if the CPU requires it the download is refused, but the CPU may already have been stopped.",
33397
+ "Any OTHER configuration dialog serve does not recognize is left UNTOUCHED, which can abort the load."
33398
+ ],
33399
+ note: "Openness has no preview-without-downloading; these are the selections serve's delegates will make. The real download returns 'configurations' with what was actually confirmed."
33400
+ },
33401
+ note: "Plan verified by serve. NOTHING was downloaded. After a human approves THIS plan, fingerprint and target (project + CPU address), call tia_download with approved:true and this planHash (single-use, expires at expiresAt)."
33402
+ },
33403
+ false
33117
33404
  );
33118
- server2.registerTool(
33119
- "tia_source_put",
33120
- {
33121
- title: "TIA \u2014 write/compile SCL source",
33122
- description: "Writes a block from textual SCL source and (optionally) compiles it. Gd6: use THIS for TEXTUAL language (SCL/STL); for graphical (LAD/FBD/GRAPH) use tia_import_xml. With compile:true, the raw compile DTO is nested under 'compile' (same as tia_compile's response), and 'located[]' plus a nextHint are merged at the TOP LEVEL of the result \u2014 same place tia_compile puts them \u2014 when the compile regenerated blocks, e.g. an instance DB after an FB interface change. Maps to POST /plcs/{plc}/source. M-off.",
33123
- inputSchema: {
33124
- plc: external_exports.string().describe("PLC name"),
33125
- name: external_exports.string().describe("block/source name"),
33126
- code: external_exports.string().describe("SCL source code"),
33127
- compile: external_exports.boolean().optional().describe("compile after generating (default false)"),
33128
- ...dryRunField
33405
+ }
33406
+ async function downloadFlow(args, store = planStore) {
33407
+ const plan = buildPlan(args);
33408
+ if (args.dryRun) return planDownload(args, plan, store);
33409
+ if (args.approved !== true) return gateHandoff("download_approval", { plc: args.plc, plan, reason: "not_approved" });
33410
+ const check2 = store.check(args.planHash, plan);
33411
+ if (!check2.ok) return gateHandoff("download_approval", { plc: args.plc, plan, reason: check2.reason });
33412
+ store.consume(check2.issued.token);
33413
+ let raw;
33414
+ try {
33415
+ raw = await tiaFetch(
33416
+ `/plcs/${seg(args.plc)}/download`,
33417
+ { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(bodyFromApprovedPlan(check2.issued)) },
33418
+ { timeoutMs: 18e4 }
33419
+ );
33420
+ } catch (e) {
33421
+ const err = asTiaError(e);
33422
+ if (isInstallingError(err))
33423
+ return errorResult(
33424
+ err,
33425
+ "Serve is installing a TIAOpenness app update: nothing was downloaded (the call was refused BEFORE running, so no CPU check is needed). The single-use approval token is already spent \u2014 after the update finishes, run a fresh dryRun plan and get a new human approval. There is no background job for this call."
33426
+ );
33427
+ const knownRefusal = err.status === 409 && (err.kind === "plan_stale" || err.kind === "upgrade_target_device_required");
33428
+ if (knownRefusal) return errorResult(err);
33429
+ const isTransport = err.kind === "timeout" || err.kind === "connection_refused";
33430
+ return gateHandoff("download_approval", {
33431
+ plc: args.plc,
33432
+ plan,
33433
+ reason: "outcome_unknown",
33434
+ extra: {
33435
+ approvedPlanHash: check2.issued.token,
33436
+ ...isTransport ? { transportKind: err.kind, transportDiagnostics: err.message } : {
33437
+ serveErrorStatus: err.status,
33438
+ serveErrorKind: err.kind,
33439
+ serveErrorType: err.type ?? null,
33440
+ serveErrorInner: err.inner ?? null,
33441
+ serveErrorDetails: err.details ?? null,
33442
+ serveErrorDiagnostics: err.message
33443
+ }
33129
33444
  }
33130
- },
33131
- async ({ plc, name, code, compile, dryRun }) => sourcePutFlow({ plc, name, code, compile, dryRun })
33132
- );
33445
+ });
33446
+ }
33447
+ const data = isObject2(raw) ? raw : {};
33448
+ const state = typeof data.state === "string" ? data.state : null;
33449
+ const errors = typeof data.errors === "number" ? data.errors : null;
33450
+ const stateLower = state !== null ? state.toLowerCase() : null;
33451
+ const cleanErrors = errors === 0;
33452
+ const loadOutcome = stateLower === "success" && cleanErrors ? "success" : (stateLower === "warning" || stateLower === "information") && cleanErrors ? "success_with_warnings" : "failed";
33453
+ const downloaded = loadOutcome !== "failed";
33454
+ const fingerprintVerified = data.fingerprintVerified === true;
33455
+ const warnings = [];
33456
+ if (loadOutcome === "failed") {
33457
+ warnings.push(
33458
+ `serve answered the download call, but did not report a clean load (state='${state ?? "unknown"}', errors=${errors ?? "unknown"}). Check 'result.messages' for what happened \u2014 the CPU may be in a partial or unexpected state. Do not treat this as a confirmed successful deploy.`
33459
+ );
33460
+ }
33461
+ if (!fingerprintVerified) {
33462
+ warnings.push(
33463
+ "serve did NOT confirm the software fingerprint check (fingerprintVerified is not true): it is NOT proven that the CPU received exactly the approved software. The serve may be older than v1.6.0 and have ignored expectedFingerprint. Tell the human and check the CPU before relying on it."
33464
+ );
33465
+ }
33466
+ return textResult({
33467
+ downloaded,
33468
+ loadOutcome,
33469
+ approvedPlanHash: check2.issued.token,
33470
+ fingerprint: check2.issued.fingerprint,
33471
+ fingerprintVerified,
33472
+ state,
33473
+ errors,
33474
+ ...loadOutcome === "success_with_warnings" ? { note: "The load completed with warnings \u2014 read result.messages." } : {},
33475
+ ...warnings.length > 0 ? { warning: warnings.join(" ") } : {},
33476
+ result: raw ?? null
33477
+ });
33478
+ }
33479
+ function registerDownloadTools(server2) {
33133
33480
  server2.registerTool(
33134
- "tia_import_xml",
33481
+ "tia_download",
33135
33482
  {
33136
- title: "TIA \u2014 import block (SimaticML XML)",
33137
- description: "Imports a block in SimaticML XML (the only path for LAD/FBD/GRAPH \u2014 Gd6). PREFER `xml` inline (tested up to ~300 KB: 280 KB imported in 1\u20135 s); use `path` ONLY for a file that is already on the serve host \u2014 never copy files to the host to import them. Gd7: SimaticML version must match V21. Import UDTs FIRST (tia_types_import). Returns, per block, type/number/created/interfaceChanged/affectedInstanceDbs, and \u2014 when `xml` was sent inline \u2014 a transport check (sha256 sent vs received). Requires app \u2265 v1.6.0 for the receipt; with an older serve transport.match is null and there are no per-block fields. An FB whose interface changed makes the next compile regenerate its instance DBs. Maps to POST /plcs/{plc}/import. M-off.",
33483
+ title: "TIA \u2014 download to the PLC (GATE G3)",
33484
+ description: "Downloads hardware/software to the PHYSICAL CPU (STOPS and RESTARTS the CPU). GATE G3: does NOT download without human approval. dryRun:true asks serve for a VERIFIED plan (clean compile, PG/PC interface found, software fingerprint) and returns a single-use planHash that expires (TIA_PLAN_TTL_MS, default 15 min). After a human approves that plan, call with approved:true and the SAME planHash; serve re-checks the fingerprint inside the download and refuses (plan_stale) if the project changed. Pick connectionMode/pcInterfaceName/targetInterfaceName with tia_pg_interfaces (no scan). Requires app \u2265 v1.6.0. Maps to POST /plcs/{plc}/download/plan and POST /plcs/{plc}/download. " + LONG_OPERATION_NOTE,
33138
33485
  inputSchema: {
33139
33486
  plc: external_exports.string().describe("PLC name"),
33140
- xml: external_exports.string().optional().describe("SimaticML XML content (alternative to path)"),
33141
- path: external_exports.string().optional().describe("path to the .xml on the serve host (alternative to xml)"),
33142
- override: external_exports.boolean().optional().describe("overwrite if it already exists (default true)"),
33143
- ...dryRunField
33487
+ connectionMode: external_exports.string().optional().describe(`connection mode (e.g., "PN/IE") \u2014 TIA's LOCALIZED name`),
33488
+ pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized name)"),
33489
+ pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
33490
+ targetInterfaceName: external_exports.string().optional().describe('target CPU interface (e.g., "1 X1")'),
33491
+ hardware: external_exports.boolean().optional().describe("download hardware (default false)"),
33492
+ software: external_exports.boolean().optional().describe("download software (default true)"),
33493
+ allowUpgradeTargetDevice: external_exports.boolean().optional().describe("confirm TIA's 'upgrade the target device' check (default false). Part of the approved plan \u2014 changing it needs a new dryRun + approval"),
33494
+ dryRun: external_exports.boolean().optional().describe("Gd11: returns the plan + planHash WITHOUT downloading"),
33495
+ approved: external_exports.boolean().optional().describe("G3: only true after explicit HUMAN APPROVAL"),
33496
+ planHash: external_exports.string().optional().describe("G3: the single-use approval token returned by dryRun (issued only by this MCP process; expires)")
33144
33497
  }
33145
33498
  },
33146
- async ({ plc, xml, path, override, dryRun }) => importXmlFlow({ plc, xml, path, override, dryRun })
33499
+ // ENTIRE handler in the job and ENTIRE args in the key (planHash/approved/connection included): a busy returns
33500
+ // BEFORE downloadFlow runs, so the single-use token is only consumed inside the job, before the serve call.
33501
+ async (args) => jobs.run("tia_download", args, () => downloadFlow(args))
33147
33502
  );
33503
+ }
33504
+
33505
+ // src/tools/upload.ts
33506
+ var UPLOAD_TIMEOUT_MS = 24e4;
33507
+ function buildUploadPlan(args) {
33508
+ return {
33509
+ ip: args.ip,
33510
+ connectionMode: args.connectionMode ?? null,
33511
+ pcInterfaceName: args.pcInterfaceName ?? null,
33512
+ pcInterfaceNumber: args.pcInterfaceNumber ?? 1
33513
+ };
33514
+ }
33515
+ function uploadBodyFromApprovedPlan(issued, password) {
33516
+ const plan = issued.plan;
33517
+ return {
33518
+ ...jsonBody({
33519
+ connectionMode: plan.connectionMode,
33520
+ pcInterfaceName: plan.pcInterfaceName,
33521
+ pcInterfaceNumber: plan.pcInterfaceNumber,
33522
+ ip: plan.ip
33523
+ }),
33524
+ expectedProjectPath: issued.fingerprint,
33525
+ ...password !== void 0 ? { password } : {}
33526
+ };
33527
+ }
33528
+ async function planUpload(args, plan, store) {
33529
+ let raw;
33530
+ try {
33531
+ raw = await tiaFetch(
33532
+ "/stations/upload/plan",
33533
+ {
33534
+ method: "POST",
33535
+ headers: JSON_HEADERS,
33536
+ body: JSON.stringify(
33537
+ jsonBody({
33538
+ connectionMode: args.connectionMode,
33539
+ pcInterfaceName: args.pcInterfaceName,
33540
+ pcInterfaceNumber: args.pcInterfaceNumber,
33541
+ ip: args.ip
33542
+ })
33543
+ )
33544
+ },
33545
+ { timeoutMs: SLOW_TIMEOUT_MS }
33546
+ );
33547
+ } catch (e) {
33548
+ const err = asTiaError(e);
33549
+ if (err.status === 404 && err.kind === "route_not_found") {
33550
+ return errorResult(
33551
+ new TiaApiError(
33552
+ "This serve does not support station-upload plans (POST /stations/upload/plan \u2192 404). Update the TIAOpenness app to v1.6.0 or later. Nothing was uploaded.",
33553
+ { status: 404, kind: "serve_too_old" }
33554
+ ),
33555
+ "Update the TIAOpenness app to v1.6.0 or later. Nothing was uploaded."
33556
+ );
33557
+ }
33558
+ return errorResult(err);
33559
+ }
33560
+ const data = isObject2(raw) ? raw : {};
33561
+ const project = isObject2(data.project) ? data.project : {};
33562
+ const projectPath = typeof project.path === "string" ? project.path : "";
33563
+ const projectName = typeof project.name === "string" ? project.name : "(unnamed)";
33564
+ const devices = Array.isArray(data.devices) ? [...data.devices] : [];
33565
+ if (data.ready !== true || projectPath.trim().length === 0) {
33566
+ const blockers = Array.isArray(data.blockers) ? [...data.blockers] : [];
33567
+ if (!isObject2(raw)) blockers.push("invalid_plan_response");
33568
+ if (data.ready === true) blockers.push("project_path_missing");
33569
+ return textResult(
33570
+ {
33571
+ status: "plan_blocked",
33572
+ gate: "station_upload",
33573
+ plan,
33574
+ blockers,
33575
+ connection: data.connection ?? null,
33576
+ project: data.project ?? null,
33577
+ devices,
33578
+ note: typeof data.note === "string" ? data.note : null
33579
+ },
33580
+ false
33581
+ );
33582
+ }
33583
+ const issued = store.issue(plan, projectPath);
33584
+ const warning = devices.length > 0 ? `The open project already has ${devices.length} device(s); a backup belongs in a dedicated EMPTY project (tia.backup).` : void 0;
33585
+ const youMustDo = `GATE G4: upload (read) the hardware configuration and program of the PHYSICAL CPU at ${String(plan.ip)} into the OPEN project "${projectName}" (${projectPath}), which currently holds ${devices.length} device(s) \u2014 it reads the CPU and does not write it. Confirm with a human that it is safe to connect to this machine AND that this is a dedicated backup project, never the working project. After an explicit yes, re-call tia_upload with confirm:true and this planHash.`;
33586
+ return gateHandoff("station_upload", {
33587
+ plan,
33588
+ planHash: issued.token,
33589
+ youMustDo,
33590
+ extra: {
33591
+ expiresAt: new Date(issued.expiresAt).toISOString(),
33592
+ project: data.project,
33593
+ // no `?? null`: the plan_blocked guard above only lets a project object with a path through
33594
+ devices,
33595
+ connection: data.connection ?? null,
33596
+ ...warning !== void 0 ? { warning } : {}
33597
+ }
33598
+ });
33599
+ }
33600
+ async function uploadFlow(args, store = uploadPlanStore) {
33601
+ const plan = buildUploadPlan(args);
33602
+ if (args.confirm !== true) return planUpload(args, plan, store);
33603
+ const check2 = store.check(args.planHash, plan);
33604
+ if (!check2.ok) return gateHandoff("station_upload", { plan, reason: check2.reason });
33605
+ store.consume(check2.issued.token);
33606
+ let raw;
33607
+ try {
33608
+ raw = await tiaFetch(
33609
+ "/stations/upload",
33610
+ { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(uploadBodyFromApprovedPlan(check2.issued, args.password)) },
33611
+ { timeoutMs: UPLOAD_TIMEOUT_MS }
33612
+ );
33613
+ } catch (e) {
33614
+ const err = asTiaError(e);
33615
+ if (isInstallingError(err))
33616
+ return errorResult(
33617
+ err,
33618
+ "Serve is installing a TIAOpenness app update: nothing was uploaded (the call was refused BEFORE going online, so no station check is needed). The single-use approval token is already spent \u2014 after the update finishes, run a fresh plan and get a new human approval. There is no background job for this call."
33619
+ );
33620
+ const knownRefusal = err.status === 400 || err.status === 409 && (err.kind === "project_changed" || err.kind === "upload_provider_unavailable" || err.kind === "connection_unresolved");
33621
+ if (knownRefusal) {
33622
+ return errorResult(
33623
+ new TiaApiError(`${err.message} The approval token is SPENT (single-use) and cannot be reused; nothing was uploaded.`, {
33624
+ status: err.status,
33625
+ kind: err.kind,
33626
+ type: err.type,
33627
+ inner: err.inner,
33628
+ details: err.details
33629
+ })
33630
+ );
33631
+ }
33632
+ if (err.status === 409 && (err.kind === "upload_password_required" || err.kind === "upload_password_rejected")) {
33633
+ const det = isObject2(err.details) ? err.details : {};
33634
+ return gateHandoff("upload_password", {
33635
+ plan,
33636
+ reason: err.kind === "upload_password_required" ? "password_required" : "password_rejected",
33637
+ extra: { configurations: det.configurations ?? null }
33638
+ });
33639
+ }
33640
+ const isTransport = err.kind === "timeout" || err.kind === "connection_refused";
33641
+ return gateHandoff("station_upload", {
33642
+ plan,
33643
+ reason: "outcome_unknown",
33644
+ extra: {
33645
+ approvedPlanHash: check2.issued.token,
33646
+ ...isTransport ? { transportKind: err.kind, transportDiagnostics: err.message } : {
33647
+ serveErrorStatus: err.status,
33648
+ serveErrorKind: err.kind,
33649
+ serveErrorType: err.type ?? null,
33650
+ serveErrorInner: err.inner ?? null,
33651
+ serveErrorDetails: err.details ?? null,
33652
+ serveErrorDiagnostics: err.message
33653
+ }
33654
+ }
33655
+ });
33656
+ }
33657
+ if (!isObject2(raw)) {
33658
+ return gateHandoff("station_upload", {
33659
+ plan,
33660
+ reason: "outcome_unknown",
33661
+ extra: {
33662
+ approvedPlanHash: check2.issued.token,
33663
+ serveErrorStatus: null,
33664
+ serveErrorKind: null,
33665
+ serveErrorType: null,
33666
+ serveErrorInner: null,
33667
+ serveErrorDetails: null,
33668
+ serveErrorDiagnostics: "POST /stations/upload answered 2xx with an empty or non-JSON body AFTER the single-use token was already consumed \u2014 the upload outcome is unknown."
33669
+ }
33670
+ });
33671
+ }
33672
+ const data = raw;
33673
+ const state = typeof data.state === "string" ? data.state : null;
33674
+ const errors = typeof data.errors === "number" ? data.errors : null;
33675
+ const stateLower = state !== null ? state.toLowerCase() : null;
33676
+ const cleanErrors = errors === 0;
33677
+ const uploadOutcome = stateLower === "success" && cleanErrors ? "success" : (stateLower === "warning" || stateLower === "information") && cleanErrors ? "success_with_warnings" : "failed";
33678
+ const uploaded = uploadOutcome !== "failed";
33679
+ const createdDevices = Array.isArray(data.createdDevices) ? data.createdDevices : [];
33680
+ const warnings = [];
33681
+ if (uploadOutcome === "failed") {
33682
+ warnings.push(
33683
+ `serve answered the upload call, but did not report a clean upload (state='${state ?? "unknown"}', errors=${errors ?? "unknown"}). Do not treat this as a backup \u2014 read result.messages for what happened; the project may hold a partial station.`
33684
+ );
33685
+ }
33686
+ if (uploaded && createdDevices.length === 0) {
33687
+ warnings.push("serve reported success but no new device appeared; check tia_devices.");
33688
+ }
33689
+ return textResult({
33690
+ uploaded,
33691
+ uploadOutcome,
33692
+ approvedPlanHash: check2.issued.token,
33693
+ projectPath: check2.issued.fingerprint,
33694
+ state,
33695
+ errors,
33696
+ uploadedStation: typeof data.uploadedStation === "string" ? data.uploadedStation : null,
33697
+ createdDevices,
33698
+ configurations: data.configurations ?? null,
33699
+ ...warnings.length > 0 ? { warning: warnings.join(" ") } : {},
33700
+ nextSteps: [
33701
+ "1. Save the project with tia_project_save.",
33702
+ "2. Archive it with tia_project_archive \u2014 the .zap21 is the backup (the archive name must carry the .zap21 extension).",
33703
+ "3. Optionally compile the new PLC with tia_compile (a GUI-gated license message is not a backup failure)."
33704
+ ],
33705
+ result: raw
33706
+ // no `?? null`: the outcome_unknown guard above only lets an object body through
33707
+ });
33708
+ }
33709
+ function registerUploadTools(server2) {
33148
33710
  server2.registerTool(
33149
- "tia_types_import",
33711
+ "tia_upload",
33150
33712
  {
33151
- title: "TIA \u2014 import type/UDT (SimaticML XML)",
33152
- description: "Imports a UDT in SimaticML XML. Import UDTs BEFORE the blocks that use them (Gd6). Maps to POST /plcs/{plc}/types/import. M-off.",
33713
+ title: "TIA \u2014 station upload (GATE G4)",
33714
+ description: "Station upload (GATE G4): goes ONLINE to the PHYSICAL CPU at `ip` and reads its hardware configuration and program into the OPEN project as a new station \u2014 it reads the CPU and does not write or stop it (observed on hardware: the CPU stayed in RUN). Back up into a dedicated EMPTY project, never the working project (skill tia.backup). Without confirm it asks serve for an upload plan (PG/PC interface resolved, the open project's path and devices \u2014 no network access) and returns a single-use planHash bound to that project; after a human confirms, call again with confirm:true and that planHash. A read-protected CPU needs its read-access password from a HUMAN (G6 \u2014 never invented). Needs the deploy license scope (Basic \u2192 403 scope_required) and app \u2265 v1.6.0. Maps to POST /stations/upload/plan and POST /stations/upload. " + LONG_OPERATION_NOTE,
33153
33715
  inputSchema: {
33154
- plc: external_exports.string().describe("PLC name"),
33155
- xml: external_exports.string().optional().describe("SimaticML XML content of the UDT (alternative to path)"),
33156
- path: external_exports.string().optional().describe("path to the .xml on the host (alternative to xml)"),
33157
- override: external_exports.boolean().optional().describe("overwrite if it already exists (default true)"),
33158
- ...dryRunField
33716
+ ip: external_exports.string().describe("IPv4 of the PHYSICAL CPU"),
33717
+ connectionMode: external_exports.string().optional().describe(`connection mode (e.g., "PN/IE") \u2014 TIA's LOCALIZED name`),
33718
+ pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized name)"),
33719
+ pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
33720
+ confirm: external_exports.boolean().optional().describe("G4: true only after explicit HUMAN confirmation"),
33721
+ planHash: external_exports.string().optional().describe("G4: the single-use approval token returned by the unconfirmed call (issued only by this MCP process; expires)"),
33722
+ password: external_exports.string().optional().describe("G6: the CPU read-access password provided by a HUMAN, never invented")
33159
33723
  }
33160
33724
  },
33161
- async ({ plc, xml, path, override, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/types/import`, jsonBody3({ xml, path, override }), { dryRun, summary: `import UDT on ${plc}` })
33725
+ // ENTIRE handler in the job and ENTIRE args in the key (like tia_download): a busy returns BEFORE uploadFlow
33726
+ // runs, so the single-use token is only consumed inside the job, before the serve call. The key is a
33727
+ // sha256 hash — the password never appears in plain text in the job state.
33728
+ async (args) => jobs.run("tia_upload", args, () => uploadFlow(args))
33162
33729
  );
33730
+ }
33731
+
33732
+ // src/tools/online.ts
33733
+ function registerOnlineTools(server2) {
33163
33734
  server2.registerTool(
33164
- "tia_export_xml",
33735
+ "tia_connection_create",
33165
33736
  {
33166
- title: "TIA \u2014 export blocks/types (SimaticML XML)",
33167
- description: "Exports the PLC's blocks and types to SimaticML XML files in a directory (project-as-code). Maps to POST /plcs/{plc}/export. M-off. " + LONG_OPERATION_NOTE,
33737
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33738
+ title: "TIA \u2014 create S7 connection",
33739
+ description: (
33740
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33741
+ "Creates an S7 connection between two devices. Guard G2: requires \u22652 CONSISTENT CPUs (compile clean) \u2014 a bare CPU fails. On error, the envelope's 'details' carries the diagnostic (or use tia_connections_diagnose). Maps to POST /connections. M-off."
33742
+ ),
33168
33743
  inputSchema: {
33169
- plc: external_exports.string().describe("PLC name"),
33170
- directory: external_exports.string().describe("target directory on the serve host"),
33171
- ...dryRunField
33744
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33745
+ localDevice: external_exports.string().describe("local device"),
33746
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33747
+ partnerDevice: external_exports.string().describe("partner device")
33172
33748
  }
33173
33749
  },
33174
- async ({ plc, directory, dryRun }) => jobs.run(
33175
- "tia_export_xml",
33176
- { plc, directory, dryRun },
33177
- () => mutate("POST", `/plcs/${seg3(plc)}/export`, jsonBody3({ directory }), { dryRun, summary: `export XML from ${plc} to ${directory}` })
33178
- )
33179
- );
33180
- server2.registerTool(
33181
- "tia_watchtable_create",
33182
- {
33183
- title: "TIA \u2014 create watch table",
33184
- description: "Creates a watch table. Maps to POST /plcs/{plc}/watchtables. M-off.",
33185
- inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("watch table name"), ...dryRunField }
33186
- },
33187
- async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg3(plc)}/watchtables`, jsonBody3({ name }), { dryRun, summary: `create watch table ${name}` })
33188
- );
33189
- server2.registerTool(
33190
- "tia_watchtable_delete",
33191
- {
33192
- title: "TIA \u2014 delete watch table",
33193
- description: "Deletes a watch table. Maps to DELETE /plcs/{plc}/watchtables/{wt}. M-off.",
33194
- inputSchema: { plc: external_exports.string().describe("PLC name"), watchtable: external_exports.string().describe("watch table name"), ...dryRunField }
33195
- },
33196
- async ({ plc, watchtable, dryRun }) => mutate("DELETE", `/plcs/${seg3(plc)}/watchtables/${seg3(watchtable)}`, void 0, { dryRun, summary: `delete watch table ${watchtable}` })
33750
+ async ({ localDevice, partnerDevice }) => send("POST", "/connections", jsonBody({ localDevice, partnerDevice }))
33197
33751
  );
33198
33752
  server2.registerTool(
33199
- "tia_obj_service",
33753
+ "tia_online",
33200
33754
  {
33201
- title: "TIA \u2014 acquire service (GetService\u2192handle)",
33202
- description: "Acquires a service from an object by handle (generic GetService<T>) and returns a service HANDLE, to then invoke methods via tia_obj_invoke. E.g.: PlcMasterSecretConfigurator.Protect \u2014 unlocks a bare CPU (offline confidential-data password; generates the certificate). The acquisition itself does NOT mutate the project. Maps to POST /obj/{handle}/service {type}. M-off.",
33755
+ title: "TIA \u2014 go online (GATE G4)",
33756
+ description: "Connects ONLINE to the physical PLC. GATE G4: pass confirm:true (after a human confirms it's safe to connect to the target machine); without it, returns a handoff. Maps to POST /plcs/{plc}/online.",
33203
33757
  inputSchema: {
33204
- handle: external_exports.string().describe("object handle (e.g., the CPU's device item)"),
33205
- type: external_exports.string().describe("service type name (e.g., Siemens.Engineering.HW.Features.PlcMasterSecretConfigurator)")
33758
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33759
+ plc: external_exports.string().describe("PLC name"),
33760
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33761
+ connectionMode: external_exports.string().optional().describe("connection mode (localized)"),
33762
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33763
+ pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized)"),
33764
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33765
+ pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
33766
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33767
+ targetInterfaceName: external_exports.string().optional().describe("target CPU interface"),
33768
+ confirm: external_exports.boolean().optional().describe("G4: true after human confirmation")
33206
33769
  }
33207
33770
  },
33208
- async ({ handle, type }) => mutate("POST", `/obj/${seg3(handle)}/service`, jsonBody3({ type }), { summary: `acquire service ${type} from obj ${handle}` })
33771
+ async ({ plc, connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName, confirm }) => {
33772
+ if (confirm !== true) return gateHandoff("go_online", { plc, plan: { plc, connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName } });
33773
+ return send("POST", `/plcs/${seg(plc)}/online`, jsonBody({ connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName }), 6e4);
33774
+ }
33209
33775
  );
33210
33776
  server2.registerTool(
33211
- "tia_obj_set_attributes",
33777
+ "tia_offline",
33212
33778
  {
33213
- title: "TIA \u2014 set attributes (generic)",
33214
- description: "Sets attributes of any model object by handle. Maps to POST /obj/{handle}/attributes. M-off. Use the handles from the read-only obj tools (M1).",
33215
- inputSchema: {
33216
- handle: external_exports.string().describe("object handle (from the read-only tia_obj_* tools)"),
33217
- attributes: external_exports.record(external_exports.string(), external_exports.unknown()).describe("name\u2192value map of attributes to set"),
33218
- ...dryRunField
33219
- }
33779
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33780
+ title: "TIA \u2014 go offline",
33781
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33782
+ description: "Disconnects the PLC from online mode. Maps to POST /plcs/{plc}/offline.",
33783
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33784
+ inputSchema: { plc: external_exports.string().describe("PLC name") }
33220
33785
  },
33221
- async ({ handle, attributes, dryRun }) => mutate("POST", `/obj/${seg3(handle)}/attributes`, jsonBody3({ ...attributes }), { dryRun, summary: `set attributes on obj ${handle}` })
33786
+ async ({ plc }) => send("POST", `/plcs/${seg(plc)}/offline`)
33222
33787
  );
33223
33788
  server2.registerTool(
33224
- "tia_obj_invoke",
33789
+ "tia_online_state",
33225
33790
  {
33226
- title: "TIA \u2014 invoke method (generic)",
33227
- description: 'Invokes a method of a model object by handle (args coerced to the parameter types; {"$handle":N} passes another object). Maps to POST /obj/{handle}/invoke. M-off. Powerful \u2014 combine with tia_obj_info to see the signature.',
33228
- inputSchema: {
33229
- handle: external_exports.string().describe("object handle"),
33230
- name: external_exports.string().describe("name of the method to invoke"),
33231
- args: external_exports.array(external_exports.unknown()).optional().describe("positional arguments (coerced to the parameter types)"),
33232
- ...dryRunField
33233
- }
33791
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33792
+ title: "TIA \u2014 online state",
33793
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33794
+ description: "Reads the PLC's online state (online/offline). Read-only (class R). Maps to GET /plcs/{plc}/online/state.",
33795
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33796
+ inputSchema: { plc: external_exports.string().describe("PLC name") }
33234
33797
  },
33235
- async ({ handle, name, args, dryRun }) => mutate("POST", `/obj/${seg3(handle)}/invoke`, jsonBody3({ name, args }), { dryRun, summary: `invoke ${name}() on obj ${handle}` })
33798
+ async ({ plc }) => getResult(`/plcs/${seg(plc)}/online/state`)
33236
33799
  );
33237
33800
  server2.registerTool(
33238
- "tia_obj_create",
33801
+ "tia_accessible_devices",
33239
33802
  {
33240
- title: "TIA \u2014 create object (generic)",
33241
- description: "Creates an object in a composition of a parent object by handle. Maps to POST /obj/{handle}/create. M-off. See the creatable types in tia_obj_creationinfos.",
33803
+ title: "TIA \u2014 accessible devices (GATE G7)",
33804
+ description: "Scans the network via the PG/PC adapter and lists accessible devices \u2014 to see which devices answer on the network \u2014 to discover mode/adapter/interface names WITHOUT a scan, use tia_pg_interfaces. GATE G7 (net scan): pass confirm:true. Maps to POST /plcs/{plc}/online/accessibledevices.",
33242
33805
  inputSchema: {
33243
- handle: external_exports.string().describe("parent object handle"),
33244
- composition: external_exports.string().describe("composition name (e.g., 'Blocks')"),
33245
- type: external_exports.string().describe("type to create (Siemens type)"),
33246
- parameters: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("constructor parameters (name\u2192value)"),
33247
- ...dryRunField
33806
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33807
+ plc: external_exports.string().describe("PLC name"),
33808
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33809
+ connectionMode: external_exports.string().optional().describe("connection mode (localized)"),
33810
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33811
+ pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized)"),
33812
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33813
+ pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
33814
+ confirm: external_exports.boolean().optional().describe("G7: true after human confirmation")
33248
33815
  }
33249
33816
  },
33250
- async ({ handle, composition, type, parameters, dryRun }) => mutate("POST", `/obj/${seg3(handle)}/create`, jsonBody3({ composition, type, parameters }), {
33251
- dryRun,
33252
- summary: `create ${type} in ${composition} of obj ${handle}`
33253
- })
33817
+ async ({ plc, connectionMode, pcInterfaceName, pcInterfaceNumber, confirm }) => {
33818
+ if (confirm !== true) return gateHandoff("net_scan", { plc, plan: { plc, connectionMode, pcInterfaceName, pcInterfaceNumber } });
33819
+ return send("POST", `/plcs/${seg(plc)}/online/accessibledevices`, jsonBody({ connectionMode, pcInterfaceName, pcInterfaceNumber }), 6e4);
33820
+ }
33254
33821
  );
33255
- }
33256
-
33257
- // src/tools/asCode.ts
33258
- var seg4 = (v) => encodeURIComponent(v);
33259
- function errorResult4(e) {
33260
- const err = asTiaError(e);
33261
- return textResult({ error: err.message, kind: err.kind, status: err.status, details: err.details ?? null, hint: hintFor(err) }, true);
33262
- }
33263
- async function fetchBlockXml(plc, block, options) {
33264
- const q = options ? `?options=${encodeURIComponent(options)}` : "";
33265
- return await tiaFetch(`/plcs/${seg4(plc)}/blocks/${seg4(block)}/xml${q}`, {}, { timeoutMs: SLOW_TIMEOUT_MS });
33266
- }
33267
- async function exportBlockFlow(plc, block, options) {
33268
- try {
33269
- const d = await fetchBlockXml(plc, block, options);
33270
- return textResult({
33271
- name: d.name,
33272
- options: d.options,
33273
- sha256: sha256Utf8(d.xml),
33274
- normalizedSha256: sha256Utf8(normalizeSimaticMl(d.xml)),
33275
- bytes: Buffer.byteLength(d.xml, "utf8"),
33276
- hashNote: "sha256 = SHA-256 of the XML text as UTF-8 without BOM, line endings as TIA wrote them (CRLF). A git checkout (LF/BOM) or another export (<Created>, UIds) differs byte-wise \u2014 prove equality with tia_block_compare.",
33277
- xml: d.xml
33278
- });
33279
- } catch (e) {
33280
- return errorResult4(e);
33281
- }
33282
- }
33283
- async function blockCompareFlow(args) {
33284
- try {
33285
- const d = await fetchBlockXml(args.plc, args.block, args.options);
33286
- const opts = { ignoreFormatting: args.ignoreFormatting };
33287
- const r = compareSimaticMl(d.xml, args.xml, opts);
33288
- return textResult({
33289
- block: d.name,
33290
- verdict: r.equal ? "equal" : "different",
33291
- ...r,
33292
- projectNormalizedSha256: sha256Utf8(normalizeSimaticMl(d.xml, opts)),
33293
- givenNormalizedSha256: sha256Utf8(normalizeSimaticMl(args.xml, opts)),
33294
- note: "left = the block exported from the project now; right = the XML you passed (e.g. the file in git)."
33295
- });
33296
- } catch (e) {
33297
- return errorResult4(e);
33298
- }
33299
- }
33300
- function registerAsCodeTools(server2) {
33301
33822
  server2.registerTool(
33302
- "tia_export_block",
33823
+ "tia_mastersecret_set",
33303
33824
  {
33304
- title: "TIA \u2014 export one block (SimaticML, inline)",
33305
- description: "Exports ONE block as SimaticML XML and returns it INLINE with sha256, normalizedSha256 and bytes \u2014 no file on the serve host. Read-mostly \u2014 it does not change code/data, but the export may compile an inconsistent block first if needed (export requires consistency), which can regenerate its instance DB; treated as read for agent tool policy. Maps to GET /plcs/{plc}/blocks/{block}/xml. " + LONG_OPERATION_NOTE,
33825
+ title: "TIA \u2014 set master secret (GATE G6)",
33826
+ description: "Sets the master secret (password) of a protected CPU, before online/download. GATE G6: the password comes from a HUMAN (or a credential vault) \u2014 the AI NEVER makes it up. (Note: P3.7 questions sending the secret over HTTP in plain text; prefer local entry on the host.) Maps to POST /plcs/{plc}/online/mastersecret.",
33306
33827
  inputSchema: {
33828
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33307
33829
  plc: external_exports.string().describe("PLC name"),
33308
- block: external_exports.string().describe("block name"),
33309
- options: external_exports.string().optional().describe("ExportOptions: None (default), WithDefaults, WithReadOnly (comma-separated)")
33830
+ password: external_exports.string().describe("master secret provided by a human (NEVER made up by the AI)")
33310
33831
  }
33311
33832
  },
33312
- async ({ plc, block, options }) => jobs.run("tia_export_block", { plc, block, options }, () => exportBlockFlow(plc, block, options))
33833
+ async ({ plc, password }) => send("POST", `/plcs/${seg(plc)}/online/mastersecret`, jsonBody({ password }))
33313
33834
  );
33314
33835
  server2.registerTool(
33315
- "tia_block_compare",
33836
+ "tia_mastersecret_reset",
33316
33837
  {
33317
- title: "TIA \u2014 compare a block with given SimaticML",
33318
- description: "Exports the block from the project and compares it with the SimaticML you pass (e.g. the file committed in git). Like tia_export_block, this may compile an inconsistent block first (export requires consistency), which can regenerate its instance DB; read-mostly, treated as read for agent tool policy. Normalized: ignores BOM, line endings, indentation, blank lines, <Created>, <InstalledProducts>, UId attributes and \u2014 unless ignoreFormatting:false \u2014 <NewLine/>/<Blank/> formatting tokens (see the result's `ignored` field for the exact list). Returns verdict equal|different and the first differing line. This is the proof that the project contains what was versioned. Maps to GET /plcs/{plc}/blocks/{block}/xml. " + LONG_OPERATION_NOTE,
33319
- inputSchema: {
33320
- plc: external_exports.string().describe("PLC name"),
33321
- block: external_exports.string().describe("block name"),
33322
- xml: external_exports.string().describe("SimaticML XML to compare against (e.g. the committed file's content)"),
33323
- ignoreFormatting: external_exports.boolean().optional().describe("ignore <NewLine/>/<Blank/> code-formatting tokens (default true)"),
33324
- options: external_exports.string().optional().describe("ExportOptions used for the project side (default None)")
33325
- }
33838
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33839
+ title: "TIA \u2014 reset master secret",
33840
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33841
+ description: "Removes/resets the CPU's master secret. Maps to DELETE /plcs/{plc}/online/mastersecret.",
33842
+ // Stryker disable next-line StringLiteral: handoff prose, facts are tested
33843
+ inputSchema: { plc: external_exports.string().describe("PLC name") }
33326
33844
  },
33327
- async (args) => jobs.run("tia_block_compare", args, () => blockCompareFlow(args))
33845
+ async ({ plc }) => send("DELETE", `/plcs/${seg(plc)}/online/mastersecret`)
33328
33846
  );
33329
33847
  }
33330
33848
 
33331
33849
  // src/tools/spec.ts
33332
- var seg5 = (v) => encodeURIComponent(v);
33333
- var JSON_HEADERS2 = { "Content-Type": "application/json; charset=utf-8" };
33334
33850
  var TYPEID_RE = /^OrderNumber:.+\/V[0-9]+\.[0-9]+$/;
33335
- function jsonBody4(obj) {
33336
- const out = {};
33337
- for (const [k, v] of Object.entries(obj)) if (v !== void 0 && v !== null) out[k] = v;
33338
- return out;
33339
- }
33340
33851
  function ipToInt(ip) {
33341
33852
  const p = ip.split(".").map((x) => Number(x));
33342
33853
  if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
@@ -33360,11 +33871,43 @@ function checkUnique(names, rule, what, out) {
33360
33871
  seen.add(n);
33361
33872
  }
33362
33873
  }
33874
+ function rejectNonObjects(entries, what, out) {
33875
+ if (!Array.isArray(entries)) return;
33876
+ entries.forEach((entry, i) => {
33877
+ if (!isObject2(entry))
33878
+ out.push({ rule: "SCHEMA", severity: "error", detail: `${what}[${i}] is not an object \u2014 entries must be objects.` });
33879
+ });
33880
+ }
33363
33881
  function validateSpec(spec) {
33364
33882
  const v = [];
33365
33883
  const devices = Array.isArray(spec?.devices) ? spec.devices : [];
33366
33884
  if (!spec?.project?.name) v.push({ rule: "SCHEMA", severity: "error", detail: "project.name is required." });
33367
33885
  if (devices.length === 0) v.push({ rule: "SCHEMA", severity: "error", detail: "devices must have \u22651 item." });
33886
+ rejectNonObjects(devices, "device", v);
33887
+ devices.forEach((d, i) => {
33888
+ if (isObject2(d)) rejectNonObjects(d.modules, `device[${i}].modules`, v);
33889
+ });
33890
+ rejectNonObjects(spec?.subnets, "subnet", v);
33891
+ if (spec?.network?.subnet !== void 0 && !isObject2(spec.network.subnet))
33892
+ v.push({ rule: "SCHEMA", severity: "error", detail: "network.subnet is not an object \u2014 it must be { name, cidr }." });
33893
+ rejectNonObjects(spec?.network?.nodes, "network node", v);
33894
+ rejectNonObjects(spec?.tagTables, "tagTable", v);
33895
+ rejectNonObjects(spec?.tags, "tag", v);
33896
+ rejectNonObjects(spec?.dataTypes, "dataType", v);
33897
+ rejectNonObjects(spec?.blocks, "block", v);
33898
+ if (Array.isArray(spec?.functionalUnits)) {
33899
+ rejectNonObjects(spec.functionalUnits, "functionalUnit", v);
33900
+ spec.functionalUnits.forEach((fu, i) => {
33901
+ if (!isObject2(fu)) return;
33902
+ rejectNonObjects(fu.equipmentModules, `functionalUnit[${i}].equipmentModules`, v);
33903
+ if (Array.isArray(fu.equipmentModules)) {
33904
+ fu.equipmentModules.forEach((em, j) => {
33905
+ if (!isObject2(em)) return;
33906
+ rejectNonObjects(em.controlModules, `functionalUnit[${i}].equipmentModules[${j}].controlModules`, v);
33907
+ });
33908
+ }
33909
+ });
33910
+ }
33368
33911
  checkUnique(devices.map((d) => d?.name).filter(Boolean), "R-NAMES", "device", v);
33369
33912
  const subnetNames = [
33370
33913
  ...spec?.network?.subnet?.name ? [spec.network.subnet.name] : [],
@@ -33418,8 +33961,12 @@ function validateSpec(spec) {
33418
33961
  const sName = n?.subnet ?? net?.subnet?.name;
33419
33962
  const sub = sName ? subnetByName.get(sName) : void 0;
33420
33963
  if (!sub) v.push({ rule: "R-SUBNET", severity: "error", detail: `node "${n?.device}" references nonexistent subnet "${sName}".` });
33421
- else if (n?.ip && sub?.cidr && !ipInCidr(n.ip, sub.cidr))
33422
- v.push({ rule: "R-SUBNET", severity: "error", detail: `node "${n?.device}": IP ${n.ip} is outside CIDR ${sub.cidr} of subnet ${sName}.` });
33964
+ else if (n?.ip && sub?.cidr) {
33965
+ if (typeof n.ip !== "string" || typeof sub.cidr !== "string")
33966
+ v.push({ rule: "R-SUBNET", severity: "error", detail: `node "${n?.device}": IP and CIDR must be strings (got IP ${typeof n.ip}, CIDR ${typeof sub.cidr}) \u2014 fix the spec before applying.` });
33967
+ else if (!ipInCidr(n.ip, sub.cidr))
33968
+ v.push({ rule: "R-SUBNET", severity: "error", detail: `node "${n?.device}": IP ${n.ip} is outside CIDR ${sub.cidr} of subnet ${sName}.` });
33969
+ }
33423
33970
  if (n?.createIoSystem) {
33424
33971
  ioSystemCount++;
33425
33972
  ioSystemSubnet = n?.subnet ?? net?.subnet?.name ?? null;
@@ -33467,30 +34014,35 @@ function planSpec(spec) {
33467
34014
  for (const s of subnets) {
33468
34015
  if (!s?.name || subnetSeen.has(s.name)) continue;
33469
34016
  subnetSeen.add(s.name);
33470
- steps.push({ op: "subnet.create", method: "POST", path: "/subnets", body: jsonBody4({ typeIdentifier: s.type ?? "System:Subnet.Ethernet", name: s.name }), summary: `create subnet ${s.name}` });
34017
+ steps.push({ op: "subnet.create", method: "POST", path: "/subnets", body: jsonBody({ typeIdentifier: s.type ?? "System:Subnet.Ethernet", name: s.name }), summary: `create subnet ${s.name}` });
33471
34018
  }
33472
34019
  for (const d of Array.isArray(spec?.devices) ? spec.devices : []) {
33473
- steps.push({ op: "device.create", method: "POST", path: "/devices", body: jsonBody4({ typeIdentifier: d.typeIdentifier, deviceName: d.name }), summary: `create device ${d.name}` });
34020
+ if (!isObject2(d)) continue;
34021
+ steps.push({ op: "device.create", method: "POST", path: "/devices", body: jsonBody({ typeIdentifier: d.typeIdentifier, deviceName: d.name }), summary: `create device ${d.name}` });
33474
34022
  }
33475
34023
  for (const d of Array.isArray(spec?.devices) ? spec.devices : []) {
34024
+ if (!isObject2(d)) continue;
33476
34025
  for (const m of Array.isArray(d?.modules) ? d.modules : []) {
33477
- steps.push({ op: "device.plug", method: "POST", path: `/devices/${seg5(d.name)}/plug`, body: jsonBody4({ typeIdentifier: m.order, position: m.slot }), summary: `plug module into ${d.name}` });
34026
+ if (!isObject2(m)) continue;
34027
+ steps.push({ op: "device.plug", method: "POST", path: `/devices/${seg(d.name)}/plug`, body: jsonBody({ typeIdentifier: m.order, position: m.slot }), summary: `plug module into ${d.name}` });
33478
34028
  }
33479
34029
  }
33480
34030
  for (const n of Array.isArray(spec?.network?.nodes) ? spec.network.nodes : []) {
34031
+ if (!isObject2(n)) continue;
33481
34032
  const sName = n?.subnet ?? spec?.network?.subnet?.name;
33482
- steps.push({ op: "network.connect", method: "POST", path: "/network/connect", body: jsonBody4({ device: n.device, subnet: sName, ip: n.ip, createIoSystem: n.createIoSystem }), summary: `connect ${n.device} @ ${n.ip} to subnet ${sName}` });
34033
+ steps.push({ op: "network.connect", method: "POST", path: "/network/connect", body: jsonBody({ device: n.device, subnet: sName, ip: n.ip, createIoSystem: n.createIoSystem }), summary: `connect ${n.device} @ ${n.ip} to subnet ${sName}` });
33483
34034
  }
33484
34035
  if (plc) {
33485
34036
  const tableNames = /* @__PURE__ */ new Set();
33486
34037
  for (const tt of Array.isArray(spec?.tagTables) ? spec.tagTables : []) if (tt?.name) tableNames.add(tt.name);
33487
34038
  for (const t of Array.isArray(spec?.tags) ? spec.tags : []) if (t?.table) tableNames.add(t.table);
33488
- for (const name of tableNames) steps.push({ op: "tagtable.create", method: "POST", path: `/plcs/${seg5(plc)}/tagtables`, body: { name }, summary: `create tag table ${name}` });
34039
+ for (const name of tableNames) steps.push({ op: "tagtable.create", method: "POST", path: `/plcs/${seg(plc)}/tagtables`, body: { name }, summary: `create tag table ${name}` });
33489
34040
  for (const t of Array.isArray(spec?.tags) ? spec.tags : []) {
33490
- steps.push({ op: "tag.create", method: "POST", path: `/plcs/${seg5(plc)}/tags`, body: jsonBody4({ table: t.table, name: t.name, dataType: t.dataType, address: t.address }), summary: `create tag ${t.name}:${t.dataType}` });
34041
+ if (!isObject2(t)) continue;
34042
+ steps.push({ op: "tag.create", method: "POST", path: `/plcs/${seg(plc)}/tags`, body: jsonBody({ table: t.table, name: t.name, dataType: t.dataType, address: t.address }), summary: `create tag ${t.name}:${t.dataType}` });
33491
34043
  }
33492
34044
  for (const b of Array.isArray(spec?.blocks) ? spec.blocks : []) {
33493
- if (b?.kind === "FB") steps.push({ op: "fb.create", method: "POST", path: `/plcs/${seg5(plc)}/fbs`, body: jsonBody4({ name: b.name, language: b.language }), summary: `create FB ${b.name} (${b.language})` });
34045
+ if (b?.kind === "FB") steps.push({ op: "fb.create", method: "POST", path: `/plcs/${seg(plc)}/fbs`, body: jsonBody({ name: b.name, language: b.language }), summary: `create FB ${b.name} (${b.language})` });
33494
34046
  }
33495
34047
  const fcObDb = (Array.isArray(spec?.blocks) ? spec.blocks : []).filter((b) => b?.kind && b.kind !== "FB").map((b) => b.name);
33496
34048
  if (fcObDb.length) assumptions.push(`OB/FC/DB blocks (${fcObDb.join(", ")}) and their logic are not included in apply \u2014 author them via tia_source_put (SCL) / tia_import_xml (graphical).`);
@@ -33499,16 +34051,17 @@ function planSpec(spec) {
33499
34051
  for (const cm of Array.isArray(em?.controlModules) ? em.controlModules : []) {
33500
34052
  if (cm?.instanceDb && cm?.libraryType) {
33501
34053
  const fb = String(cm.libraryType).split("@")[0];
33502
- steps.push({ op: "instancedb.create", method: "POST", path: `/plcs/${seg5(plc)}/instancedbs`, body: jsonBody4({ name: cm.instanceDb, instanceOf: fb }), summary: `create iDB ${cm.instanceDb} from ${fb}` });
34054
+ steps.push({ op: "instancedb.create", method: "POST", path: `/plcs/${seg(plc)}/instancedbs`, body: jsonBody({ name: cm.instanceDb, instanceOf: fb }), summary: `create iDB ${cm.instanceDb} from ${fb}` });
33503
34055
  }
33504
34056
  }
33505
34057
  }
33506
34058
  }
33507
34059
  const ladder = Array.isArray(spec?.verification?.ladder) ? spec.verification.ladder : ["compile"];
33508
- if (ladder.includes("compile")) steps.push({ op: "compile", method: "POST", path: `/plcs/${seg5(plc)}/compile`, body: {}, summary: `compile ${plc} (verifier)` });
34060
+ if (ladder.includes("compile")) steps.push({ op: "compile", method: "POST", path: `/plcs/${seg(plc)}/compile`, body: {}, summary: `compile ${plc} (verifier)` });
33509
34061
  }
33510
34062
  return { steps, assumptions };
33511
34063
  }
34064
+ var SPEC_INSTALLING_HINT = "Serve is installing a TIAOpenness app update: the refused step did NOT run \u2014 but any earlier SUCCESSFUL steps in `applied` may have changed the project, so review `applied` (against a fresh dryRun plan) before doing anything else. Wait until the update finishes, then apply each remaining step individually with the matching M-off tool (or re-run the whole apply on a fresh project): this apply always restarts at step 0 and create steps are not idempotent, so it does NOT resume from the refused step. There is no background job for this call.";
33512
34065
  async function applySpec(spec, opts = {}) {
33513
34066
  if (spec?.safety?.required === true && spec?.autonomous === true) {
33514
34067
  return textResult({ status: "rejected", gate: "safety_signoff", reason: "G5: safety.required && autonomous \u21D2 REJECT (IEC 61511). Selecting an F-CPU is OK; authoring/downloading F is never autonomous." }, true);
@@ -33525,19 +34078,20 @@ async function applySpec(spec, opts = {}) {
33525
34078
  let compileResult = null;
33526
34079
  for (const s of steps) {
33527
34080
  try {
33528
- const data = await tiaFetch(s.path, { method: s.method, headers: JSON_HEADERS2, body: JSON.stringify(s.body) }, { timeoutMs: SLOW_TIMEOUT_MS });
34081
+ const data = await tiaFetch(s.path, { method: s.method, headers: JSON_HEADERS, body: JSON.stringify(s.body) }, { timeoutMs: SLOW_TIMEOUT_MS });
33529
34082
  applied.push({ op: s.op, summary: s.summary, ok: true });
33530
34083
  if (s.op === "compile") compileResult = data;
33531
34084
  } catch (e) {
33532
34085
  const err = asTiaError(e);
33533
34086
  applied.push({ op: s.op, summary: s.summary, ok: false, error: err.message, kind: err.kind });
33534
34087
  if (!opts.continueOnError) {
33535
- return textResult({ status: "stopped", appliedCount: applied.length, applied, stoppedAt: s.summary, error: err.message, kind: err.kind, assumptions, note: "Stopped at the 1st error (Gd2: re-running converges by name; pass continueOnError:true to keep going despite errors)." }, true);
34088
+ return textResult({ status: "stopped", appliedCount: applied.length, applied, stoppedAt: s.summary, error: err.message, kind: err.kind, ...isInstallingError(err) ? { hint: SPEC_INSTALLING_HINT } : {}, assumptions, note: "Stopped at the 1st error. Review `applied` (against a fresh dryRun plan) and apply each remaining step individually with the matching M-off tool, or re-run the whole apply on a fresh project \u2014 this apply restarts at step 0 and create steps are not idempotent. Pass continueOnError:true to keep going despite errors." }, true);
33536
34089
  }
33537
34090
  }
33538
34091
  }
33539
34092
  const okAll = applied.every((a) => a.ok);
33540
- return textResult({ status: okAll ? "applied" : "applied_with_errors", appliedCount: applied.length, applied, compile: compileResult, assumptions, warnings: val.violations.filter((x) => x.severity === "warning"), nextHints: ["Offline build complete. To deploy: review the compile, then tia_download (GATE G3, requires human approval)."] }, !okAll);
34093
+ const failedCount = applied.filter((a) => !a.ok).length;
34094
+ return textResult({ status: okAll ? "applied" : "applied_with_errors", appliedCount: applied.length, applied, compile: compileResult, assumptions, ...applied.some((a) => a.kind === "installing") ? { hint: SPEC_INSTALLING_HINT } : {}, warnings: val.violations.filter((x) => x.severity === "warning"), nextHints: okAll ? ["Offline build complete. To deploy: review the compile, then tia_download (GATE G3, requires human approval)."] : [`Build incomplete: ${failedCount} step(s) failed (see \`applied\` entries with ok:false). Apply the remainder individually with the matching M-off tools \u2014 this apply restarts at step 0 and create steps are not idempotent \u2014 then review the compile before any tia_download (GATE G3, requires human approval).`] }, !okAll);
33541
34095
  }
33542
34096
  function registerSpecTools(server2) {
33543
34097
  server2.registerTool(
@@ -33574,7 +34128,7 @@ function registerSpecTools(server2) {
33574
34128
  inputSchema: {
33575
34129
  spec: external_exports.record(external_exports.string(), external_exports.unknown()).describe("the project-spec"),
33576
34130
  dryRun: external_exports.boolean().optional().describe("true \u2192 returns the plan without applying"),
33577
- continueOnError: external_exports.boolean().optional().describe("true \u2192 does not stop at the 1st error (Gd2: re-running converges by name)")
34131
+ continueOnError: external_exports.boolean().optional().describe("true \u2192 keeps applying the remaining steps after an error instead of stopping at the 1st")
33578
34132
  }
33579
34133
  },
33580
34134
  // dryRun é puro (não chama o serve) → fora do runner. O apply real passa pelo runner com os args inteiros.
@@ -33633,75 +34187,22 @@ function registerGuideTool(server2) {
33633
34187
 
33634
34188
  // src/index.ts
33635
34189
  var server = new McpServer(
33636
- { name: "tia-openness", version: "1.5.0" },
34190
+ { name: "tia-openness", version: "1.6.1" },
33637
34191
  // Camada 1 (ambiente): o brief operacional viaja no handshake MCP — qualquer cliente
33638
34192
  // que honre `instructions` recebe gates/serial-only/pipeline sem instalar nada.
33639
34193
  { instructions: BRIEF }
33640
34194
  );
33641
- server.registerTool(
33642
- "tia_ping",
33643
- {
33644
- title: "TIA \u2014 connection diagnostics",
33645
- description: "Diagnoses connectivity to the TIA Openness `serve` API and whether the server is ACTIVATED. Tests GET /health (reachability) and GET /readiness (license activation). Ideal for the MCP-on-Mac-pointing-at-a-`serve`-on-a-Windows-VM scenario. Read-only. Returns { base, reachable, activated, latencyMs, hint }.",
33646
- inputSchema: {}
33647
- },
33648
- async () => {
33649
- const report = {
33650
- base: BASE,
33651
- timeoutMs: TIMEOUT_MS,
33652
- reachable: false,
33653
- activated: null,
33654
- latencyMs: null,
33655
- detail: null,
33656
- hint: null
33657
- };
33658
- const start = Date.now();
33659
- try {
33660
- await tiaFetch("/health");
33661
- report.reachable = true;
33662
- report.latencyMs = Date.now() - start;
33663
- } catch (e) {
33664
- const err = asTiaError(e);
33665
- report.detail = err.message;
33666
- report.hint = hintFor(err);
33667
- return textResult(report);
33668
- }
33669
- try {
33670
- await tiaFetch("/readiness");
33671
- report.activated = true;
33672
- } catch (e) {
33673
- const err = asTiaError(e);
33674
- report.activated = err.kind === "license_required" || err.status === 403 ? false : null;
33675
- report.detail = err.message;
33676
- report.hint = hintFor(err);
33677
- }
33678
- return textResult(report);
33679
- }
33680
- );
33681
- server.registerTool(
33682
- "tia_readiness",
33683
- {
33684
- title: "TIA \u2014 environment readiness",
33685
- description: "Readiness diagnostic for the TIA Openness V21 environment ON THE SERVE HOST (x64 process, Windows 'Siemens TIA Openness' group, PublicAPI, 21.0 registry key, and TIA instances). Call BEFORE connecting. Maps to GET /readiness. Read-only (class R). Returns { ready, checks:[{ name, status, detail, remediation }] }.",
33686
- inputSchema: {}
33687
- },
33688
- async () => {
33689
- try {
33690
- const data = await tiaFetch("/readiness");
33691
- return textResult(data);
33692
- } catch (e) {
33693
- const err = asTiaError(e);
33694
- return textResult({ error: err.message, kind: err.kind, status: err.status, details: err.details ?? null, hint: hintFor(err) }, true);
33695
- }
33696
- }
33697
- );
34195
+ registerDiagnosticTools(server);
33698
34196
  registerGuideTool(server);
33699
34197
  registerJobTools(server);
33700
34198
  registerReadOnlyTools(server);
33701
34199
  registerLifecycleTools(server);
33702
34200
  registerAuthoringTools(server);
33703
34201
  registerAsCodeTools(server);
33704
- registerVerificationTools(server);
34202
+ registerCompileTools(server);
34203
+ registerDownloadTools(server);
34204
+ registerUploadTools(server);
34205
+ registerOnlineTools(server);
33705
34206
  registerSpecTools(server);
33706
34207
  async function main() {
33707
34208
  const transport = new StdioServerTransport();