-
Notifications
You must be signed in to change notification settings - Fork 265
Add LSP multiplexer to support multiple LSP toolsets #1970
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dgageot
wants to merge
1
commit into
docker:main
Choose a base branch
from
dgageot:board/multiple-lsp-7f7e9871
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+423
−2
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| package builtin | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "github.com/docker/cagent/pkg/tools" | ||
| ) | ||
|
|
||
| // LSPMultiplexer combines multiple LSP backends into a single toolset. | ||
| // It presents one set of lsp_* tools and routes each call to the appropriate | ||
| // backend based on the file extension in the tool arguments. | ||
| type LSPMultiplexer struct { | ||
| backends []LSPBackend | ||
| } | ||
|
|
||
| // LSPBackend pairs a raw LSPTool (used for file-type routing) with an | ||
| // optionally-wrapped ToolSet (used for tool enumeration, so that per-toolset | ||
| // config like tool filters, instructions, or toon wrappers are respected). | ||
| type LSPBackend struct { | ||
| LSP *LSPTool | ||
| Toolset tools.ToolSet | ||
| } | ||
|
|
||
| // lspRouteTarget pairs a backend with the tool handler it produced for a given tool name. | ||
| type lspRouteTarget struct { | ||
| lsp *LSPTool | ||
| handler tools.ToolHandler | ||
| } | ||
|
|
||
| // Verify interface compliance. | ||
| var ( | ||
| _ tools.ToolSet = (*LSPMultiplexer)(nil) | ||
| _ tools.Startable = (*LSPMultiplexer)(nil) | ||
| _ tools.Instructable = (*LSPMultiplexer)(nil) | ||
| ) | ||
|
|
||
| // NewLSPMultiplexer creates a multiplexer that routes LSP tool calls | ||
| // to the appropriate backend based on file type. | ||
| func NewLSPMultiplexer(backends []LSPBackend) *LSPMultiplexer { | ||
| return &LSPMultiplexer{backends: append([]LSPBackend{}, backends...)} | ||
| } | ||
|
|
||
| func (m *LSPMultiplexer) Start(ctx context.Context) error { | ||
| var started int | ||
| for _, b := range m.backends { | ||
| if err := b.LSP.Start(ctx); err != nil { | ||
| // Clean up previously started backends to avoid resource leaks. | ||
| for _, s := range m.backends[:started] { | ||
| _ = s.LSP.Stop(ctx) | ||
| } | ||
| return fmt.Errorf("starting LSP backend %q: %w", b.LSP.handler.command, err) | ||
| } | ||
| started++ | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (m *LSPMultiplexer) Stop(ctx context.Context) error { | ||
| var errs []error | ||
| for _, b := range m.backends { | ||
| if err := b.LSP.Stop(ctx); err != nil { | ||
| errs = append(errs, fmt.Errorf("stopping LSP backend %q: %w", b.LSP.handler.command, err)) | ||
| } | ||
| } | ||
| return errors.Join(errs...) | ||
| } | ||
|
|
||
| func (m *LSPMultiplexer) Instructions() string { | ||
| // Combine instructions from all backends, deduplicating identical ones. | ||
| // Typically they share the same base LSP instructions, but individual | ||
| // toolsets may override them via the Instruction config field. | ||
| var parts []string | ||
| seen := make(map[string]bool) | ||
| for _, b := range m.backends { | ||
| instr := tools.GetInstructions(b.Toolset) | ||
| if instr != "" && !seen[instr] { | ||
| seen[instr] = true | ||
| parts = append(parts, instr) | ||
| } | ||
| } | ||
| return strings.Join(parts, "\n\n") | ||
| } | ||
|
|
||
| func (m *LSPMultiplexer) Tools(ctx context.Context) ([]tools.Tool, error) { | ||
| // Collect each backend's tools keyed by name. We build the union of all | ||
| // tool names (not just the first backend's) so that per-backend tool | ||
| // filters don't accidentally hide tools that other backends expose. | ||
| handlersByName := make(map[string][]lspRouteTarget) | ||
| seenTools := make(map[string]tools.Tool) // first definition wins (for schema/description) | ||
| var toolOrder []string // preserve insertion order | ||
| for _, b := range m.backends { | ||
| bTools, err := b.Toolset.Tools(ctx) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("getting tools from LSP backend %q: %w", b.LSP.handler.command, err) | ||
| } | ||
| for _, t := range bTools { | ||
| handlersByName[t.Name] = append(handlersByName[t.Name], lspRouteTarget{b.LSP, t.Handler}) | ||
| if _, exists := seenTools[t.Name]; !exists { | ||
| seenTools[t.Name] = t | ||
| toolOrder = append(toolOrder, t.Name) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| result := make([]tools.Tool, 0, len(toolOrder)) | ||
| for _, name := range toolOrder { | ||
| t := seenTools[name] | ||
| handlers := handlersByName[name] | ||
| if name == ToolNameLSPWorkspace || name == ToolNameLSPWorkspaceSymbols { | ||
| t.Handler = broadcastLSP(handlers) | ||
| } else { | ||
| t.Handler = routeByFile(handlers) | ||
| } | ||
| result = append(result, t) | ||
| } | ||
| return result, nil | ||
| } | ||
|
|
||
| // routeByFile returns a handler that extracts the "file" field from the JSON | ||
| // arguments and dispatches to the backend whose file-type filter matches. | ||
| func routeByFile(handlers []lspRouteTarget) tools.ToolHandler { | ||
| return func(ctx context.Context, tc tools.ToolCall) (*tools.ToolCallResult, error) { | ||
| var args struct { | ||
| File string `json:"file"` | ||
| } | ||
| if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil { | ||
| return tools.ResultError(fmt.Sprintf("failed to parse file argument: %s", err)), nil | ||
| } | ||
| if args.File == "" { | ||
| return tools.ResultError("file argument is required"), nil | ||
| } | ||
| for _, h := range handlers { | ||
| if h.lsp.HandlesFile(args.File) { | ||
dgageot marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return h.handler(ctx, tc) | ||
| } | ||
| } | ||
| return tools.ResultError(fmt.Sprintf("no LSP server configured for file: %s", args.File)), nil | ||
| } | ||
| } | ||
|
|
||
| // broadcastLSP returns a handler that calls every backend best-effort and | ||
| // merges the outputs. Individual backend failures are collected rather than | ||
| // aborting the entire operation. | ||
| func broadcastLSP(handlers []lspRouteTarget) tools.ToolHandler { | ||
| return func(ctx context.Context, tc tools.ToolCall) (*tools.ToolCallResult, error) { | ||
| var sections []string | ||
| var errs []error | ||
| for _, h := range handlers { | ||
| result, err := h.handler(ctx, tc) | ||
dgageot marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if err != nil { | ||
| errs = append(errs, fmt.Errorf("backend %s: %w", h.lsp.handler.command, err)) | ||
| continue | ||
| } | ||
| if result.IsError { | ||
| sections = append(sections, fmt.Sprintf("[LSP %s] Error: %s", h.lsp.handler.command, result.Output)) | ||
| } else if result.Output != "" { | ||
| sections = append(sections, result.Output) | ||
| } | ||
| } | ||
| if len(sections) == 0 && len(errs) > 0 { | ||
| return nil, errors.Join(errs...) | ||
| } | ||
| if len(sections) == 0 { | ||
| return tools.ResultSuccess("No results"), nil | ||
| } | ||
| return tools.ResultSuccess(strings.Join(sections, "\n---\n")), nil | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.