Repository navigation
Expand file tree
/
Copy pathProgram.fs
More file actions
1367 lines (1172 loc) · 72.6 KB
/
Copy pathProgram.fs
File metadata and controls
1367 lines (1172 loc) · 72.6 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
module FsLangMcp.Program
open System
open System.IO
open System.Diagnostics
open System.Threading
open System.Threading.Tasks
open FsLangMcp.Types
open FsLangMcp.LspBridge
open FsLangMcp.FcsBridge
open FsLangMcp.ProjectHealth
open FsLangMcp.ProjectInspection
open FsLangMcp.Tools
open FsLangMcp.RuntimeStatus
open FsLangMcp.ProcessRunner
open FsMcp.Core
open FsMcp.Core.Validation
open FsMcp.Server
open System.Text.Json
open System.Text.Json.Nodes
open System.Reflection
open System.Text.RegularExpressions
// ─── CLI helpers ───────────────────────────────────────────────────────────────
let private readPositiveIntEnv (name: string) (defaultValue: int) =
match Environment.GetEnvironmentVariable(name) with
| null -> defaultValue
| value ->
match Int32.TryParse(value) with
| true, parsed when parsed > 0 -> parsed
| _ -> defaultValue
let private timeoutFromEnv (name: string) (defaultMilliseconds: int) =
TimeSpan.FromMilliseconds(float (readPositiveIntEnv name defaultMilliseconds))
let private runProcess (fileName: string) (args: string list) =
let result =
ProcessRunner.run
fileName
args
(timeoutFromEnv "FSLANGMCP_BOOTSTRAP_TIMEOUT_MS" 300_000)
result.ExitCode, result.StandardOutput, result.StandardError
let private parseProjInfoOutput (path: string) (exitCode: int) (stdout: string) (stderr: string) : JsonNode =
if exitCode <> 0 then
jobj [ "error", jstr $"proj-info failed (exit %d{exitCode})"; "stderr", jstr stderr ] :> JsonNode
elif String.IsNullOrWhiteSpace(stdout) then
jobj [ "error", jstr "proj-info produced no output" ] :> JsonNode
else
let token = JsonNode.Parse(stdout)
let json =
match token with
| :? JsonArray as arr when arr.Count > 0 ->
match arr.[0] with
| :? JsonObject as obj -> obj
| other ->
let kind = other.GetValueKind()
jobj [ "warning", jstr (sprintf "unexpected element type: %s" (kind.ToString())) ]
| :? JsonObject as obj -> obj
| _ -> JsonObject()
let otherOptions =
json["OtherOptions"]
|> Option.ofObj
|> Option.map (fun t -> t.Deserialize<string array>() |> Option.ofObj |> Option.defaultValue [||])
|> Option.defaultValue [||]
jobj
[ "projectPath", jstr path
"otherOptions", JsonArray(otherOptions |> Array.map jstr) :> JsonNode
"optionsCount", jint otherOptions.Length ]
:> JsonNode
let private runProjInfoAsync (path: string) : Task<JsonNode> =
task {
InstallationHealth.ensureCurrent ()
// #192: the out-of-process proj-info CLI calls the same Init.init and dies the
// same way (exit 134, unhandled), so it needs the same pre-flight the in-process
// loader got. Raising lets Tools.toolResult render the shared typed envelope.
// Walk from the path itself when it is a directory: starting at its parent
// would skip a global.json sitting inside it.
let projectDirectory =
let full = Path.GetFullPath path
if Directory.Exists full then
full
else
Path.GetDirectoryName full
do! Task.Run(fun () -> SdkPreflight.ensure [ projectDirectory ])
try
let! result =
ProcessRunner.runAsync
"proj-info"
[ "--project"; path; "--fcs"; "--serialize" ]
(timeoutFromEnv "FSLANGMCP_PROJ_INFO_TIMEOUT_MS" 120_000)
CancellationToken.None
return parseProjInfoOutput path result.ExitCode result.StandardOutput result.StandardError
with
| :? System.ComponentModel.Win32Exception
| :? IOException ->
return
raise (
FileNotFoundException
"proj-info not found on PATH. Install with: dotnet tool install -g ionide.projinfo.tool"
)
}
let internal runLimitedWithTimeoutCore
(gate: SemaphoreSlim)
(cancellationToken: CancellationToken)
(timeoutMs: int option)
(onAdmitted: unit -> unit)
(work: int option -> Task<JsonNode>)
: Task<JsonNode> =
match timeoutMs with
| Some milliseconds when milliseconds < 0 ->
Task.FromResult(
jobj
[ "status", jstr "invalid_args"
"errorKind", jstr "invalid_timeout"
"message", jstr $"timeoutMs must be non-negative; got %d{milliseconds}."
"timeoutMs", jint milliseconds ]
:> JsonNode
)
| _ ->
task {
let stopwatch = Stopwatch.StartNew()
let admissionTimeoutMs =
match timeoutMs with
| Some milliseconds -> milliseconds
| None -> Timeout.Infinite
let mutable entered = false
try
let! admitted = gate.WaitAsync(admissionTimeoutMs, cancellationToken)
if not admitted then
return
jobj
[ "status", jstr "timeout"
"errorKind", jstr "fcs_admission_timeout"
"message",
jstr $"FCS admission timed out after %d{admissionTimeoutMs} ms before protected work started."
"timeoutMs", jint admissionTimeoutMs
"retryable", jbool true ]
:> JsonNode
else
entered <- true
onAdmitted ()
// Cancellation can race with a released slot. Once protected work starts it
// owns the slot until its returned Task really completes; before that point a
// cancelled waiter must never become a late starter.
cancellationToken.ThrowIfCancellationRequested()
let remainingTimeoutMs =
match timeoutMs with
| Some milliseconds ->
let remaining = max 0L (int64 milliseconds - stopwatch.ElapsedMilliseconds)
Some(int remaining)
| None -> None
return! work remainingTimeoutMs
finally
if entered then
gate.Release() |> ignore
}
let internal runLimitedWithTimeout
(gate: SemaphoreSlim)
(cancellationToken: CancellationToken)
(timeoutMs: int option)
(work: int option -> Task<JsonNode>)
: Task<JsonNode> =
runLimitedWithTimeoutCore gate cancellationToken timeoutMs ignore work
/// Owns one admitted FCS slot while the response-producing task and any explicitly
/// retained non-cancellable workers are still active. Retention must happen before
/// the response task settles; ProjectOutline does that in the timeout/cancellation
/// catch path that observed the underlying task still running.
type internal ProtectedWorkLifetime(gate: SemaphoreSlim) =
let mutable pendingOwners = 1
let releaseOne () =
if Interlocked.Decrement(&pendingOwners) = 0 then
gate.Release() |> ignore
member _.Retain(operation: Task) =
Interlocked.Increment(&pendingOwners) |> ignore
operation.ContinueWith(
(fun (completed: Task) ->
if completed.IsFaulted then
completed.Exception |> ignore
releaseOne ()),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default
)
|> ignore
member _.CompleteResponseOwner() = releaseOne ()
let internal runLimitedWithTimeoutRetainedCore
(gate: SemaphoreSlim)
(cancellationToken: CancellationToken)
(timeoutMs: int option)
(onAdmitted: unit -> unit)
(work: int option -> (Task -> unit) -> Task<JsonNode>)
: Task<JsonNode> =
match timeoutMs with
| Some milliseconds when milliseconds < 0 ->
Task.FromResult(
jobj
[ "status", jstr "invalid_args"
"errorKind", jstr "invalid_timeout"
"message", jstr $"timeoutMs must be non-negative; got %d{milliseconds}."
"timeoutMs", jint milliseconds ]
:> JsonNode
)
| _ ->
task {
let stopwatch = Stopwatch.StartNew()
let admissionTimeoutMs = timeoutMs |> Option.defaultValue Timeout.Infinite
let mutable lifetime: ProtectedWorkLifetime option = None
try
let! admitted = gate.WaitAsync(admissionTimeoutMs, cancellationToken)
if not admitted then
return
jobj
[ "status", jstr "timeout"
"errorKind", jstr "fcs_admission_timeout"
"message",
jstr
$"FCS admission timed out after %d{admissionTimeoutMs} ms before protected work started."
"timeoutMs", jint admissionTimeoutMs
"retryable", jbool true ]
:> JsonNode
else
let admittedLifetime = ProtectedWorkLifetime(gate)
lifetime <- Some admittedLifetime
onAdmitted ()
cancellationToken.ThrowIfCancellationRequested()
let remainingTimeoutMs =
timeoutMs
|> Option.map (fun milliseconds ->
max 0L (int64 milliseconds - stopwatch.ElapsedMilliseconds) |> int)
return! work remainingTimeoutMs admittedLifetime.Retain
finally
lifetime |> Option.iter _.CompleteResponseOwner()
}
let internal runLimitedWithTimeoutRetained
(gate: SemaphoreSlim)
(cancellationToken: CancellationToken)
(timeoutMs: int option)
(work: int option -> (Task -> unit) -> Task<JsonNode>)
: Task<JsonNode> =
runLimitedWithTimeoutRetainedCore gate cancellationToken timeoutMs ignore work
/// Find-specific admission wrapper. Unlike the legacy relative-timeout helper, this
/// receives the same monotonic deadline object that the admitted find operation uses,
/// so queue wait and every later phase consume one clock. The semantic cutoff reserves
/// FindRequestDeadline.ResponseAllowanceMs for constructing a typed response.
let internal runLimitedWithFindDeadlineRetainedCore
(gate: SemaphoreSlim)
(cancellationToken: CancellationToken)
(deadline: FindRequestDeadline)
(onAdmitted: unit -> unit)
(work: FindRequestDeadline -> (Task -> unit) -> Task<JsonNode>)
: Task<JsonNode> =
task {
let mutable lifetime: ProtectedWorkLifetime option = None
let admissionTimeout () =
jobj
[ "status", jstr "timeout"
"errorKind", jstr "fcs_admission_timeout"
"message",
jstr
$"FCS admission exhausted find's end-to-end timeoutMs=%d{deadline.TimeoutMs} before protected work started."
"timeoutMs", jint deadline.TimeoutMs
"retryable", jbool true ]
:> JsonNode
try
let remaining = deadline.RemainingSemanticBudget()
if remaining <= TimeSpan.Zero then
deadline.MarkSemanticExpired()
return admissionTimeout ()
else
use admissionCancellation =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)
let admission = gate.WaitAsync(admissionCancellation.Token)
let timeout = Task.Delay(remaining, admissionCancellation.Token)
let contenders =
match deadline.SemanticExpirySignal with
| Some signal -> [| admission; timeout; signal |]
| None -> [| admission; timeout |]
let! winner = Task.WhenAny(contenders)
admissionCancellation.Cancel()
let admitted =
Object.ReferenceEquals(winner, admission)
&& admission.IsCompletedSuccessfully
&& not deadline.SemanticExpired
if not admitted then
try
do! admission
with :? OperationCanceledException ->
()
// The semaphore can complete concurrently with expiry after WhenAny
// chose the other contender. Return that raced permit explicitly.
if admission.IsCompletedSuccessfully then
gate.Release() |> ignore
cancellationToken.ThrowIfCancellationRequested()
deadline.MarkSemanticExpired()
return admissionTimeout ()
else
let admittedLifetime = ProtectedWorkLifetime(gate)
lifetime <- Some admittedLifetime
onAdmitted ()
cancellationToken.ThrowIfCancellationRequested()
if deadline.SemanticExpired then
deadline.MarkSemanticExpired()
return admissionTimeout ()
else
return! work deadline admittedLifetime.Retain
finally
lifetime |> Option.iter _.CompleteResponseOwner()
}
let internal runLimitedWithFindDeadlineRetained
(gate: SemaphoreSlim)
(cancellationToken: CancellationToken)
(deadline: FindRequestDeadline)
(work: FindRequestDeadline -> (Task -> unit) -> Task<JsonNode>)
: Task<JsonNode> =
runLimitedWithFindDeadlineRetainedCore gate cancellationToken deadline ignore work
let internal runLimited
(gate: SemaphoreSlim)
(cancellationToken: CancellationToken)
(work: unit -> Task<JsonNode>)
: Task<JsonNode> =
runLimitedWithTimeout gate cancellationToken None (fun _ -> work ())
let internal normalizeProjectOutlineAdmissionResult (timeoutMs: int) (result: JsonNode) : JsonNode =
let isAdmissionTimeout =
match result["errorKind"] with
| null -> false
| kind -> kind.GetValue<string>() = "fcs_admission_timeout"
if not isAdmissionTimeout then
result
else
let issue =
jobj
[ "phase", jstr "admission"
"status", jstr "timed_out"
"errorKind", jstr "fcs_admission_timeout"
"message", result["message"].DeepClone() ]
:> JsonNode
jobj
[ "status", jstr "unknown"
"errorKind", jstr "fcs_admission_timeout"
"message", result["message"].DeepClone()
"timeoutMs", jint timeoutMs
"retryable", jbool true
"resultSetComplete", jbool false
"coverage",
jobj
[ "complete", jbool false
"filesRequested", jint 0
"filesScanned", jint 0
"filesTimedOut", jint 0
"filesFailed", jint 0
"filesNotStarted", jint 0
"phases",
JsonArray([| jobj [ "phase", jstr "admission"; "status", jstr "timed_out" ] :> JsonNode |])
:> JsonNode
"issues", JsonArray([| issue |]) :> JsonNode
"issuesReturned", jint 1
"issuesTruncated", jbool false ]
:> JsonNode
"truncated", jbool false
"nextCursor", null
"files", JsonArray() :> JsonNode ]
:> JsonNode
type internal RuntimeToolPin =
{ PackageId: string
Version: string
Command: string }
[<RequireQualifiedAccess>]
module internal RuntimeToolManifest =
[<Literal>]
let ResourceName = "FsLangMcp.dotnet-tools.json"
let private requiredRuntimeTools =
[ "fantomas", "fantomas"
"fsautocomplete", "fsautocomplete"
"ionide.projinfo.tool", "proj-info" ]
let loadPinnedRuntimeTools () : RuntimeToolPin list =
use stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName)
if isNull stream then
invalidOp $"Embedded runtime tool manifest '{ResourceName}' was not found."
use document = JsonDocument.Parse(stream)
let root = document.RootElement
if root.GetProperty("version").GetInt32() <> 1 || not (root.GetProperty("isRoot").GetBoolean()) then
invalidOp "The embedded dotnet-tools.json must be a root version-1 tool manifest."
let tools = root.GetProperty("tools")
requiredRuntimeTools
|> List.map (fun (packageId, command) ->
let mutable entry = Unchecked.defaultof<JsonElement>
if not (tools.TryGetProperty(packageId, &entry)) then
invalidOp $"The embedded tool manifest does not pin required runtime tool '{packageId}'."
let version = entry.GetProperty("version").GetString()
if
String.IsNullOrWhiteSpace version
|| not (Regex.IsMatch(version, "^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?$"))
then
invalidOp $"Runtime tool '{packageId}' must use one exact SemVer; got '{version}'."
let commands =
entry.GetProperty("commands").EnumerateArray()
|> Seq.map _.GetString()
|> Seq.toArray
if commands <> [| command |] then
invalidOp $"Runtime tool '{packageId}' must expose exactly the '{command}' command."
if entry.GetProperty("rollForward").GetBoolean() then
invalidOp $"Runtime tool '{packageId}' must set rollForward=false."
{ PackageId = packageId
Version = version
Command = command })
let dotnetToolArgs (verb: string) (pin: RuntimeToolPin) =
[ "tool"
verb
"-g"
pin.PackageId
"--version"
pin.Version
"--allow-downgrade" ]
let globalToolsDirectory () =
let cliHome =
Environment.GetEnvironmentVariable("DOTNET_CLI_HOME")
|> Option.ofObj
|> Option.filter (String.IsNullOrWhiteSpace >> not)
|> Option.defaultWith (fun () -> Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
Path.Combine(cliHome, ".dotnet", "tools")
/// Fantomas.Client 0.9.x invokes `dotnet fantomas --daemon`. The current
/// Fantomas package exposes only a `fantomas` tool command, so a sibling
/// `dotnet-fantomas` shim is required for the dotnet driver to resolve it.
let ensureFantomasDotnetAlias () =
let directory = globalToolsDirectory ()
let extension = if OperatingSystem.IsWindows() then ".exe" else ""
let source = Path.Combine(directory, "fantomas" + extension)
let destination = Path.Combine(directory, "dotnet-fantomas" + extension)
if not (File.Exists source) then
invalidOp $"The exact Fantomas install did not create its expected shim: {source}"
let temporary = destination + $".tmp-{Guid.NewGuid():N}"
try
if OperatingSystem.IsWindows() then
File.Copy(source, temporary, true)
else
File.CreateSymbolicLink(temporary, Path.GetFileName(source)) |> ignore
File.Move(temporary, destination, true)
finally
if File.Exists temporary then
File.Delete temporary
let private ensureDotnetGlobalTool (pin: RuntimeToolPin) =
let updateCode, _, updateErr =
runProcess "dotnet" (RuntimeToolManifest.dotnetToolArgs "update" pin)
if updateCode = 0 then
Console.Error.WriteLine($"[bootstrap] updated {pin.PackageId} to exact {pin.Version}")
true
else
let installCode, _, installErr =
runProcess "dotnet" (RuntimeToolManifest.dotnetToolArgs "install" pin)
if installCode = 0 then
Console.Error.WriteLine($"[bootstrap] installed {pin.PackageId} exact {pin.Version}")
true
else
Console.Error.WriteLine($"[bootstrap] failed for {pin.PackageId} {pin.Version}")
if not (String.IsNullOrWhiteSpace(updateErr)) then
Console.Error.WriteLine(updateErr)
if not (String.IsNullOrWhiteSpace(installErr)) then
Console.Error.WriteLine(installErr)
false
let private bootstrapTools () =
try
let installed =
RuntimeToolManifest.loadPinnedRuntimeTools ()
|> List.map ensureDotnetGlobalTool
|> List.forall id
if installed then
RuntimeToolManifest.ensureFantomasDotnetAlias ()
installed
with ex ->
Console.Error.WriteLine($"[bootstrap] {ex.Message}")
false
let private applyCliOverrides (argv: string array) =
let rec loop index projectPath =
if index >= argv.Length then
Start { ProjectPath = projectPath }
else
match argv[index] with
| "--project"
| "-p" ->
if index + 1 >= argv.Length then
Fail "--project requires a value."
else
loop (index + 2) (Some argv[index + 1])
| "--fsac-command" ->
if index + 1 >= argv.Length then
Fail "--fsac-command requires a value."
else
Environment.SetEnvironmentVariable("FSAC_COMMAND", argv[index + 1])
loop (index + 2) projectPath
| "--fsac-args" ->
if index + 1 >= argv.Length then
Fail "--fsac-args requires a value."
else
Environment.SetEnvironmentVariable("FSAC_ARGS", argv[index + 1])
loop (index + 2) projectPath
| "--help"
| "-h" ->
ShowHelp
"Usage: fslangmcp [--project <path-to-fsproj|sln|slnx|directory>] [--fsac-command <cmd>] [--fsac-args \"...\"] [--bootstrap-tools] [--version]"
| "--version" -> ShowVersion
| "--bootstrap-tools" -> BootstrapTools
| unknown -> Fail $"Unknown argument: %s{unknown}"
let projectFromEnvironment =
Environment.GetEnvironmentVariable("FSA_PROJECT_PATH")
|> Option.ofObj
|> Option.filter (String.IsNullOrWhiteSpace >> not)
loop 0 projectFromEnvironment
// ─── Entry point ───────────────────────────────────────────────────────────────
/// #192 hardening. Deliberately narrow, and the split matters:
///
/// * TaskScheduler.UnobservedTaskException is genuinely log-and-survive. Marking
/// the exception observed keeps a faulted background task from becoming fatal
/// even if a host ever enables ThrowUnobservedTaskExceptions.
/// * AppDomain.CurrentDomain.UnhandledException CANNOT rescue the process on
/// .NET — by then the runtime has already decided to terminate. It only buys a
/// named cause on stderr instead of an agent seeing a bare "connection lost".
///
/// What neither covers: a dependency calling Environment.Exit/FailFast, a stack
/// overflow, or a child process dying (the actual #192 mechanism — that one is
/// handled by SdkPreflight, not here).
let private installHostFaultDiagnostics () =
TaskScheduler.UnobservedTaskException.Add(fun args ->
args.SetObserved()
Console.Error.WriteLine($"[unobserved-task] %s{args.Exception.GetBaseException().Message}"))
AppDomain.CurrentDomain.UnhandledException.Add(fun args ->
let description =
match args.ExceptionObject with
| :? exn as ex -> $"%s{ex.GetType().Name}: %s{ex.Message}\n%s{ex.StackTrace}"
| other -> $"%O{other}"
Console.Error.WriteLine($"[unhandled] terminating=%b{args.IsTerminating} %s{description}"))
let private mainCore argv =
match applyCliOverrides argv with
| BootstrapTools -> if bootstrapTools () then 0 else 1
| ShowVersion ->
Console.WriteLine(FsLangMcp.Version.current)
0
| ShowHelp message ->
Console.WriteLine(message)
0
| Fail message ->
Console.Error.WriteLine(message)
1
| Start startOptions ->
installHostFaultDiagnostics ()
let fcsBridge = new FcsBridge()
let projInfoTimeout = timeoutFromEnv "FSLANGMCP_PROJ_INFO_TIMEOUT_MS" 120_000
let projectOptionsTelemetry () : ProjectOptionsTelemetry =
{ LoadAttempts = fcsBridge.ProjectOptionsLoadCount
StaleReloads = fcsBridge.ProjectOptionsStaleReloadCount
CacheValidations = fcsBridge.ProjectOptionsCacheValidationCount
InFlight = fcsBridge.ProjectOptionsInFlightCount }
let waitForProjInfo operationName projectPath (work: Task<Result<'T, string>>) =
task {
try
return! work.WaitAsync(projInfoTimeout)
with :? TimeoutException ->
return
Error
$"%s{operationName} timed out after %d{int64 projInfoTimeout.TotalMilliseconds} ms for '%s{projectPath}'."
}
let getEvaluatedProjectSnapshot projectPath =
fcsBridge.GetEvaluatedProjectSnapshot(projectPath)
|> waitForProjInfo "MSBuild project evaluation" projectPath
let probeProjectOptions projectPath =
fcsBridge.ProbeProjectOptions(projectPath)
|> waitForProjInfo "FCS project-options probe" projectPath
let evaluatedSourceFilesProvider
(projectPath: string)
: Task<Result<string array, string>> =
task {
let! result = getEvaluatedProjectSnapshot projectPath
return
result
|> Result.map (fun snapshot ->
snapshot.Files |> List.map (fun file -> file.Path) |> List.toArray)
}
use bridge =
new FsAutoCompleteBridge(evaluatedSourceFilesProvider = evaluatedSourceFilesProvider)
use fcsGate = new SemaphoreSlim(readPositiveIntEnv "FSLANGMCP_MAX_CONCURRENT_FCS" 2)
// FSAC owns one mutable workspace. Keep the public gate fixed at one; the bridge
// also serializes internally because some FCS orchestrators call LSP directly.
use lspGate = new SemaphoreSlim(1, 1)
let setProjectAndRefresh (args: SetProjectArgs) : Task<JsonNode> =
task {
InstallationHealth.ensureCurrent ()
let! result = bridge.SetProject args
let succeeded =
match result["status"] with
| :? JsonValue as value ->
try
value.GetValue<string>() = "ok"
with _ ->
false
| _ -> false
if succeeded then
// A rejected restartLsp=false transition must not invalidate the
// still-active context. Only accepted transitions clear analysis.
fcsBridge.ClearAnalysisCaches()
// Enrich readiness.projectOptions by probing the first evaluated
// project. CLI preload and the MCP tool share this exact coordinator.
match result["result"] with
| :? JsonObject as resultObj ->
let probeTarget =
match resultObj["loadedProjects"] with
| :? JsonArray as arr when arr.Count > 0 ->
match arr[0] with
| null -> None
| node ->
let value = node.GetValue<string>()
if String.IsNullOrWhiteSpace value then None else Some value
| _ -> None
match probeTarget with
| Some path ->
let! probe = probeProjectOptions path
match resultObj["readiness"] with
| :? JsonObject as readinessObj ->
match probe with
| Ok info ->
readinessObj["projectOptions"] <- jbool true
if
FsLangMcp.Types.ReferenceResolution.looksUnrestored
info.ReferencesExisting
info.ReferencesTotal
then
readinessObj["restoreStatus"] <- jstr "unrestored"
readinessObj["restoreHint"] <-
jstr
"external references unresolved — run dotnet restore && dotnet build before using FCS tools"
| Error error ->
readinessObj["projectOptions"] <- jbool false
readinessObj["projectOptionsError"] <- jstr error
| _ -> ()
| None -> ()
match currentThreadWarning (projectOptionsTelemetry ()) with
| Some warning -> resultObj["runtimeWarning"] <- warning
| None -> ()
| _ -> ()
return result
}
match startOptions.ProjectPath with
| Some projectPath ->
let preload =
setProjectAndRefresh
{ projectPath = projectPath
workspacePath = None
restartLsp = Some true }
|> fun operation -> operation.GetAwaiter().GetResult()
let ready =
match preload["status"], preload["result"] with
| (:? JsonValue as status), (:? JsonObject as resultObj) when status.GetValue<string>() = "ok" ->
match resultObj["readiness"] with
| :? JsonObject as readiness ->
let readBool (key: string) =
match readiness[key] with
| :? JsonValue as value ->
let mutable parsed = false
value.TryGetValue(&parsed) && parsed
| _ -> false
readBool "lsp" && readBool "projectOptions"
| _ -> false
| _ -> false
if not ready then
invalidOp $"--project preload failed: {preload.ToJsonString()}"
| None -> ()
let versionResponse () : Task<JsonNode> =
Task.FromResult(
jobj
[ "status", jstr "ok"
"fslangmcpVersion", jstr FsLangMcp.Version.current
"productName", jstr FsLangMcp.Version.productName ]
:> JsonNode
)
let server =
mcpServer {
name "fsharp-fsautocomplete"
version FsLangMcp.Version.current
tool (
TypedTool.define<CompletionArgs>
"textDocument_completion"
"Raw LSP proxy to fsautocomplete textDocument/completion. Exact-position IDE primitive; requires set_project first. line/character are 0-based. Pass 'text' for unsaved content. Avoid for free-form agent flows — completion is exact-position editor IO; for symbol semantics use fcs_symbol_at_word or find(kind=position) instead."
(fun args (ct: CancellationToken) ->
toolResult (fun () -> runLimited lspGate ct (fun () -> bridge.Completion args)))
|> unwrapResult
)
tool (
TypedTool.define<CheckArgs>
"check"
"Fresh F# verdict for the active context. Bare check() returns clean|errors|unknown from an in-process type-check. For scope=snippet, snippetPosition=start|end (default end) controls compile-order placement and is echoed; end sees all project sources. trusted is fresh; fast uses cached FSAC. Project scope marks downstream consumers unchecked; workspace requires a solution or directory."
(fun args (ct: CancellationToken) ->
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
let timeoutMs = args.timeoutMs |> Option.defaultValue 60_000 |> Some
toolResult (fun () ->
runLimitedWithTimeout fcsGate ct timeoutMs (fun remainingTimeoutMs ->
let args = { args with timeoutMs = remainingTimeoutMs }
Dispatcher.CheckDispatch.run fcsBridge bridge (Dispatcher.Check args))))
|> unwrapResult
)
tool (
TypedTool.define<SetProjectArgs>
"set_project"
"Initialize or switch the FSAC/LSP project context. Required before raw LSP proxies. Accepts .fsproj, .sln, .slnx, or directory. Waits up to 30s for workspace load and clears stale FCS analysis while retaining validated MSBuild project options. Response includes loadedProjects, readiness, restart intent, and whether a running FSAC process was actually replaced."
(fun args (ct: CancellationToken) ->
toolResult (fun () ->
runLimited lspGate ct (fun () -> setProjectAndRefresh args)))
|> unwrapResult
)
tool (
TypedTool.define<ProjectHealthArgs>
"project_health"
"Fast read-only preflight for one F# project. Reports whether FsLangMCP can trust semantic tooling, project options availability, source file readability, analyzer setup, test project discovery, and current LSP readiness. projectPath is optional after set_project (falls back to the active project); pass it explicitly to inspect a different .fsproj/.sln/.slnx. Does not start/switch FSAC, run compile, or run tests."
(fun args (ct: CancellationToken) ->
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
let snapshot =
{ ProjectPath = bridge.CurrentProjectPath
WorkspaceRoot = bridge.CurrentWorkspaceRoot
LoadedProjects = bridge.LoadedProjects
SessionLive = bridge.IsSessionLive
WorkspaceReady = bridge.IsWorkspaceReady
DiagnosticsFileCount = bridge.DiagnosticsFileCount }
let evaluatedProject path =
getEvaluatedProjectSnapshot path |> Async.AwaitTask
toolResult (fun () ->
runLimited fcsGate ct (fun () ->
createReport args snapshot evaluatedProject |> Async.StartAsTask)))
|> unwrapResult
)
tool (
TypedTool.define<FSharpProjectInspectArgs>
"fsharp_project_inspect"
"Read-only .fsproj inspection for agents. Prefer over textual reads of `.fsproj` — handles MSBuild evaluation correctly. Returns project identity, compile order, package/project references, signature/implementation pairing, and shared scan filtering summary. `projectPath` is optional after `set_project`. Does not build, restore, test, or edit files."
(fun args (ct: CancellationToken) ->
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
let evaluatedProject path =
getEvaluatedProjectSnapshot path |> Async.AwaitTask
toolResult (fun () ->
runLimited fcsGate ct (fun () ->
inspectProject args evaluatedProject |> Async.StartAsTask)))
|> unwrapResult
)
tool (
TypedTool.define<FcsReferencedSymbolsArgs>
"fcs_referenced_symbols"
"Substring search across the project's referenced assemblies (NuGet + framework) by DisplayName or FullName (case-insensitive). Prefer `fcs_nuget_types` when you already know the exact assembly name; use `find` for project-local symbols. Reports assembly, kind, accessibility, isObsolete. `includeNonPublic=true` for internals. Paginated; default 200, max 1000. First call triggers ParseAndCheckProject. Details: docs/tools-detailed.md#fcs_referenced_symbols."
(fun args (ct: CancellationToken) ->
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
toolResult (fun () -> runLimited fcsGate ct (fun () -> fcsBridge.ReferencedSymbols args)))
|> unwrapResult
)
tool (
TypedTool.define<FcsSuggestOpenArgs>
"fcs_suggest_open"
"Given an unresolved symbol name (FS0039), returns ranked `open` directive candidates — project-local first, then referenced assemblies. Use when an agent sees 'X is not defined' to get the right namespace instantly. Set includeReferences=false for project-only. Caveat: openPath is empty for global-namespace symbols; doesn't deduplicate the same name across multiple assemblies."
(fun args (ct: CancellationToken) ->
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
toolResult (fun () -> runLimited fcsGate ct (fun () -> fcsBridge.SuggestOpen args)))
|> unwrapResult
)
tool (
TypedTool.define<FcsNugetTypesArgs>
"fcs_nuget_types"
"Enumerate all types in one referenced assembly. `packageId` accepts the NuGet package id OR an assembly SimpleName it ships (exact, case-insensitive, never a prefix); the two often differ, and multi-assembly packages resolve fully. Prefer `fcs_referenced_symbols` for substring search across assemblies. Entry: displayName, fullName, kind, accessibility, isObsolete. Paginated; default 500, max 2000. A miss adds `hint` + `candidatePackages`. Details: docs/tools-detailed.md#fcs_nuget_types."
(fun args (ct: CancellationToken) ->
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
toolResult (fun () -> runLimited fcsGate ct (fun () -> fcsBridge.NugetTypes args)))
|> unwrapResult
)
tool (
TypedTool.define<FcsNugetMembersArgs>
"fcs_nuget_members"
"Members of one type from a referenced assembly. packageId accepts a NuGet package id or assembly SimpleName; use fcs_nuget_types to discover names. Rows include signature and constraints, exact CLR accessibility when metadata is available, isAbstract, genericParameters, obsolete/XML docs. Protected API is included by default; includeNonPublic widens. Paginated (500 default, 2000 max); misses include routing hints. Details: docs/tools-detailed.md#fcs_nuget_members."
(fun args (ct: CancellationToken) ->
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
toolResult (fun () -> runLimited fcsGate ct (fun () -> fcsBridge.NugetMembers args)))
|> unwrapResult
)
tool (
TypedTool.define<FcsFileOutlineArgs>
"fcs_file_outline"
"Compact outline for one F# file. Start with summaryOnly=true (default): container headers and attributes, member counts, CustomOperation index, and parse/check diagnostics. Those diagnostics are a per-file signal, not a project verdict. summaryOnly=false adds signatures/accessibility/attributes; oversized output downgrades to summary. Filters locals/noise by default. Use fcs_project_outline for a project or find(kind=\"symbol\") for search."
(fun args (ct: CancellationToken) ->
toolResult (fun () -> runLimited fcsGate ct (fun () -> fcsBridge.FileOutline args)))
|> unwrapResult
)
tool (
TypedTool.define<FcsMakeInternalVisibleArgs>
"fcs_make_internal_visible"
"Drop the `private` keyword from a declaration at `(line, character)`. Returns a non-destructive workspace edit `{ status, edits, appliedPreview, originalLineText }` — does NOT write the file. Use before tests need to call internals. Returns `{ status: 'no_action', reason }` on no symbol or no recognized modifier. Supported forms and Variant B status: docs/tools-detailed.md#fcs_make_internal_visible."
(fun args (ct: CancellationToken) ->
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
toolResult (fun () -> runLimited fcsGate ct (fun () -> fcsBridge.MakeInternalVisible args)))
|> unwrapResult
)
tool (
TypedTool.define<FindToolArgs>
"find"
"F# definitions/references, field sites and member calls. query returns snippets with v2 cursors; queries (1..50) or query+countsOnly=true inventories counts in one sweep, kind=symbol/definition, no cursor. kind=field: query=Card + field=Name, or exact Card.Name without field; bare field names unsupported. Narrow scope=project + projectPath; inspect coverage, phaseTimingsMs and cache before trusting zero. 60,000 UTF-16 ceiling. For covering tests prefer fcs_tests_for_symbol."
(fun args (ct: CancellationToken) ->
// Start the one monotonic deadline at public-handler entry,
// before active-project fallback or gate admission.
let timeoutMs = args.timeoutMs |> Option.defaultValue 120_000
let deadline = FindRequestDeadline(max 0 timeoutMs)
let args =
{ args with projectPath = args.projectPath |> Option.orElse bridge.CurrentProjectPath }
toolResult (fun () ->
match FindInput.prepare args with
| Error invalid ->
deadline.BeginResponseConstruction()
Task.FromResult(deadline.GuardResponse invalid)
| Ok prepared ->
let seedArgs, request, inventoryQueries =
match prepared with
| FindInput.Sites args -> args, Dispatcher.Find args, None
| FindInput.Inventory(args, queries) -> args, Dispatcher.FindInventory(args, queries), Some queries
task {
let! result =
if timeoutMs < 0 then
runLimitedWithTimeout fcsGate ct (Some timeoutMs) (fun _ ->
Dispatcher.FindDispatch.run fcsBridge bridge request)
else
runLimitedWithFindDeadlineRetained
fcsGate
ct
deadline
(fun sharedDeadline retainUntil ->
Dispatcher.FindDispatch.runWithinDeadline
fcsBridge
bridge
sharedDeadline
ct
retainUntil
request)
let isAdmissionTimeout =
match result["errorKind"] with
| null -> false
| errorKind ->
errorKind.GetValue<string>() = "fcs_admission_timeout"
if isAdmissionTimeout then
let timeoutResponse =
if seedArgs.cursor.IsSome then
FindCursorContract.validationIncomplete
deadline
"The find deadline expired during gate admission before the continuation could be validated. Retry the same cursor with a larger timeoutMs."
else
FindDeadlineResponse.beforeDiscovery
seedArgs
deadline
"admission"
"timed_out"
"fcs_admission_timeout"