-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
564 lines (484 loc) · 18.6 KB
/
Program.cs
File metadata and controls
564 lines (484 loc) · 18.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
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace CSharpLspAdapter;
/// <summary>
/// LSP adapter/proxy for csharp-ls that intercepts and handles
/// protocol methods not supported by Claude Code's LSP client.
/// </summary>
public static class Program
{
private static readonly bool DebugMode = Environment.GetEnvironmentVariable("LSP_ADAPTER_DEBUG") == "1";
private static readonly string? SolutionPath = Environment.GetEnvironmentVariable("LSP_SOLUTION_PATH");
private static readonly string LogPath = Path.Combine(Path.GetTempPath(), "csharp-lsp-adapter.log");
private static readonly object LogLock = new();
private static Process? _serverProcess;
private static readonly SemaphoreSlim ClientWriteLock = new(1, 1);
private static readonly SemaphoreSlim ServerWriteLock = new(1, 1);
public static async Task<int> Main(string[] args)
{
try
{
var csharpLsPath = FindCSharpLs();
if (csharpLsPath == null)
{
await Console.Error.WriteLineAsync("Error: csharp-ls not found. Install it with: dotnet tool install -g csharp-ls").ConfigureAwait(false);
return 1;
}
LogDebug($"=== Adapter starting ===");
LogDebug($"Log file: {LogPath}");
LogDebug($"csharp-ls path: {csharpLsPath}");
LogDebug($"Solution path: {SolutionPath ?? "(auto-detect)"}");
_serverProcess = StartServer(csharpLsPath, args);
using var cts = new CancellationTokenSource();
var clientToServer = ProcessClientMessages(_serverProcess, cts.Token);
var serverToClient = ProcessServerMessages(_serverProcess, cts.Token);
await Task.WhenAny(clientToServer, serverToClient).ConfigureAwait(false);
await cts.CancelAsync().ConfigureAwait(false);
return 0;
}
catch (Exception ex)
{
await Console.Error.WriteLineAsync($"Adapter error: {ex.Message}").ConfigureAwait(false);
return 1;
}
finally
{
if (_serverProcess is { HasExited: false })
{
_serverProcess.Kill();
}
}
}
private static string? FindCSharpLs()
{
// Check common locations
var candidates = new[]
{
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".dotnet", "tools", "csharp-ls"),
"/usr/local/bin/csharp-ls",
"/usr/bin/csharp-ls",
};
foreach (var path in candidates)
{
if (File.Exists(path))
return path;
}
// Try to find in PATH using 'which' on Unix or 'where' on Windows
try
{
var whichCommand = OperatingSystem.IsWindows() ? "where" : "which";
var psi = new ProcessStartInfo(whichCommand, "csharp-ls")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = Process.Start(psi);
if (process != null)
{
var output = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit();
if (process.ExitCode == 0 && !string.IsNullOrEmpty(output))
{
return output.Split('\n')[0].Trim();
}
}
}
catch
{
// Ignore errors from which/where
}
return null;
}
private static Process StartServer(string path, string[] args)
{
var psi = new ProcessStartInfo(path)
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
foreach (var arg in args)
{
psi.ArgumentList.Add(arg);
}
var process = Process.Start(psi)
?? throw new InvalidOperationException("Failed to start csharp-ls");
// Forward stderr
_ = Task.Run(async () =>
{
while (!process.HasExited)
{
var line = await process.StandardError.ReadLineAsync().ConfigureAwait(false);
if (line != null)
{
LogDebug($"[csharp-ls stderr] {line}");
}
}
});
return process;
}
private static async Task ProcessClientMessages(Process server, CancellationToken ct)
{
LogDebug("ProcessClientMessages started");
await using var reader = Console.OpenStandardInput();
await using var writer = server.StandardInput.BaseStream;
while (!ct.IsCancellationRequested && !server.HasExited)
{
LogDebug("Waiting for client message...");
var message = await ReadLspMessage(reader, "client", ct).ConfigureAwait(false);
if (message == null)
{
LogDebug("Client stream ended (null message)");
break;
}
// Transform client messages if needed (e.g., enable capabilities)
message = TransformClientMessage(message);
LogDebug($"Client → Server: {TruncateForLog(message)}");
// Forward to server (with lock since ProcessServerMessages also writes to server)
await WriteLspMessageWithLock(writer, message, ServerWriteLock, ct).ConfigureAwait(false);
LogDebug("Message forwarded to server");
}
LogDebug("ProcessClientMessages ended");
}
private static async Task ProcessServerMessages(Process server, CancellationToken ct)
{
LogDebug("ProcessServerMessages started");
await using var reader = server.StandardOutput.BaseStream;
await using var clientWriter = Console.OpenStandardOutput();
var serverWriter = server.StandardInput.BaseStream; // For responses back to server
while (!ct.IsCancellationRequested && !server.HasExited)
{
LogDebug("Waiting for server message...");
var message = await ReadLspMessage(reader, "server", ct).ConfigureAwait(false);
if (message == null)
{
LogDebug("Server stream ended (null message)");
break;
}
LogDebug($"Server → Client: {TruncateForLog(message)}");
// Check if this is a request we need to intercept
// Responses go BACK TO SERVER (not to client!)
if (await TryHandleServerRequest(message, serverWriter, ct).ConfigureAwait(false))
{
LogDebug("Message intercepted and handled (response sent to server)");
continue; // We handled it, don't forward
}
// Forward notifications/responses to client
await WriteLspMessageWithLock(clientWriter, message, ClientWriteLock, ct).ConfigureAwait(false);
LogDebug("Message forwarded to client");
}
LogDebug("ProcessServerMessages ended");
}
private static string TransformClientMessage(string message)
{
try
{
var json = JsonNode.Parse(message);
if (json == null) return message;
var method = json["method"]?.GetValue<string>();
// Normalize all file URIs in the message to RFC 8089 format
// This fixes Windows URI inconsistencies in Claude Code's LSP client
var modified = NormalizeUrisInNode(json);
if (method == "initialize")
{
// Enable workspace/configuration support so csharp-ls will request config
var capabilities = json["params"]?["capabilities"];
if (capabilities != null)
{
var workspace = capabilities["workspace"];
if (workspace != null)
{
workspace["configuration"] = true;
LogDebug("Modified initialize: enabled workspace.configuration=true");
}
else
{
// Create workspace object if it doesn't exist
capabilities["workspace"] = new JsonObject { ["configuration"] = true };
LogDebug("Modified initialize: created workspace with configuration=true");
}
}
return json.ToJsonString();
}
// Return modified message if URIs were normalized
if (modified)
{
return json.ToJsonString();
}
}
catch (JsonException ex)
{
LogDebug($"TransformClientMessage parse error: {ex.Message}");
}
return message;
}
/// <summary>
/// Normalizes file URIs in a JSON node to RFC 8089 compliant format.
/// Converts Windows-style URIs like "file://C:\path" to "file:///C:/path".
/// </summary>
private static bool NormalizeUrisInNode(JsonNode? node)
{
if (node == null) return false;
var modified = false;
switch (node)
{
case JsonObject obj:
var keysToProcess = obj.Select(kvp => kvp.Key).ToList();
foreach (var key in keysToProcess)
{
var value = obj[key];
// Check if this is a URI field that needs normalization
if (key == "uri" || key == "rootUri" || key == "scopeUri")
{
if (value is JsonValue jsonValue && jsonValue.TryGetValue<string>(out var uriStr))
{
var normalized = NormalizeFileUri(uriStr);
if (normalized != uriStr)
{
obj[key] = normalized;
LogDebug($"Normalized URI: {uriStr} → {normalized}");
modified = true;
}
}
}
else
{
// Recursively process nested objects/arrays
if (NormalizeUrisInNode(value))
{
modified = true;
}
}
}
break;
case JsonArray arr:
foreach (var item in arr)
{
if (NormalizeUrisInNode(item))
{
modified = true;
}
}
break;
}
return modified;
}
/// <summary>
/// Normalizes a file URI to RFC 8089 compliant format.
/// Converts "file://C:\path" or "file://C:/path" to "file:///C:/path".
/// </summary>
private static string NormalizeFileUri(string uri)
{
if (string.IsNullOrEmpty(uri)) return uri;
// Only process file:// URIs
if (!uri.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
return uri;
// Already in correct format with triple slash
if (uri.StartsWith("file:///", StringComparison.OrdinalIgnoreCase))
{
// Still need to normalize backslashes to forward slashes
var pathPart = uri.Substring(8); // After "file:///"
var normalizedPath = pathPart.Replace("\\", "/");
if (normalizedPath != pathPart)
{
return "file:///" + normalizedPath;
}
return uri;
}
// Handle file:// (only 2 slashes) - needs to become file:///
var path = uri.Substring(7); // After "file://"
// Normalize backslashes to forward slashes
path = path.Replace("\\", "/");
return "file:///" + path;
}
private static async Task<bool> TryHandleServerRequest(string message, Stream writer, CancellationToken ct)
{
try
{
var json = JsonNode.Parse(message);
if (json == null) return false;
var method = json["method"]?.GetValue<string>();
var id = json["id"];
// Only intercept requests (have id and method)
if (id == null || method == null) return false;
string? response = method switch
{
"workspace/configuration" => HandleWorkspaceConfiguration(json, id),
"client/registerCapability" => HandleRegisterCapability(id),
"window/workDoneProgress/create" => HandleWorkDoneProgressCreate(id),
_ => null
};
if (response != null)
{
LogDebug($"Intercepted {method}, responding: {response}");
await WriteLspMessageWithLock(writer, response, ServerWriteLock, ct).ConfigureAwait(false);
return true;
}
}
catch (JsonException ex)
{
LogDebug($"Failed to parse message: {ex.Message}");
}
return false;
}
private static string HandleWorkspaceConfiguration(JsonNode request, JsonNode id)
{
var items = request["params"]?["items"]?.AsArray();
var results = new JsonArray();
if (items != null)
{
foreach (var item in items)
{
var section = item?["section"]?.GetValue<string>();
if (section == "csharp")
{
var config = new JsonObject();
if (!string.IsNullOrEmpty(SolutionPath))
{
config["solution"] = SolutionPath;
}
results.Add(config);
}
else
{
results.Add(new JsonObject());
}
}
}
return CreateResponse(id, results);
}
private static string HandleRegisterCapability(JsonNode id)
{
return CreateResponse(id, null);
}
private static string HandleWorkDoneProgressCreate(JsonNode id)
{
return CreateResponse(id, null);
}
private static string CreateResponse(JsonNode id, JsonNode? result)
{
var response = new JsonObject
{
["jsonrpc"] = "2.0",
["id"] = id.DeepClone()
};
if (result != null)
{
response["result"] = result;
}
else
{
response["result"] = null;
}
return response.ToJsonString();
}
private static async Task<string?> ReadLspMessage(Stream stream, string source, CancellationToken ct)
{
var headers = new Dictionary<string, string>();
var headerBuilder = new StringBuilder();
LogDebug($"[{source}] Reading headers...");
// Read headers byte by byte
while (true)
{
var buffer = new byte[1];
var bytesRead = await stream.ReadAsync(buffer, ct).ConfigureAwait(false);
if (bytesRead == 0)
{
LogDebug($"[{source}] Stream returned 0 bytes while reading headers");
return null;
}
var c = (char)buffer[0];
headerBuilder.Append(c);
// Check for end of headers (double CRLF)
if (headerBuilder.Length >= 4 &&
headerBuilder.ToString(headerBuilder.Length - 4, 4) == "\r\n\r\n")
{
break;
}
}
// Parse headers
var headerLines = headerBuilder.ToString().Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
foreach (var line in headerLines)
{
var colonIndex = line.IndexOf(':');
if (colonIndex > 0)
{
var name = line[..colonIndex].Trim();
var value = line[(colonIndex + 1)..].Trim();
headers[name] = value;
}
}
if (!headers.TryGetValue("Content-Length", out var lengthStr) ||
!int.TryParse(lengthStr, out var contentLength))
{
LogDebug($"[{source}] Missing or invalid Content-Length header");
return null;
}
LogDebug($"[{source}] Reading content ({contentLength} bytes)...");
// Read content
var contentBuffer = new byte[contentLength];
var totalRead = 0;
while (totalRead < contentLength)
{
var read = await stream.ReadAsync(contentBuffer.AsMemory(totalRead, contentLength - totalRead), ct).ConfigureAwait(false);
if (read == 0)
{
LogDebug($"[{source}] Stream ended while reading content (got {totalRead}/{contentLength} bytes)");
return null;
}
totalRead += read;
}
LogDebug($"[{source}] Message read complete");
return Encoding.UTF8.GetString(contentBuffer);
}
private static string TruncateForLog(string message)
{
const int maxLength = 500;
if (message.Length <= maxLength) return message;
return message[..maxLength] + $"... ({message.Length} bytes total)";
}
private static async Task WriteLspMessage(Stream stream, string content, CancellationToken ct)
{
var contentBytes = Encoding.UTF8.GetBytes(content);
var header = $"Content-Length: {contentBytes.Length}\r\n\r\n";
var headerBytes = Encoding.UTF8.GetBytes(header);
await stream.WriteAsync(headerBytes, ct).ConfigureAwait(false);
await stream.WriteAsync(contentBytes, ct).ConfigureAwait(false);
await stream.FlushAsync(ct).ConfigureAwait(false);
}
private static async Task WriteLspMessageWithLock(Stream stream, string content, SemaphoreSlim writeLock, CancellationToken ct)
{
await writeLock.WaitAsync(ct).ConfigureAwait(false);
try
{
await WriteLspMessage(stream, content, ct).ConfigureAwait(false);
}
finally
{
writeLock.Release();
}
}
private static void LogDebug(string message)
{
if (!DebugMode) return;
var timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
var logLine = $"[{timestamp}] {message}";
Console.Error.WriteLine($"[adapter] {logLine}");
lock (LogLock)
{
try
{
File.AppendAllText(LogPath, logLine + Environment.NewLine);
}
catch
{
// Ignore file write errors
}
}
}
}