client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. package lsp
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "os"
  9. "os/exec"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "github.com/kujtimiihoxha/termai/internal/config"
  15. "github.com/kujtimiihoxha/termai/internal/logging"
  16. "github.com/kujtimiihoxha/termai/internal/lsp/protocol"
  17. )
  18. var logger = logging.Get()
  19. type Client struct {
  20. Cmd *exec.Cmd
  21. stdin io.WriteCloser
  22. stdout *bufio.Reader
  23. stderr io.ReadCloser
  24. // Request ID counter
  25. nextID atomic.Int32
  26. // Response handlers
  27. handlers map[int32]chan *Message
  28. handlersMu sync.RWMutex
  29. // Server request handlers
  30. serverRequestHandlers map[string]ServerRequestHandler
  31. serverHandlersMu sync.RWMutex
  32. // Notification handlers
  33. notificationHandlers map[string]NotificationHandler
  34. notificationMu sync.RWMutex
  35. // Diagnostic cache
  36. diagnostics map[protocol.DocumentUri][]protocol.Diagnostic
  37. diagnosticsMu sync.RWMutex
  38. // Files are currently opened by the LSP
  39. openFiles map[string]*OpenFileInfo
  40. openFilesMu sync.RWMutex
  41. }
  42. func NewClient(command string, args ...string) (*Client, error) {
  43. cmd := exec.Command(command, args...)
  44. // Copy env
  45. cmd.Env = os.Environ()
  46. stdin, err := cmd.StdinPipe()
  47. if err != nil {
  48. return nil, fmt.Errorf("failed to create stdin pipe: %w", err)
  49. }
  50. stdout, err := cmd.StdoutPipe()
  51. if err != nil {
  52. return nil, fmt.Errorf("failed to create stdout pipe: %w", err)
  53. }
  54. stderr, err := cmd.StderrPipe()
  55. if err != nil {
  56. return nil, fmt.Errorf("failed to create stderr pipe: %w", err)
  57. }
  58. client := &Client{
  59. Cmd: cmd,
  60. stdin: stdin,
  61. stdout: bufio.NewReader(stdout),
  62. stderr: stderr,
  63. handlers: make(map[int32]chan *Message),
  64. notificationHandlers: make(map[string]NotificationHandler),
  65. serverRequestHandlers: make(map[string]ServerRequestHandler),
  66. diagnostics: make(map[protocol.DocumentUri][]protocol.Diagnostic),
  67. openFiles: make(map[string]*OpenFileInfo),
  68. }
  69. // Start the LSP server process
  70. if err := cmd.Start(); err != nil {
  71. return nil, fmt.Errorf("failed to start LSP server: %w", err)
  72. }
  73. // Handle stderr in a separate goroutine
  74. go func() {
  75. scanner := bufio.NewScanner(stderr)
  76. for scanner.Scan() {
  77. fmt.Fprintf(os.Stderr, "LSP Server: %s\n", scanner.Text())
  78. }
  79. if err := scanner.Err(); err != nil {
  80. fmt.Fprintf(os.Stderr, "Error reading stderr: %v\n", err)
  81. }
  82. }()
  83. // Start message handling loop
  84. go client.handleMessages()
  85. return client, nil
  86. }
  87. func (c *Client) RegisterNotificationHandler(method string, handler NotificationHandler) {
  88. c.notificationMu.Lock()
  89. defer c.notificationMu.Unlock()
  90. c.notificationHandlers[method] = handler
  91. }
  92. func (c *Client) RegisterServerRequestHandler(method string, handler ServerRequestHandler) {
  93. c.serverHandlersMu.Lock()
  94. defer c.serverHandlersMu.Unlock()
  95. c.serverRequestHandlers[method] = handler
  96. }
  97. func (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
  98. initParams := &protocol.InitializeParams{
  99. WorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{
  100. WorkspaceFolders: []protocol.WorkspaceFolder{
  101. {
  102. URI: protocol.URI("file://" + workspaceDir),
  103. Name: workspaceDir,
  104. },
  105. },
  106. },
  107. XInitializeParams: protocol.XInitializeParams{
  108. ProcessID: int32(os.Getpid()),
  109. ClientInfo: &protocol.ClientInfo{
  110. Name: "mcp-language-server",
  111. Version: "0.1.0",
  112. },
  113. RootPath: workspaceDir,
  114. RootURI: protocol.DocumentUri("file://" + workspaceDir),
  115. Capabilities: protocol.ClientCapabilities{
  116. Workspace: protocol.WorkspaceClientCapabilities{
  117. Configuration: true,
  118. DidChangeConfiguration: protocol.DidChangeConfigurationClientCapabilities{
  119. DynamicRegistration: true,
  120. },
  121. DidChangeWatchedFiles: protocol.DidChangeWatchedFilesClientCapabilities{
  122. DynamicRegistration: true,
  123. RelativePatternSupport: true,
  124. },
  125. },
  126. TextDocument: protocol.TextDocumentClientCapabilities{
  127. Synchronization: &protocol.TextDocumentSyncClientCapabilities{
  128. DynamicRegistration: true,
  129. DidSave: true,
  130. },
  131. Completion: protocol.CompletionClientCapabilities{
  132. CompletionItem: protocol.ClientCompletionItemOptions{},
  133. },
  134. CodeLens: &protocol.CodeLensClientCapabilities{
  135. DynamicRegistration: true,
  136. },
  137. DocumentSymbol: protocol.DocumentSymbolClientCapabilities{},
  138. CodeAction: protocol.CodeActionClientCapabilities{
  139. CodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{
  140. CodeActionKind: protocol.ClientCodeActionKindOptions{
  141. ValueSet: []protocol.CodeActionKind{},
  142. },
  143. },
  144. },
  145. PublishDiagnostics: protocol.PublishDiagnosticsClientCapabilities{
  146. VersionSupport: true,
  147. },
  148. SemanticTokens: protocol.SemanticTokensClientCapabilities{
  149. Requests: protocol.ClientSemanticTokensRequestOptions{
  150. Range: &protocol.Or_ClientSemanticTokensRequestOptions_range{},
  151. Full: &protocol.Or_ClientSemanticTokensRequestOptions_full{},
  152. },
  153. TokenTypes: []string{},
  154. TokenModifiers: []string{},
  155. Formats: []protocol.TokenFormat{},
  156. },
  157. },
  158. Window: protocol.WindowClientCapabilities{},
  159. },
  160. InitializationOptions: map[string]any{
  161. "codelenses": map[string]bool{
  162. "generate": true,
  163. "regenerate_cgo": true,
  164. "test": true,
  165. "tidy": true,
  166. "upgrade_dependency": true,
  167. "vendor": true,
  168. "vulncheck": false,
  169. },
  170. },
  171. },
  172. }
  173. var result protocol.InitializeResult
  174. if err := c.Call(ctx, "initialize", initParams, &result); err != nil {
  175. return nil, fmt.Errorf("initialize failed: %w", err)
  176. }
  177. if err := c.Notify(ctx, "initialized", struct{}{}); err != nil {
  178. return nil, fmt.Errorf("initialized notification failed: %w", err)
  179. }
  180. // Register handlers
  181. c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
  182. c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
  183. c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
  184. c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
  185. c.RegisterNotificationHandler("textDocument/publishDiagnostics",
  186. func(params json.RawMessage) { HandleDiagnostics(c, params) })
  187. // Notify the LSP server
  188. err := c.Initialized(ctx, protocol.InitializedParams{})
  189. if err != nil {
  190. return nil, fmt.Errorf("initialization failed: %w", err)
  191. }
  192. // LSP sepecific Initialization
  193. path := strings.ToLower(c.Cmd.Path)
  194. switch {
  195. case strings.Contains(path, "typescript-language-server"):
  196. // err := initializeTypescriptLanguageServer(ctx, c, workspaceDir)
  197. // if err != nil {
  198. // return nil, err
  199. // }
  200. }
  201. return &result, nil
  202. }
  203. func (c *Client) Close() error {
  204. // Try to close all open files first
  205. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  206. defer cancel()
  207. // Attempt to close files but continue shutdown regardless
  208. c.CloseAllFiles(ctx)
  209. // Close stdin to signal the server
  210. if err := c.stdin.Close(); err != nil {
  211. return fmt.Errorf("failed to close stdin: %w", err)
  212. }
  213. // Use a channel to handle the Wait with timeout
  214. done := make(chan error, 1)
  215. go func() {
  216. done <- c.Cmd.Wait()
  217. }()
  218. // Wait for process to exit with timeout
  219. select {
  220. case err := <-done:
  221. return err
  222. case <-time.After(2 * time.Second):
  223. // If we timeout, try to kill the process
  224. if err := c.Cmd.Process.Kill(); err != nil {
  225. return fmt.Errorf("failed to kill process: %w", err)
  226. }
  227. return fmt.Errorf("process killed after timeout")
  228. }
  229. }
  230. type ServerState int
  231. const (
  232. StateStarting ServerState = iota
  233. StateReady
  234. StateError
  235. )
  236. func (c *Client) WaitForServerReady(ctx context.Context) error {
  237. // TODO: wait for specific messages or poll workspace/symbol
  238. time.Sleep(time.Second * 1)
  239. return nil
  240. }
  241. type OpenFileInfo struct {
  242. Version int32
  243. URI protocol.DocumentUri
  244. }
  245. func (c *Client) OpenFile(ctx context.Context, filepath string) error {
  246. uri := fmt.Sprintf("file://%s", filepath)
  247. c.openFilesMu.Lock()
  248. if _, exists := c.openFiles[uri]; exists {
  249. c.openFilesMu.Unlock()
  250. return nil // Already open
  251. }
  252. c.openFilesMu.Unlock()
  253. // Skip files that do not exist or cannot be read
  254. content, err := os.ReadFile(filepath)
  255. if err != nil {
  256. return fmt.Errorf("error reading file: %w", err)
  257. }
  258. params := protocol.DidOpenTextDocumentParams{
  259. TextDocument: protocol.TextDocumentItem{
  260. URI: protocol.DocumentUri(uri),
  261. LanguageID: DetectLanguageID(uri),
  262. Version: 1,
  263. Text: string(content),
  264. },
  265. }
  266. if err := c.Notify(ctx, "textDocument/didOpen", params); err != nil {
  267. return err
  268. }
  269. c.openFilesMu.Lock()
  270. c.openFiles[uri] = &OpenFileInfo{
  271. Version: 1,
  272. URI: protocol.DocumentUri(uri),
  273. }
  274. c.openFilesMu.Unlock()
  275. return nil
  276. }
  277. func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
  278. uri := fmt.Sprintf("file://%s", filepath)
  279. content, err := os.ReadFile(filepath)
  280. if err != nil {
  281. return fmt.Errorf("error reading file: %w", err)
  282. }
  283. c.openFilesMu.Lock()
  284. fileInfo, isOpen := c.openFiles[uri]
  285. if !isOpen {
  286. c.openFilesMu.Unlock()
  287. return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
  288. }
  289. // Increment version
  290. fileInfo.Version++
  291. version := fileInfo.Version
  292. c.openFilesMu.Unlock()
  293. params := protocol.DidChangeTextDocumentParams{
  294. TextDocument: protocol.VersionedTextDocumentIdentifier{
  295. TextDocumentIdentifier: protocol.TextDocumentIdentifier{
  296. URI: protocol.DocumentUri(uri),
  297. },
  298. Version: version,
  299. },
  300. ContentChanges: []protocol.TextDocumentContentChangeEvent{
  301. {
  302. Value: protocol.TextDocumentContentChangeWholeDocument{
  303. Text: string(content),
  304. },
  305. },
  306. },
  307. }
  308. return c.Notify(ctx, "textDocument/didChange", params)
  309. }
  310. func (c *Client) CloseFile(ctx context.Context, filepath string) error {
  311. cnf := config.Get()
  312. uri := fmt.Sprintf("file://%s", filepath)
  313. c.openFilesMu.Lock()
  314. if _, exists := c.openFiles[uri]; !exists {
  315. c.openFilesMu.Unlock()
  316. return nil // Already closed
  317. }
  318. c.openFilesMu.Unlock()
  319. params := protocol.DidCloseTextDocumentParams{
  320. TextDocument: protocol.TextDocumentIdentifier{
  321. URI: protocol.DocumentUri(uri),
  322. },
  323. }
  324. if cnf.Debug {
  325. logger.Debug("Closing file", "file", filepath)
  326. }
  327. if err := c.Notify(ctx, "textDocument/didClose", params); err != nil {
  328. return err
  329. }
  330. c.openFilesMu.Lock()
  331. delete(c.openFiles, uri)
  332. c.openFilesMu.Unlock()
  333. return nil
  334. }
  335. func (c *Client) IsFileOpen(filepath string) bool {
  336. uri := fmt.Sprintf("file://%s", filepath)
  337. c.openFilesMu.RLock()
  338. defer c.openFilesMu.RUnlock()
  339. _, exists := c.openFiles[uri]
  340. return exists
  341. }
  342. // CloseAllFiles closes all currently open files
  343. func (c *Client) CloseAllFiles(ctx context.Context) {
  344. cnf := config.Get()
  345. c.openFilesMu.Lock()
  346. filesToClose := make([]string, 0, len(c.openFiles))
  347. // First collect all URIs that need to be closed
  348. for uri := range c.openFiles {
  349. // Convert URI back to file path by trimming "file://" prefix
  350. filePath := strings.TrimPrefix(uri, "file://")
  351. filesToClose = append(filesToClose, filePath)
  352. }
  353. c.openFilesMu.Unlock()
  354. // Then close them all
  355. for _, filePath := range filesToClose {
  356. err := c.CloseFile(ctx, filePath)
  357. if err != nil && cnf.Debug {
  358. logger.Warn("Error closing file", "file", filePath, "error", err)
  359. }
  360. }
  361. if cnf.Debug {
  362. logger.Debug("Closed all files", "files", filesToClose)
  363. }
  364. }
  365. func (c *Client) GetFileDiagnostics(uri protocol.DocumentUri) []protocol.Diagnostic {
  366. c.diagnosticsMu.RLock()
  367. defer c.diagnosticsMu.RUnlock()
  368. return c.diagnostics[uri]
  369. }
  370. func (c *Client) GetDiagnostics() map[protocol.DocumentUri][]protocol.Diagnostic {
  371. return c.diagnostics
  372. }