forked from CoplayDev/unity-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManageScript.cs
More file actions
3018 lines (2741 loc) · 140 KB
/
Copy pathManageScript.cs
File metadata and controls
3018 lines (2741 loc) · 140 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
using MCPForUnity.Editor.Constants;
using MCPForUnity.Editor.Helpers;
using System.Threading;
using System.Security.Cryptography;
#if USE_ROSLYN
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Formatting;
#endif
#if UNITY_EDITOR
using UnityEditor.Compilation;
#endif
namespace MCPForUnity.Editor.Tools
{
/// <summary>
/// Handles CRUD operations for C# scripts within the Unity project.
/// </summary>
/// <remarks>
/// ROSLYN INSTALLATION GUIDE:
/// To enable advanced syntax validation with Roslyn compiler services:
///
/// 1. Install Microsoft.CodeAnalysis.CSharp NuGet package:
/// - Open Package Manager in Unity
/// - Follow the instruction on https://github.com/GlitchEnzo/NuGetForUnity
///
/// 2. Open NuGet Package Manager and Install Microsoft.CodeAnalysis.CSharp:
///
/// 3. Alternative: Manual DLL installation:
/// - Download Microsoft.CodeAnalysis.CSharp.dll and dependencies
/// - Place in Assets/Plugins/ folder
/// - Ensure .NET compatibility settings are correct
///
/// 4. Define USE_ROSLYN symbol:
/// - Go to Player Settings > Scripting Define Symbols
/// - Add "USE_ROSLYN" to enable Roslyn-based validation
///
/// 5. Restart Unity after installation
///
/// Note: Without Roslyn, the system falls back to basic structural validation.
/// Roslyn provides full C# compiler diagnostics with line numbers and detailed error messages.
/// </remarks>
[McpForUnityTool("manage_script", AutoRegister = false)]
public static class ManageScript
{
/// <summary>
/// Resolves a directory under Assets/, preventing traversal and escaping.
/// Returns fullPathDir on disk and canonical 'Assets/...' relative path.
/// </summary>
private static bool TryResolveUnderAssets(string relDir, out string fullPathDir, out string relPathSafe)
{
string assets = AssetPathUtility.NormalizeSeparators(Application.dataPath);
// Normalize caller path: allow both "Scripts/..." and "Assets/Scripts/..."
string rel = AssetPathUtility.NormalizeSeparators(relDir ?? "Scripts").Trim();
if (string.IsNullOrEmpty(rel)) rel = "Scripts";
// Handle both "Assets" and "Assets/" prefixes
if (rel.Equals("Assets", StringComparison.OrdinalIgnoreCase))
{
rel = string.Empty;
}
else if (rel.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
{
rel = rel.Substring(7);
}
rel = rel.TrimStart('/');
string targetDir = AssetPathUtility.NormalizeSeparators(Path.Combine(assets, rel));
string full = AssetPathUtility.NormalizeSeparators(Path.GetFullPath(targetDir));
bool underAssets = full.StartsWith(assets + "/", StringComparison.OrdinalIgnoreCase)
|| string.Equals(full, assets, StringComparison.OrdinalIgnoreCase);
if (!underAssets)
{
fullPathDir = null;
relPathSafe = null;
return false;
}
// Best-effort symlink guard: if the directory OR ANY ANCESTOR (up to Assets/) is a reparse point/symlink, reject
try
{
var di = new DirectoryInfo(full);
while (di != null)
{
if (di.Exists && (di.Attributes & FileAttributes.ReparsePoint) != 0)
{
fullPathDir = null;
relPathSafe = null;
return false;
}
var atAssets = string.Equals(
di.FullName.Replace('\\', '/'),
assets,
StringComparison.OrdinalIgnoreCase
);
if (atAssets) break;
di = di.Parent;
}
}
catch { /* best effort; proceed */ }
fullPathDir = full;
string tail = full.Length > assets.Length ? full.Substring(assets.Length).TrimStart('/') : string.Empty;
relPathSafe = ("Assets/" + tail).TrimEnd('/');
return true;
}
/// <summary>
/// Main handler for script management actions.
/// </summary>
public static object HandleCommand(JObject @params)
{
// Handle null parameters
if (@params == null)
{
return new ErrorResponse("invalid_params", "Parameters cannot be null.");
}
var p = new ToolParams(@params);
// Extract and validate required parameters
var actionResult = p.GetRequired("action");
if (!actionResult.IsSuccess)
{
return new ErrorResponse(actionResult.ErrorMessage);
}
string action = actionResult.Value.ToLowerInvariant();
var nameResult = p.GetRequired("name");
if (!nameResult.IsSuccess)
{
return new ErrorResponse(nameResult.ErrorMessage);
}
string name = nameResult.Value;
// Optional parameters
string path = p.Get("path"); // Relative to Assets/
// If the caller passed a full file path (e.g. "Assets/Scripts/Foo.cs"),
// strip the filename so path is treated as a directory.
if (path != null && path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
{
path = Path.GetDirectoryName(path)?.Replace('\\', '/');
}
string contents = null;
// Check if we have base64 encoded contents
bool contentsEncoded = p.GetBool("contentsEncoded", false);
if (contentsEncoded && p.Has("encodedContents"))
{
try
{
contents = DecodeBase64(p.Get("encodedContents"));
}
catch (Exception e)
{
return new ErrorResponse($"Failed to decode script contents: {e.Message}");
}
}
else
{
contents = p.Get("contents");
}
string scriptType = p.Get("scriptType"); // For templates/validation
string namespaceName = p.Get("namespace"); // For organizing code
// Basic name validation (alphanumeric, underscores, cannot start with number)
if (!Regex.IsMatch(name, @"^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(2)))
{
return new ErrorResponse(
$"Invalid script name: '{name}'. Use only letters, numbers, underscores, and don't start with a number."
);
}
// Resolve and harden target directory under Assets/
if (!TryResolveUnderAssets(path, out string fullPathDir, out string relPathSafeDir))
{
return new ErrorResponse($"Invalid path. Target directory must be within 'Assets/'. Provided: '{(path ?? "(null)")}'");
}
// Construct file paths
string scriptFileName = $"{name}.cs";
string fullPath = Path.Combine(fullPathDir, scriptFileName);
string relativePath = AssetPathUtility.NormalizeSeparators(Path.Combine(relPathSafeDir, scriptFileName));
// Ensure the target directory exists for create/update
if (action == "create" || action == "update")
{
try
{
Directory.CreateDirectory(fullPathDir);
}
catch (Exception e)
{
return new ErrorResponse(
$"Could not create directory '{fullPathDir}': {e.Message}"
);
}
}
// Route to specific action handlers
switch (action)
{
case "create":
return CreateScript(
fullPath,
relativePath,
name,
contents,
scriptType,
namespaceName
);
case "read":
McpLog.Warn("manage_script.read is deprecated; prefer resources/read. Serving read for backward compatibility.");
return ReadScript(fullPath, relativePath);
case "update":
McpLog.Warn("manage_script.update is deprecated; prefer apply_text_edits. Serving update for backward compatibility.");
return UpdateScript(fullPath, relativePath, name, contents);
case "delete":
return DeleteScript(fullPath, relativePath);
case "apply_text_edits":
{
var textEdits = p.GetRaw("edits") as JArray;
string precondition = p.Get("precondition_sha256");
// Respect optional options (guard type before indexing)
var optionsObj = p.GetRaw("options") as JObject;
string refreshOpt = optionsObj?["refresh"]?.ToString()?.ToLowerInvariant();
string validateOpt = optionsObj?["validate"]?.ToString()?.ToLowerInvariant();
return ApplyTextEdits(fullPath, relativePath, name, textEdits, precondition, refreshOpt, validateOpt);
}
case "validate":
{
string level = p.Get("level", "standard").ToLowerInvariant();
var chosen = level switch
{
"basic" => ValidationLevel.Basic,
"standard" => ValidationLevel.Standard,
"strict" => ValidationLevel.Strict,
"comprehensive" => ValidationLevel.Comprehensive,
_ => ValidationLevel.Standard
};
string fileText;
try { fileText = File.ReadAllText(fullPath); }
catch (Exception ex) { return new ErrorResponse($"Failed to read script: {ex.Message}"); }
bool ok = ValidateScriptSyntax(fileText, chosen, out string[] diagsRaw);
var diags = (diagsRaw ?? Array.Empty<string>()).Select(s =>
{
var m = Regex.Match(
s,
@"^(ERROR|WARNING|INFO): (.*?)(?: \(Line (\d+)\))?$",
RegexOptions.CultureInvariant | RegexOptions.Multiline,
TimeSpan.FromMilliseconds(250)
);
string severity = m.Success ? m.Groups[1].Value.ToLowerInvariant() : "info";
string message = m.Success ? m.Groups[2].Value : s;
int lineNum = m.Success && int.TryParse(m.Groups[3].Value, out var l) ? l : 0;
return new { line = lineNum, col = 0, severity, message };
}).ToArray();
var result = new { diagnostics = diags };
return ok ? new SuccessResponse("Validation completed.", result)
: new ErrorResponse("Validation failed.", result);
}
case "edit":
McpLog.Warn("manage_script.edit is deprecated; prefer apply_text_edits. Serving structured edit for backward compatibility.");
var structEdits = @params["edits"] as JArray;
var options = @params["options"] as JObject;
return EditScript(fullPath, relativePath, name, structEdits, options);
case "get_sha":
{
try
{
if (!File.Exists(fullPath))
return new ErrorResponse($"Script not found at '{relativePath}'.");
string text = File.ReadAllText(fullPath);
string sha = ComputeSha256(text);
var fi = new FileInfo(fullPath);
long lengthBytes;
try { lengthBytes = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetByteCount(text); }
catch { lengthBytes = fi.Exists ? fi.Length : 0; }
var data = new
{
uri = $"mcpforunity://path/{relativePath}",
path = relativePath,
sha256 = sha,
lengthBytes,
lastModifiedUtc = fi.Exists ? fi.LastWriteTimeUtc.ToString("o") : string.Empty
};
return new SuccessResponse($"SHA computed for '{relativePath}'.", data);
}
catch (Exception ex)
{
return new ErrorResponse($"Failed to compute SHA: {ex.Message}");
}
}
default:
return new ErrorResponse(
$"Unknown action: '{action}'. Valid actions are: create, delete, apply_text_edits, validate, read (deprecated), update (deprecated), edit (deprecated)."
);
}
}
/// <summary>
/// Decode base64 string to normal text
/// </summary>
private static string DecodeBase64(string encoded)
{
byte[] data = Convert.FromBase64String(encoded);
return System.Text.Encoding.UTF8.GetString(data);
}
/// <summary>
/// Encode text to base64 string
/// </summary>
private static string EncodeBase64(string text)
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(data);
}
private static object CreateScript(
string fullPath,
string relativePath,
string name,
string contents,
string scriptType,
string namespaceName
)
{
// Check if script already exists
if (File.Exists(fullPath))
{
return new ErrorResponse(
$"Script already exists at '{relativePath}'. Use 'update' action to modify."
);
}
// Generate default content if none provided
if (string.IsNullOrEmpty(contents))
{
contents = GenerateDefaultScriptContent(name, scriptType, namespaceName);
}
// Validate syntax with detailed error reporting using GUI setting
ValidationLevel validationLevel = GetValidationLevelFromGUI();
bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);
if (!isValid)
{
return new ErrorResponse("validation_failed", new { status = "validation_failed", diagnostics = validationErrors ?? Array.Empty<string>() });
}
else if (validationErrors != null && validationErrors.Length > 0)
{
// Log warnings but don't block creation
McpLog.Warn($"Script validation warnings for {name}:\n" + string.Join("\n", validationErrors));
}
try
{
// Atomic create without BOM; schedule refresh after reply
var enc = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
var tmp = fullPath + ".tmp";
File.WriteAllText(tmp, contents, enc);
try
{
File.Move(tmp, fullPath);
}
catch (IOException)
{
File.Copy(tmp, fullPath, overwrite: true);
try { File.Delete(tmp); } catch { }
}
var uri = $"mcpforunity://path/{relativePath}";
var ok = new SuccessResponse(
$"Script '{name}.cs' created successfully at '{relativePath}'.",
new { uri, scheduledRefresh = false }
);
ManageScriptRefreshHelpers.ImportAndRequestCompile(relativePath);
return ok;
}
catch (Exception e)
{
return new ErrorResponse($"Failed to create script '{relativePath}': {e.Message}");
}
}
private static object ReadScript(string fullPath, string relativePath)
{
if (!File.Exists(fullPath))
{
return new ErrorResponse($"Script not found at '{relativePath}'.");
}
try
{
string contents = File.ReadAllText(fullPath);
// Return both normal and encoded contents for larger files
bool isLarge = contents.Length > 10000; // If content is large, include encoded version
var uri = $"mcpforunity://path/{relativePath}";
var responseData = new
{
uri,
path = relativePath,
contents = contents,
// For large files, also include base64-encoded version
encodedContents = isLarge ? EncodeBase64(contents) : null,
contentsEncoded = isLarge,
};
return new SuccessResponse(
$"Script '{Path.GetFileName(relativePath)}' read successfully.",
responseData
);
}
catch (Exception e)
{
return new ErrorResponse($"Failed to read script '{relativePath}': {e.Message}");
}
}
private static object UpdateScript(
string fullPath,
string relativePath,
string name,
string contents
)
{
if (!File.Exists(fullPath))
{
return new ErrorResponse(
$"Script not found at '{relativePath}'. Use 'create' action to add a new script."
);
}
if (string.IsNullOrEmpty(contents))
{
return new ErrorResponse("Content is required for the 'update' action.");
}
// Validate syntax with detailed error reporting using GUI setting
ValidationLevel validationLevel = GetValidationLevelFromGUI();
bool isValid = ValidateScriptSyntax(contents, validationLevel, out string[] validationErrors);
if (!isValid)
{
return new ErrorResponse("validation_failed", new { status = "validation_failed", diagnostics = validationErrors ?? Array.Empty<string>() });
}
else if (validationErrors != null && validationErrors.Length > 0)
{
// Log warnings but don't block update
McpLog.Warn($"Script validation warnings for {name}:\n" + string.Join("\n", validationErrors));
}
try
{
// Safe write with atomic replace when available, without BOM
var encoding = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
string tempPath = fullPath + ".tmp";
File.WriteAllText(tempPath, contents, encoding);
string backupPath = fullPath + ".bak";
try
{
File.Replace(tempPath, fullPath, backupPath);
try { if (File.Exists(backupPath)) File.Delete(backupPath); } catch { }
}
catch (PlatformNotSupportedException)
{
File.Copy(tempPath, fullPath, true);
try { File.Delete(tempPath); } catch { }
try { if (File.Exists(backupPath)) File.Delete(backupPath); } catch { }
}
catch (IOException)
{
File.Copy(tempPath, fullPath, true);
try { File.Delete(tempPath); } catch { }
try { if (File.Exists(backupPath)) File.Delete(backupPath); } catch { }
}
// Prepare success response BEFORE any operation that can trigger a domain reload
var uri = $"mcpforunity://path/{relativePath}";
var ok = new SuccessResponse(
$"Script '{name}.cs' updated successfully at '{relativePath}'.",
new { uri, path = relativePath, scheduledRefresh = true }
);
// Schedule a debounced import/compile on next editor tick to avoid stalling the reply
ManageScriptRefreshHelpers.ScheduleScriptRefresh(relativePath);
return ok;
}
catch (Exception e)
{
return new ErrorResponse($"Failed to update script '{relativePath}': {e.Message}");
}
}
/// <summary>
/// Apply simple text edits specified by line/column ranges. Applies transactionally and validates result.
/// </summary>
private const int MaxEditPayloadBytes = 64 * 1024;
private static object ApplyTextEdits(
string fullPath,
string relativePath,
string name,
JArray edits,
string preconditionSha256,
string refreshModeFromCaller = null,
string validateMode = null)
{
if (!File.Exists(fullPath))
return new ErrorResponse($"Script not found at '{relativePath}'.");
// Refuse edits if the target or any ancestor is a symlink
try
{
var di = new DirectoryInfo(Path.GetDirectoryName(fullPath) ?? "");
while (di != null && !string.Equals(di.FullName.Replace('\\', '/'), Application.dataPath.Replace('\\', '/'), StringComparison.OrdinalIgnoreCase))
{
if (di.Exists && (di.Attributes & FileAttributes.ReparsePoint) != 0)
return new ErrorResponse("Refusing to edit a symlinked script path.");
di = di.Parent;
}
}
catch
{
// If checking attributes fails, proceed without the symlink guard
}
if (edits == null || edits.Count == 0)
return new ErrorResponse("No edits provided.");
string original;
try { original = File.ReadAllText(fullPath); }
catch (Exception ex) { return new ErrorResponse($"Failed to read script: {ex.Message}"); }
// Require precondition to avoid drift on large files
string currentSha = ComputeSha256(original);
if (string.IsNullOrEmpty(preconditionSha256))
return new ErrorResponse("precondition_required", new { status = "precondition_required", current_sha256 = currentSha });
if (!preconditionSha256.Equals(currentSha, StringComparison.OrdinalIgnoreCase))
return new ErrorResponse("stale_file", new { status = "stale_file", expected_sha256 = preconditionSha256, current_sha256 = currentSha });
// Convert edits to absolute index ranges
var spans = new List<(int start, int end, string text)>();
long totalBytes = 0;
foreach (var e in edits)
{
try
{
int sl = Math.Max(1, e.Value<int>("startLine"));
int sc = Math.Max(1, e.Value<int>("startCol"));
int el = Math.Max(1, e.Value<int>("endLine"));
int ec = Math.Max(1, e.Value<int>("endCol"));
string newText = e.Value<string>("newText") ?? string.Empty;
if (!TryIndexFromLineCol(original, sl, sc, out int sidx))
return new ErrorResponse($"apply_text_edits: start out of range (line {sl}, col {sc})");
if (!TryIndexFromLineCol(original, el, ec, out int eidx))
return new ErrorResponse($"apply_text_edits: end out of range (line {el}, col {ec})");
if (eidx < sidx) (sidx, eidx) = (eidx, sidx);
spans.Add((sidx, eidx, newText));
checked
{
totalBytes += System.Text.Encoding.UTF8.GetByteCount(newText);
}
}
catch (Exception ex)
{
return new ErrorResponse($"Invalid edit payload: {ex.Message}");
}
}
// Header guard: refuse edits that touch before the first 'using ' directive (after optional BOM) to prevent file corruption
int headerBoundary = (original.Length > 0 && original[0] == '\uFEFF') ? 1 : 0; // skip BOM once if present
// Find first top-level using (supports alias, static, and dotted namespaces)
var mUsing = System.Text.RegularExpressions.Regex.Match(
original,
@"(?m)^\s*using\s+(?:static\s+)?(?:[A-Za-z_]\w*\s*=\s*)?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*\s*;",
System.Text.RegularExpressions.RegexOptions.CultureInvariant,
TimeSpan.FromSeconds(2)
);
if (mUsing.Success)
{
headerBoundary = Math.Min(Math.Max(headerBoundary, mUsing.Index), original.Length);
}
foreach (var sp in spans)
{
if (sp.start < headerBoundary)
{
return new ErrorResponse("using_guard", new { status = "using_guard", hint = "Refusing to edit before the first 'using'. Use anchor_insert near a method or a structured edit." });
}
}
// Attempt auto-upgrade: if a single edit targets a method header/body, re-route as structured replace_method
if (spans.Count == 1)
{
var sp = spans[0];
// Heuristic: around the start of the edit, try to match a method header in original
int searchStart = Math.Max(0, sp.start - 200);
int searchEnd = Math.Min(original.Length, sp.start + 200);
string slice = original.Substring(searchStart, searchEnd - searchStart);
var rx = new System.Text.RegularExpressions.Regex(@"(?m)^[\t ]*(?:\[[^\]]+\][\t ]*)*[\t ]*(?:public|private|protected|internal|static|virtual|override|sealed|async|extern|unsafe|new|partial)[\s\S]*?\b([A-Za-z_][A-Za-z0-9_]*)\s*\(");
var mh = rx.Match(slice);
if (mh.Success)
{
string methodName = mh.Groups[1].Value;
// Find class span containing the edit
if (TryComputeClassSpan(original, name, null, out var clsStart, out var clsLen, out _))
{
if (TryComputeMethodSpan(original, clsStart, clsLen, methodName, null, null, null, out var mStart, out var mLen, out _))
{
// If the edit overlaps the method span significantly, treat as replace_method
if (sp.start <= mStart + 2 && sp.end >= mStart + 1)
{
var structEdits = new JArray();
// Apply the edit to get a candidate string, then recompute method span on the edited text
string candidate = original.Remove(sp.start, sp.end - sp.start).Insert(sp.start, sp.text ?? string.Empty);
string replacementText;
if (TryComputeClassSpan(candidate, name, null, out var cls2Start, out var cls2Len, out _)
&& TryComputeMethodSpan(candidate, cls2Start, cls2Len, methodName, null, null, null, out var m2Start, out var m2Len, out _))
{
replacementText = candidate.Substring(m2Start, m2Len);
}
else
{
// Fallback: adjust method start by the net delta if the edit was before the method
int delta = (sp.text?.Length ?? 0) - (sp.end - sp.start);
int adjustedStart = mStart + (sp.start <= mStart ? delta : 0);
adjustedStart = Math.Max(0, Math.Min(adjustedStart, candidate.Length));
// If the edit was within the original method span, adjust the length by the delta within-method
int withinMethodDelta = 0;
if (sp.start >= mStart && sp.start <= mStart + mLen)
{
withinMethodDelta = delta;
}
int adjustedLen = mLen + withinMethodDelta;
adjustedLen = Math.Max(0, Math.Min(candidate.Length - adjustedStart, adjustedLen));
replacementText = candidate.Substring(adjustedStart, adjustedLen);
}
var op = new JObject
{
["mode"] = "replace_method",
["className"] = name,
["methodName"] = methodName,
["replacement"] = replacementText
};
structEdits.Add(op);
// Reuse structured path
return EditScript(fullPath, relativePath, name, structEdits, new JObject { ["refresh"] = "immediate", ["validate"] = "standard" });
}
}
}
}
}
if (totalBytes > MaxEditPayloadBytes)
{
return new ErrorResponse("too_large", new { status = "too_large", limitBytes = MaxEditPayloadBytes, hint = "split into smaller edits" });
}
// Ensure non-overlap and apply from back to front
spans = spans.OrderByDescending(t => t.start).ToList();
for (int i = 1; i < spans.Count; i++)
{
if (spans[i].end > spans[i - 1].start)
{
var conflict = new[] { new { startA = spans[i].start, endA = spans[i].end, startB = spans[i - 1].start, endB = spans[i - 1].end } };
return new ErrorResponse("overlap", new { status = "overlap", conflicts = conflict, hint = "Sort ranges descending by start and compute from the same snapshot." });
}
}
string working = original;
bool syntaxOnly = string.Equals(validateMode, "syntax", StringComparison.OrdinalIgnoreCase);
foreach (var sp in spans)
{
working = working.Remove(sp.start, sp.end - sp.start).Insert(sp.start, sp.text ?? string.Empty);
}
// No-op guard: if resulting text is identical, avoid writes and return explicit no-op
if (string.Equals(working, original, StringComparison.Ordinal))
{
string noChangeSha = ComputeSha256(original);
return new SuccessResponse(
$"No-op: contents unchanged for '{relativePath}'.",
new
{
uri = $"mcpforunity://path/{relativePath}",
path = relativePath,
editsApplied = 0,
no_op = true,
sha256 = noChangeSha,
evidence = new { reason = "identical_content" }
}
);
}
// Always check final structural balance
if (!CheckBalancedDelimiters(working, out int line, out char expected))
{
int startLine = Math.Max(1, line - 5);
int endLine = line + 5;
string hint = $"unbalanced_braces at line {line}. Call resources/read for lines {startLine}-{endLine} and resend a smaller apply_text_edits that restores balance.";
return new ErrorResponse(hint, new { status = "unbalanced_braces", line, expected = expected.ToString(), evidenceWindow = new { startLine, endLine } });
}
#if USE_ROSLYN
if (!syntaxOnly)
{
var tree = CSharpSyntaxTree.ParseText(working);
var diagnostics = tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Take(3)
.Select(d => new {
line = d.Location.GetLineSpan().StartLinePosition.Line + 1,
col = d.Location.GetLineSpan().StartLinePosition.Character + 1,
code = d.Id,
message = d.GetMessage()
}).ToArray();
if (diagnostics.Length > 0)
{
int firstLine = diagnostics[0].line;
int startLineRos = Math.Max(1, firstLine - 5);
int endLineRos = firstLine + 5;
return new ErrorResponse("syntax_error", new { status = "syntax_error", diagnostics, evidenceWindow = new { startLine = startLineRos, endLine = endLineRos } });
}
// Optional formatting
try
{
var root = tree.GetRoot();
var workspace = new AdhocWorkspace();
root = Microsoft.CodeAnalysis.Formatting.Formatter.Format(root, workspace);
working = root.ToFullString();
}
catch { }
}
#endif
string newSha = ComputeSha256(working);
// Atomic write and schedule refresh
try
{
var enc = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
var tmp = fullPath + ".tmp";
File.WriteAllText(tmp, working, enc);
string backup = fullPath + ".bak";
try
{
File.Replace(tmp, fullPath, backup);
try { if (File.Exists(backup)) File.Delete(backup); } catch { /* ignore */ }
}
catch (PlatformNotSupportedException)
{
File.Copy(tmp, fullPath, true);
try { File.Delete(tmp); } catch { }
try { if (File.Exists(backup)) File.Delete(backup); } catch { }
}
catch (IOException)
{
File.Copy(tmp, fullPath, true);
try { File.Delete(tmp); } catch { }
try { if (File.Exists(backup)) File.Delete(backup); } catch { }
}
// Respect refresh mode: immediate vs debounced
bool immediate = string.Equals(refreshModeFromCaller, "immediate", StringComparison.OrdinalIgnoreCase) ||
string.Equals(refreshModeFromCaller, "sync", StringComparison.OrdinalIgnoreCase);
if (immediate)
{
McpLog.Info($"[ManageScript] ApplyTextEdits: immediate refresh for '{relativePath}'");
AssetDatabase.ImportAsset(
relativePath,
ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate
);
#if UNITY_EDITOR
UnityEditor.Compilation.CompilationPipeline.RequestScriptCompilation();
#endif
}
else
{
McpLog.Info($"[ManageScript] ApplyTextEdits: debounced refresh scheduled for '{relativePath}'");
ManageScriptRefreshHelpers.ScheduleScriptRefresh(relativePath);
}
return new SuccessResponse(
$"Applied {spans.Count} text edit(s) to '{relativePath}'.",
new
{
uri = $"mcpforunity://path/{relativePath}",
path = relativePath,
editsApplied = spans.Count,
sha256 = newSha,
scheduledRefresh = !immediate
}
);
}
catch (Exception ex)
{
return new ErrorResponse($"Failed to write edits: {ex.Message}");
}
}
private static bool TryIndexFromLineCol(string text, int line1, int col1, out int index)
{
// 1-based line/col to absolute index (0-based), col positions are counted in code points
int line = 1, col = 1;
for (int i = 0; i <= text.Length; i++)
{
if (line == line1 && col == col1)
{
index = i;
return true;
}
if (i == text.Length) break;
char c = text[i];
if (c == '\r')
{
// Treat CRLF as a single newline; skip the LF if present
if (i + 1 < text.Length && text[i + 1] == '\n')
i++;
line++;
col = 1;
}
else if (c == '\n')
{
line++;
col = 1;
}
else
{
col++;
}
}
index = -1;
return false;
}
private static string ComputeSha256(string contents)
{
using (var sha = SHA256.Create())
{
var bytes = System.Text.Encoding.UTF8.GetBytes(contents);
var hash = sha.ComputeHash(bytes);
return BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant();
}
}
/// <summary>
/// Lightweight lexer that tracks whether the current position is inside a
/// string literal (regular, verbatim, interpolated, raw) or a comment.
/// Callers advance character-by-character and check <see cref="InNonCode"/>.
/// </summary>
private struct CSharpLexer
{
private readonly string _text;
private int _pos;
private readonly int _end;
private int _line;
// String/comment state
private bool _inSingleComment;
private bool _inMultiComment;
public CSharpLexer(string text, int start = 0, int end = -1)
{
_text = text;
_pos = start;
_end = end < 0 ? text.Length : end;
_line = 1;
// count newlines before start
for (int i = 0; i < start && i < text.Length; i++)
if (text[i] == '\n') _line++;
_inSingleComment = false;
_inMultiComment = false;
InNonCode = false;
}
public bool InNonCode { get; private set; }
public int Position => _pos;
public int Line => _line;
/// <summary>
/// Advance to the next character, updating all state.
/// Returns false at end of range.
/// </summary>
public bool Advance(out char c)
{
if (_pos >= _end) { c = '\0'; return false; }
c = _text[_pos];
char next = _pos + 1 < _end ? _text[_pos + 1] : '\0';
if (c == '\n')
{
_line++;
if (_inSingleComment) _inSingleComment = false;
}
// Inside single-line comment
if (_inSingleComment) { InNonCode = true; _pos++; return true; }
// Inside multi-line comment
if (_inMultiComment)
{
if (c == '*' && next == '/') { _inMultiComment = false; InNonCode = true; _pos += 2; c = '/'; return true; }
InNonCode = true; _pos++; return true;
}
// Start of comment
if (c == '/' && next == '/') { _inSingleComment = true; InNonCode = true; _pos += 2; return true; }
if (c == '/' && next == '*') { _inMultiComment = true; InNonCode = true; _pos += 2; return true; }
// Interpolated raw string: $"""...""" or $$"""...""" etc. (C# 11)
// Must check BEFORE regular $" and BEFORE plain """
if (c == '$')
{
int dollarCount = 1;
while (_pos + dollarCount < _end && _text[_pos + dollarCount] == '$') dollarCount++;
int afterDollars = _pos + dollarCount;
if (afterDollars + 2 < _end && _text[afterDollars] == '"' && _text[afterDollars + 1] == '"' && _text[afterDollars + 2] == '"')
{
int q = 3;
while (afterDollars + q < _end && _text[afterDollars + q] == '"') q++;
_pos = afterDollars + q; // past all opening quotes
SkipInterpolatedRawStringBody(dollarCount, q);
InNonCode = true; return true;
}
}
// Raw string literal: """...""" (C# 11, non-interpolated)
if (c == '"' && next == '"' && _pos + 2 < _end && _text[_pos + 2] == '"')
{
int q = 3;
while (_pos + q < _end && _text[_pos + q] == '"') q++;
_pos += q; // past opening quotes
int closeCount = 0;
while (_pos < _end)
{
if (_text[_pos] == '\n') _line++;
if (_text[_pos] == '"') { closeCount++; if (closeCount >= q) { _pos++; break; } }
else closeCount = 0;
_pos++;
}
InNonCode = true; return true;
}
// Interpolated string: $"..." or $@"..." or @$"..."
if ((c == '$' && next == '"') ||
(c == '$' && next == '@' && _pos + 2 < _end && _text[_pos + 2] == '"') ||
(c == '@' && next == '$' && _pos + 2 < _end && _text[_pos + 2] == '"'))
{
bool isVerbatim = (next == '@') || (c == '@');
_pos += (c == '$' && next == '"') ? 2 : 3;
SkipInterpolatedStringBody(isVerbatim);
InNonCode = true; return true;
}
// Verbatim string: @"..."
if (c == '@' && next == '"')
{
_pos += 2;
while (_pos < _end)
{
if (_text[_pos] == '\n') _line++;
if (_text[_pos] == '"')
{
if (_pos + 1 < _end && _text[_pos + 1] == '"') { _pos += 2; continue; }
_pos++; break;
}
_pos++;
}
InNonCode = true; return true;
}
// Regular string: "..."
if (c == '"')
{
_pos++;
while (_pos < _end)
{
if (_text[_pos] == '\\') { _pos += 2; continue; }
if (_text[_pos] == '"') { _pos++; break; }