eppleton commented on code in PR #9712: URL: https://github.com/apache/netbeans/pull/9712#discussion_r4680756719
########## ide/acp.mcp/src/org/netbeans/modules/acp/mcp/McpHttpServer.java: ########## @@ -0,0 +1,343 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.netbeans.modules.acp.mcp; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.modules.acp.mcp.spi.McpToolProvider; +import org.netbeans.modules.acp.mcp.spi.McpToolRegistry; + +public final class McpHttpServer { + + private static final Logger LOG = Logger.getLogger(McpHttpServer.class.getName()); + private static final String MCP_PROTOCOL_VERSION = "2025-03-26"; + private static final String SERVER_NAME = "netbeans-ide"; + private static final int TOKEN_BYTES = 32; + private static final Set<String> ALLOWED_ORIGINS = Set.of( + "http://127.0.0.1", "http://localhost"); + + private final McpToolRegistry registry; + private final ObjectMapper mapper; + private final SecureRandom secureRandom = new SecureRandom(); + private final ConcurrentHashMap<String, Set<String>> sessionTokens = new ConcurrentHashMap<>(); + private HttpServer server; + private ExecutorService executor; + private int port; + + public McpHttpServer(McpToolRegistry registry) { + this.registry = registry; + this.mapper = new ObjectMapper(); + } + + public String createSessionToken(Set<String> enabledTools) { + byte[] tokenBytes = new byte[TOKEN_BYTES]; + secureRandom.nextBytes(tokenBytes); + String token = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes); + sessionTokens.put(token, enabledTools != null ? Set.copyOf(enabledTools) + : registry.getAllTools().stream().map(McpToolProvider.McpToolDefinition::name) + .collect(java.util.stream.Collectors.toUnmodifiableSet())); + LOG.log(Level.INFO, "MCP session created, tools: {0}", + enabledTools != null ? enabledTools : "all"); + return token; + } + + public void removeSessionToken(String token) { + if (token != null) { + sessionTokens.remove(token); + } + } + + public synchronized void start() throws IOException { + if (server != null) { + return; + } + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/mcp", new McpHandler()); + executor = Executors.newFixedThreadPool(4, r -> { + Thread t = new Thread(r, "MCP-Server-Worker"); + t.setDaemon(true); + return t; + }); + server.setExecutor(executor); + server.start(); + port = server.getAddress().getPort(); + LOG.log(Level.INFO, "MCP server started on 127.0.0.1:{0}", port); + } + + public synchronized void stop() { + if (server != null) { + server.stop(1); + server = null; + if (executor != null) { + executor.shutdown(); + try { + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + executor.shutdownNow(); + } + } catch (InterruptedException ex) { + executor.shutdownNow(); + Thread.currentThread().interrupt(); + } + executor = null; + } + port = 0; + sessionTokens.clear(); + LOG.info("MCP server stopped"); + } + } + + public synchronized int getPort() { + return port; + } + + public synchronized String getUrl() { + return "http://127.0.0.1:" + port + "/mcp"; + } + + public synchronized boolean isRunning() { + return server != null; + } + + private class McpHandler implements HttpHandler { + + @Override + public void handle(HttpExchange exchange) throws IOException { + if (!"POST".equalsIgnoreCase(exchange.getRequestMethod())) { + sendError(exchange, 405, "Method not allowed"); + return; + } + Set<String> sessionFilter = validateRequest(exchange); + if (sessionFilter == null) { + return; + } + byte[] body; + try (InputStream is = exchange.getRequestBody()) { + body = is.readAllBytes(); + } + String requestStr = new String(body, StandardCharsets.UTF_8); + LOG.log(Level.FINE, "MCP request: {0}", requestStr); + + try { + @SuppressWarnings("unchecked") + Map<String, Object> request = mapper.readValue(requestStr, Map.class); + Map<String, Object> response = handleJsonRpc(request, sessionFilter); + if (response == null) { + exchange.sendResponseHeaders(204, -1); + exchange.close(); + return; + } + sendJson(exchange, 200, response); + } catch (JsonProcessingException ex) { + sendJson(exchange, 200, errorResponse(null, -32700, "Parse error")); + } catch (Exception ex) { + LOG.log(Level.WARNING, "MCP handler error", ex); + sendJson(exchange, 200, errorResponse(null, -32603, "Internal error")); + } + } + + /** + * @return the session's enabled tools set, or {@code null} if the request was rejected + */ + private Set<String> validateRequest(HttpExchange exchange) throws IOException { + String auth = exchange.getRequestHeaders().getFirst("Authorization"); + if (auth == null || !auth.startsWith("Bearer ")) { + sendError(exchange, 401, "Unauthorized"); + return null; + } + String token = auth.substring("Bearer ".length()); + Set<String> filter = sessionTokens.get(token); + if (filter == null) { + sendError(exchange, 401, "Unauthorized"); + return null; + } + String host = exchange.getRequestHeaders().getFirst("Host"); + if (host != null) { + String hostOnly = host.contains(":") ? host.substring(0, host.indexOf(':')) : host; + if (!"127.0.0.1".equals(hostOnly) && !"localhost".equals(hostOnly)) { + LOG.log(Level.WARNING, "MCP request rejected: unexpected Host header: {0}", host); + sendError(exchange, 403, "Forbidden"); + return null; + } + } + String origin = exchange.getRequestHeaders().getFirst("Origin"); + if (origin != null) { + boolean allowed = ALLOWED_ORIGINS.stream() + .anyMatch(o -> origin.equals(o) || origin.startsWith(o + ":")); + if (!allowed) { + LOG.log(Level.WARNING, "MCP request rejected: unexpected Origin header: {0}", origin); + sendError(exchange, 403, "Forbidden"); + return null; + } + } + String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); + if (contentType == null || !contentType.startsWith("application/json")) { + sendError(exchange, 415, "Unsupported Media Type"); + return null; + } + return filter; + } + + private Map<String, Object> handleJsonRpc(Map<String, Object> request, + Set<String> sessionFilter) throws Exception { + String method = (String) request.get("method"); + Object id = request.get("id"); + @SuppressWarnings("unchecked") + Map<String, Object> params = (Map<String, Object>) request.getOrDefault("params", Map.of()); + + if (method == null) { + return errorResponse(id, -32600, "Invalid request: missing method"); + } + + LOG.log(Level.FINE, "MCP method: {0}, id: {1}", new Object[]{method, id}); + + return switch (method) { + case "initialize" -> handleInitialize(id); + case "notifications/initialized" -> null; Review Comment: In the Streamable HTTP transport (2025-03-26, the version announced in `initialize`), a POST that contains only notifications must be answered with `202 Accepted` and no body. Here `notifications/initialized` gets `204`, and every other notification (e.g. `notifications/cancelled`) falls through to `default` and gets a JSON-RPC error with `id: null` and HTTP 200. A JSON-RPC server must not reply to a notification at all. Treating every message without an `id` as a notification (202, no body) would cover all cases. Related: that protocol version also allows JSON-RPC batches (arrays). These currently end up as `Parse error`, because the body is always read as a `Map`. Either support them or announce a protocol version without batching. ########## ide/acp.mcp.tools/src/org/netbeans/modules/acp/mcp/tools/GitToolProvider.java: ########## @@ -0,0 +1,316 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.netbeans.modules.acp.mcp.tools; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import org.netbeans.api.project.Project; +import org.netbeans.api.project.ui.OpenProjects; +import org.netbeans.modules.acp.mcp.spi.McpToolProvider; +import org.netbeans.modules.acp.mcp.spi.ProjectPathGuard; +import org.netbeans.modules.acp.mcp.spi.ToolResult; +import org.openide.filesystems.FileUtil; +import org.openide.util.lookup.ServiceProvider; + +@ServiceProvider(service = McpToolProvider.class) +public final class GitToolProvider implements McpToolProvider { + + private static final Logger LOG = Logger.getLogger(GitToolProvider.class.getName()); + private static final Pattern SAFE_REV = Pattern.compile("^[A-Za-z0-9._/~^:-]+$"); + + @Override + public boolean isEnabledByDefault() { + return false; + } + + @Override + public List<McpToolDefinition> getTools() { + List<McpToolDefinition> tools = new ArrayList<>(); + + tools.add(new McpToolDefinition( + "git_status", + "Show git status of the repository.", + Map.of( + "type", "object", + "properties", Map.of( + "repoDir", Map.of("type", "string", + "description", "Absolute path to the repository root. " + + "If not provided, uses the first Git repo found in open projects.") + ) + ) + )); + + tools.add(new McpToolDefinition( + "git_diff", + "Show git diff (staged, unstaged, or of a specific commit).", + Map.of( + "type", "object", + "properties", Map.of( + "repoDir", Map.of("type", "string", + "description", "Absolute path to the repository root."), + "target", Map.of("type", "string", + "description", "e.g. 'HEAD', a commit hash, or 'staged'") + ) + ) + )); + + tools.add(new McpToolDefinition( + "git_log", + "Show the commit history of the repository (hash, date, author, subject per line).", + Map.of( + "type", "object", + "properties", Map.of( + "repoDir", Map.of("type", "string", + "description", "Absolute path to the repository root."), + "maxCount", Map.of("type", "integer", + "description", "Maximum number of commits to return (default 20, max 1000)"), + "since", Map.of("type", "string", + "description", "Only commits after this date, e.g. '2026-09-01' or '2 weeks ago'") + ) + ) + )); + + tools.add(new McpToolDefinition( + "file_history", + "Show the commit history of a single file, including each version's patch.", + Map.of( + "type", "object", + "properties", Map.of( + "repoDir", Map.of("type", "string", + "description", "Absolute path to the repository root."), + "path", Map.of("type", "string", + "description", "Path to the file (absolute or relative to repo root)"), + "maxCount", Map.of("type", "integer", + "description", "Maximum number of commits to return (default 10)") + ), + "required", List.of("path") + ) + )); + + return tools; + } + + @Override + public Map<String, Object> executeTool(String name, Map<String, Object> arguments) throws Exception { + LOG.log(Level.FINE, "Executing git tool: {0}", name); + Map<String, Object> result = switch (name) { + case "git_status" -> gitStatus(arguments); + case "git_diff" -> gitDiff(arguments); + case "git_log" -> gitLog(arguments); + case "file_history" -> fileHistory(arguments); + default -> throw new IllegalArgumentException("Unknown tool: " + name); + }; + if ("error".equals(result.get("status"))) { + LOG.log(Level.WARNING, "Git tool {0} failed: {1}", new Object[]{name, result.get("message")}); + } else { + LOG.log(Level.FINE, "Git tool {0} succeeded", name); + } + return result; + } + + private Map<String, Object> gitStatus(Map<String, Object> args) throws Exception { + File repoDir = resolveRepoDir((String) args.get("repoDir")); + if (repoDir == null) { + return ToolResult.error("No git repository found in open projects"); + } + return runGit(repoDir, "git", "status", "--short"); + } + + private Map<String, Object> gitDiff(Map<String, Object> args) throws Exception { + File repoDir = resolveRepoDir((String) args.get("repoDir")); + if (repoDir == null) { + return ToolResult.error("No git repository found in open projects"); + } + String target = (String) args.get("target"); + if ("staged".equalsIgnoreCase(target)) { + return runGit(repoDir, "git", "diff", "--cached"); + } + if (target == null || target.isBlank()) { + return runGit(repoDir, "git", "diff"); + } + if (!SAFE_REV.matcher(target).matches()) { Review Comment: `SAFE_REV` allows `-` as the first character, so a `target` such as `--ext-diff` or `-O<file>` is passed to `git diff` as an option rather than as a revision. I didn't find a concrete exploit with the allowed characters (no `=`, no spaces), but rejecting a leading `-`, or passing `--end-of-options` before the revision, would make this robust against future changes to the pattern. (`file_history` already uses `--` correctly.) ########## java/acp.mcp.java/src/org/netbeans/modules/acp/mcp/java/JavaRefactoringToolProvider.java: ########## @@ -0,0 +1,499 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.netbeans.modules.acp.mcp.java; + +import com.sun.source.util.TreePath; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.Modifier; +import org.netbeans.api.java.source.CompilationController; +import org.netbeans.api.java.source.JavaSource; +import org.netbeans.api.java.source.Task; +import org.netbeans.api.java.source.TreePathHandle; +import org.netbeans.modules.acp.mcp.spi.McpToolProvider; +import org.netbeans.modules.acp.mcp.spi.ProjectPathGuard; +import org.netbeans.modules.acp.mcp.spi.ToolResult; +import org.netbeans.modules.refactoring.api.Problem; +import org.netbeans.modules.refactoring.api.RefactoringElement; +import org.netbeans.modules.refactoring.api.RefactoringSession; +import org.netbeans.modules.refactoring.api.RenameRefactoring; +import org.netbeans.modules.refactoring.api.WhereUsedQuery; +import org.netbeans.modules.refactoring.java.api.EncapsulateFieldRefactoring; +import org.netbeans.modules.refactoring.java.api.InlineRefactoring; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.util.lookup.Lookups; +import org.openide.util.lookup.ServiceProvider; + +@ServiceProvider(service = McpToolProvider.class) +public final class JavaRefactoringToolProvider implements McpToolProvider { + + private static final Logger LOG = Logger.getLogger(JavaRefactoringToolProvider.class.getName()); + + @Override + public List<McpToolDefinition> getTools() { + List<McpToolDefinition> tools = new ArrayList<>(); + + tools.add(new McpToolDefinition( + "rename_symbol", + "Rename a Java symbol (class, method, field, variable, parameter) at a given offset in a source file. " + + "Updates all references across the project.", + Map.of( + "type", "object", + "properties", Map.of( + "filePath", Map.of("type", "string", + "description", "Absolute path to the Java source file"), + "offset", Map.of("type", "integer", + "description", "Character offset of the symbol to rename (0-based)"), Review Comment: Agents generally work with line/column (that is what they see when reading a file), and computing a 0-based character offset is error-prone for them. I also suspect a mismatch on files with CRLF line endings: NetBeans editor documents and the parser work on text with `\n` line endings, while an agent that counts characters in the file on disk counts `\r\n`. I haven't tested this. Accepting `line`/`column` (1-based, like `open_pos`) and converting on the IDE side would avoid both problems. Small thing: when the path is outside an open project, `resolveJavaFile` returns `null`, and the agent gets "Java file not found" / "No Java element found" instead of the explicit outside-project error the other tools return. ########## ide/acp.mcp/nbproject/project.xml: ########## @@ -0,0 +1,99 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + +--> +<project xmlns="http://www.netbeans.org/ns/project/1"> + <type>org.netbeans.modules.apisupport.project</type> + <configuration> + <data xmlns="http://www.netbeans.org/ns/nb-module-project/3"> + <code-name-base>org.netbeans.modules.acp.mcp</code-name-base> + <module-dependencies> + <dependency> + <code-name-base>org.netbeans.modules.acp.api</code-name-base> + <build-prerequisite/> + <compile-dependency/> + <run-dependency> + <release-version>1</release-version> + <specification-version>1.0</specification-version> + </run-dependency> + </dependency> + <dependency> + <code-name-base>org.netbeans.modules.acp.mcp.spi</code-name-base> + <build-prerequisite/> + <compile-dependency/> + <run-dependency> + <specification-version>1.0</specification-version> + </run-dependency> + </dependency> + <dependency> + <code-name-base>org.netbeans.libs.acp</code-name-base> + <build-prerequisite/> + <compile-dependency/> + <run-dependency> + <specification-version>1.0</specification-version> + </run-dependency> + </dependency> + <dependency> + <code-name-base>org.netbeans.libs.jackson</code-name-base> + <build-prerequisite/> + <compile-dependency/> + <run-dependency> + <release-version>2</release-version> + <specification-version>2.34</specification-version> + </run-dependency> + </dependency> + <dependency> + <code-name-base>org.openide.modules</code-name-base> + <build-prerequisite/> + <compile-dependency/> + <run-dependency> + <specification-version>7.2</specification-version> + </run-dependency> + </dependency> + <dependency> + <code-name-base>org.openide.util</code-name-base> + <build-prerequisite/> + <compile-dependency/> + <run-dependency> + <specification-version>9.19</specification-version> + </run-dependency> + </dependency> + <dependency> + <code-name-base>org.openide.util.lookup</code-name-base> + <build-prerequisite/> + <compile-dependency/> + <run-dependency> + <specification-version>8.46</specification-version> + </run-dependency> + </dependency> + </module-dependencies> + <test-dependencies> + <test-type> + <name>unit</name> + <test-dependency><code-name-base>org.netbeans.libs.junit4</code-name-base><compile-dependency/></test-dependency> + <test-dependency><code-name-base>org.netbeans.modules.nbjunit</code-name-base><recursive/><compile-dependency/></test-dependency> + </test-type> + </test-dependencies> + <public-packages> + <package>org.netbeans.modules.acp.mcp</package> Review Comment: This exports `org.netbeans.modules.acp.mcp`, which contains only implementation classes (`McpHttpServer`, `McpServerManager`, …). `acp.api` talks to it through `AcpMcpServerProvider` in the lookup, so as far as I can see no other module needs this package. If no other module needs it, it could stay private. ########## ide/acp.mcp.tools/src/org/netbeans/modules/acp/mcp/tools/EditorToolProvider.java: ########## @@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.netbeans.modules.acp.mcp.tools; + +import java.io.File; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JEditorPane; +import javax.swing.SwingUtilities; +import javax.swing.text.Document; +import org.netbeans.modules.acp.mcp.spi.McpToolProvider; +import org.netbeans.modules.acp.mcp.spi.ProjectPathGuard; +import org.netbeans.modules.acp.mcp.spi.ToolResult; +import org.openide.cookies.EditorCookie; +import org.openide.cookies.LineCookie; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.loaders.DataObject; +import org.openide.text.Line; +import org.openide.util.lookup.ServiceProvider; +import org.openide.windows.TopComponent; + +@ServiceProvider(service = McpToolProvider.class) +public final class EditorToolProvider implements McpToolProvider { + + private static final Logger LOG = Logger.getLogger(EditorToolProvider.class.getName()); + + @Override + public List<McpToolDefinition> getTools() { + List<McpToolDefinition> tools = new ArrayList<>(); + + tools.add(new McpToolDefinition( + "get_current_file_context", + "Returns the current file path, cursor position, and any text selection from the active editor tab. " + + "Call when you see phrases like 'this file', 'highlighted text', 'selected text', 'selected code', " + + "'current file', 'current line' or similar phrases indicating current editing context.", + Map.of("type", "object", "properties", Map.of()) + )); + + tools.add(new McpToolDefinition( + "get_tabs", + "Returns a list of file paths currently open in editor tabs.", + Map.of("type", "object", "properties", Map.of()) + )); + + tools.add(new McpToolDefinition( + "open_pos", + "Opens a file at the specified line number in the editor. Only works for files within open projects. " + + "focus=false (default) opens the tab without stealing focus; " + + "focus=true activates the editor — use only when the user explicitly asks to be taken to a location.", + Map.of( + "type", "object", + "properties", Map.of( + "filePath", Map.of("type", "string", "description", "Absolute path to the file to open"), + "line", Map.of("type", "integer", "description", "Line number (1-indexed)"), + "focus", Map.of("type", "boolean", "description", "Whether to focus the editor window", "default", false) + ), + "required", List.of("filePath", "line") + ) + )); + + return tools; + } + + @Override + public Map<String, Object> executeTool(String name, Map<String, Object> arguments) throws Exception { + LOG.log(Level.FINE, "Executing editor tool: {0}", name); + Map<String, Object> result = switch (name) { + case "get_current_file_context" -> getCurrentFileContext(); + case "get_tabs" -> getTabs(); + case "open_pos" -> openPos(arguments); + default -> throw new IllegalArgumentException("Unknown tool: " + name); + }; + if ("error".equals(result.get("status"))) { + LOG.log(Level.WARNING, "Editor tool {0} failed: {1}", new Object[]{name, result.get("message")}); + } else { + LOG.log(Level.FINE, "Editor tool {0} succeeded", name); + } + return result; + } + + private Map<String, Object> getCurrentFileContext() throws Exception { + Map<String, Object>[] result = new Map[1]; + SwingUtilities.invokeAndWait(() -> { + TopComponent active = TopComponent.getRegistry().getActivated(); Review Comment: `TopComponent.getRegistry().getActivated()` returns whatever has focus. While the user is typing a question into the ACP chat window, that is `AcpChatTopComponent`, so "explain the selected code" would get "Active component is not an editor" in exactly the main use case. The UI module already uses `EditorRegistry.lastFocusedComponent()` for this (`AcpAskAgentAction`, `AcpAskAgentOutputAction`), which would be the consistent choice here too. Also, unlike `get_tabs` and `open_pos`, this tool does not apply `ProjectPathGuard`. The path and the selected text of a file outside any open project are returned to the agent. ########## ide/acp.mcp.tools/src/org/netbeans/modules/acp/mcp/tools/RefactoringToolProvider.java: ########## @@ -0,0 +1,551 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.netbeans.modules.acp.mcp.tools; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.modules.acp.mcp.spi.McpToolProvider; +import org.netbeans.modules.acp.mcp.spi.ProjectPathGuard; +import org.netbeans.modules.acp.mcp.spi.ToolResult; +import org.netbeans.modules.refactoring.api.AbstractRefactoring; +import org.netbeans.modules.refactoring.api.SingleCopyRefactoring; +import org.netbeans.modules.refactoring.api.MoveRefactoring; +import org.netbeans.modules.refactoring.api.Problem; +import org.netbeans.modules.refactoring.api.RefactoringElement; +import org.netbeans.modules.refactoring.api.RefactoringSession; +import org.netbeans.modules.refactoring.api.RenameRefactoring; +import org.netbeans.modules.refactoring.api.SafeDeleteRefactoring; +import org.netbeans.modules.refactoring.api.WhereUsedQuery; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.util.Lookup; +import org.openide.util.lookup.Lookups; +import org.openide.util.lookup.ServiceProvider; + +@ServiceProvider(service = McpToolProvider.class) +public final class RefactoringToolProvider implements McpToolProvider { + + private static final Logger LOG = Logger.getLogger(RefactoringToolProvider.class.getName()); + + @Override + public List<McpToolDefinition> getTools() { + List<McpToolDefinition> tools = new ArrayList<>(); + + tools.add(new McpToolDefinition( + "rename_file", + "Rename a file, class, or package. For Java files, this performs a full refactoring: " + + "renaming the class and updating all references across the project. " + + "For other files, it renames the file.", + Map.of( + "type", "object", + "properties", Map.of( + "filePath", Map.of("type", "string", + "description", "Absolute path to the file or directory to rename"), + "newName", Map.of("type", "string", + "description", "New name (without path or extension, e.g. 'MyNewClass')"), + "searchInComments", Map.of("type", "boolean", + "description", "Also rename occurrences in comments and strings (default false)") + ), + "required", List.of("filePath", "newName") + ) + )); + + tools.add(new McpToolDefinition( + "move_refactor", + "Move a file or class to a different directory/package. For Java files, this updates " + + "all references (imports, fully qualified names) across the project.", + Map.of( + "type", "object", + "properties", Map.of( + "filePath", Map.of("type", "string", + "description", "Absolute path to the file to move"), + "targetDirectory", Map.of("type", "string", + "description", "Absolute path to the target directory") + ), + "required", List.of("filePath", "targetDirectory") + ) + )); + + tools.add(new McpToolDefinition( + "safe_delete_file", + "Safely delete a file or class after checking for usages. If usages are found, " + + "the operation reports them instead of deleting. " + + "For Java files, checks references across the project.", + Map.of( + "type", "object", + "properties", Map.of( + "filePath", Map.of("type", "string", + "description", "Absolute path to the file to delete"), + "checkInComments", Map.of("type", "boolean", + "description", "Also check for usages in comments (default false)") + ), + "required", List.of("filePath") + ) + )); + + tools.add(new McpToolDefinition( + "find_file_usages", + "Find all usages/references of a file or class across the project. " + + "Returns a list of files and locations where the element is referenced.", + Map.of( + "type", "object", + "properties", Map.of( + "filePath", Map.of("type", "string", + "description", "Absolute path to the file to find usages of"), + "searchInComments", Map.of("type", "boolean", + "description", "Also search in comments and strings (default false)") + ), + "required", List.of("filePath") + ) + )); + + tools.add(new McpToolDefinition( + "copy_class", + "Copy a file or class to a new name and/or directory. For Java files, this updates " + + "the class name, package declaration, and import statements in the copy.", + Map.of( + "type", "object", + "properties", Map.of( + "filePath", Map.of("type", "string", + "description", "Absolute path to the file to copy"), + "newName", Map.of("type", "string", + "description", "New name for the copy (without extension, e.g. 'MyNewClass')"), + "targetDirectory", Map.of("type", "string", + "description", "Absolute path to the target directory (defaults to same directory)") + ), + "required", List.of("filePath", "newName") + ) + )); + + return tools; + } + + @Override + public Map<String, Object> executeTool(String name, Map<String, Object> arguments) throws Exception { + LOG.log(Level.FINE, "Executing refactoring tool: {0}", name); + Map<String, Object> result = switch (name) { + case "rename_file" -> doRename(arguments); + case "move_refactor" -> doMove(arguments); + case "safe_delete_file" -> doSafeDelete(arguments); + case "find_file_usages" -> doFindUsages(arguments); + case "copy_class" -> doCopy(arguments); + default -> throw new IllegalArgumentException("Unknown tool: " + name); + }; + if ("error".equals(result.get("status"))) { + LOG.log(Level.WARNING, "Refactoring tool {0} failed: {1}", new Object[]{name, result.get("message")}); + } else { + LOG.log(Level.FINE, "Refactoring tool {0} succeeded", name); + } + return result; + } + + private Map<String, Object> doRename(Map<String, Object> args) throws Exception { + String filePath = requireString(args, "filePath"); + String newName = requireString(args, "newName"); + if (filePath == null) { + return ToolResult.error("filePath is required"); + } + if (newName == null) { + return ToolResult.error("newName is required"); + } + Map<String, Object> guardError = ProjectPathGuard.requireInOpenProject(filePath); + if (guardError != null) { + return guardError; + } + FileObject fo = resolveFileObject(filePath); + if (fo == null) { + return ToolResult.error("File not found: " + filePath); + } + + boolean searchComments = Boolean.TRUE.equals(args.get("searchInComments")); + + Lookup lkp = Lookups.singleton(fo); + RenameRefactoring refactoring = new RenameRefactoring(lkp); + refactoring.setNewName(newName); + refactoring.setSearchInComments(searchComments); + + return executeRefactoring(refactoring, + "Rename " + fo.getNameExt() + " to " + newName); + } + + private Map<String, Object> doMove(Map<String, Object> args) throws Exception { + String filePath = requireString(args, "filePath"); + String targetDir = requireString(args, "targetDirectory"); + if (filePath == null) { + return ToolResult.error("filePath is required"); + } + if (targetDir == null) { + return ToolResult.error("targetDirectory is required"); + } + Map<String, Object> guardError = ProjectPathGuard.requireInOpenProject(filePath, targetDir); + if (guardError != null) { + return guardError; + } + FileObject fo = resolveFileObject(filePath); + if (fo == null) { + return ToolResult.error("File not found: " + filePath); + } + File target = new File(targetDir); + if (!target.isDirectory()) { + return ToolResult.error("Target directory not found: " + targetDir); + } + + URL targetUrl; + try { + targetUrl = target.toURI().toURL(); + } catch (MalformedURLException ex) { + return ToolResult.error("Invalid target directory path"); + } + + Lookup lkp = Lookups.singleton(fo); + MoveRefactoring refactoring = new MoveRefactoring(lkp); + refactoring.setTarget(Lookups.singleton(targetUrl)); + + return executeRefactoring(refactoring, "Move " + fo.getNameExt()); + } + + private Map<String, Object> doSafeDelete(Map<String, Object> args) throws Exception { + String filePath = requireString(args, "filePath"); + if (filePath == null) { + return ToolResult.error("filePath is required"); + } + Map<String, Object> guardError = ProjectPathGuard.requireInOpenProject(filePath); + if (guardError != null) { + return guardError; + } + FileObject fo = resolveFileObject(filePath); + if (fo == null) { + return ToolResult.error("File not found: " + filePath); + } + + boolean checkComments = Boolean.TRUE.equals(args.get("checkInComments")); + + Lookup lkp = Lookups.singleton(fo); + SafeDeleteRefactoring refactoring = new SafeDeleteRefactoring(lkp); + refactoring.setCheckInComments(checkComments); + + Problem preCheck = refactoring.preCheck(); + String preCheckMsg = collectProblems(preCheck); + if (preCheck != null && preCheck.isFatal()) { + return ToolResult.error("Pre-check failed: " + preCheckMsg); + } + + Problem paramCheck = refactoring.checkParameters(); + String paramCheckMsg = collectProblems(paramCheck); + if (paramCheck != null && paramCheck.isFatal()) { + return ToolResult.error("Parameter check failed: " + paramCheckMsg); + } + + RefactoringSession session = RefactoringSession.create("Safe Delete " + fo.getNameExt()); + Problem prepare = refactoring.prepare(session); + String prepareMsg = collectProblems(prepare); + if (prepare != null && prepare.isFatal()) { + return ToolResult.error("Prepare failed: " + prepareMsg); + } + + Collection<RefactoringElement> elements = session.getRefactoringElements(); + File targetFile = FileUtil.toFile(fo); + String targetPath = targetFile != null ? targetFile.getAbsolutePath() : fo.getPath(); + + List<Map<String, Object>> usageDetails = new ArrayList<>(); + for (RefactoringElement elem : elements) { + FileObject parent = elem.getParentFile(); + if (parent == null) { + continue; + } + File f = FileUtil.toFile(parent); + String elemPath = f != null ? f.getAbsolutePath() : parent.getPath(); + if (elemPath.equals(targetPath)) { + continue; + } + Map<String, Object> detail = new LinkedHashMap<>(); + detail.put("file", elemPath); + detail.put("description", elem.getDisplayText().replaceAll("<[^>]+>", "")); + usageDetails.add(detail); + } + + if (!usageDetails.isEmpty()) { + return ToolResult.ok("deleted", false, + "usages", usageDetails, "usageCount", usageDetails.size()); + } + + Problem result = session.doRefactoring(true); + if (result != null && result.isFatal()) { + return ToolResult.error("Refactoring failed: " + collectProblems(result)); + } + + Map<String, Object> out = ToolResult.ok("deleted", true); + List<String> warnings = collectWarnings(preCheckMsg, paramCheckMsg, prepareMsg); + if (!warnings.isEmpty()) { + out.put("warnings", warnings); + } + return out; + } + + private Map<String, Object> doFindUsages(Map<String, Object> args) throws Exception { + String filePath = requireString(args, "filePath"); + if (filePath == null) { + return ToolResult.error("filePath is required"); + } + Map<String, Object> guardError = ProjectPathGuard.requireInOpenProject(filePath); + if (guardError != null) { + return guardError; + } + FileObject fo = resolveFileObject(filePath); + if (fo == null) { + return ToolResult.error("File not found: " + filePath); + } + + boolean searchComments = Boolean.TRUE.equals(args.get("searchInComments")); + + Lookup lkp = Lookups.singleton(fo); + WhereUsedQuery query = new WhereUsedQuery(lkp); + query.putValue(WhereUsedQuery.SEARCH_IN_COMMENTS, searchComments); + query.putValue(WhereUsedQuery.FIND_REFERENCES, true); + + Problem preCheck = query.preCheck(); + String preCheckMsg = collectProblems(preCheck); + if (preCheck != null && preCheck.isFatal()) { + return ToolResult.error("Pre-check failed: " + preCheckMsg); + } + + RefactoringSession session = RefactoringSession.create("Find Usages of " + fo.getNameExt()); + Problem prepare = query.prepare(session); + String prepareMsg = collectProblems(prepare); + if (prepare != null && prepare.isFatal()) { + return ToolResult.error("Prepare failed: " + prepareMsg); + } + + Collection<RefactoringElement> elements = session.getRefactoringElements(); + List<Map<String, Object>> usages = new ArrayList<>(); + for (RefactoringElement elem : elements) { + Map<String, Object> usage = new LinkedHashMap<>(); + FileObject parent = elem.getParentFile(); + if (parent != null) { + File f = FileUtil.toFile(parent); + usage.put("file", f != null ? f.getAbsolutePath() : parent.getPath()); + } + usage.put("text", elem.getText()); + usage.put("displayText", elem.getDisplayText() + .replaceAll("<[^>]+>", "")); + if (elem.getPosition() != null) { + try { + usage.put("startOffset", elem.getPosition().getBegin().getOffset()); + usage.put("endOffset", elem.getPosition().getEnd().getOffset()); + } catch (Exception ex) { + LOG.log(Level.FINE, "Could not get position bounds", ex); + } + } + usages.add(usage); + } + + return ToolResult.ok("usages", usages, "usageCount", usages.size()); + } + + private Map<String, Object> doCopy(Map<String, Object> args) throws Exception { + String filePath = requireString(args, "filePath"); + String newName = requireString(args, "newName"); + if (filePath == null) { + return ToolResult.error("filePath is required"); + } + if (newName == null) { + return ToolResult.error("newName is required"); + } + Map<String, Object> guardError = ProjectPathGuard.requireInOpenProject(filePath); + if (guardError != null) { + return guardError; + } + FileObject fo = resolveFileObject(filePath); + if (fo == null) { + return ToolResult.error("File not found: " + filePath); + } + + String targetDir = (String) args.get("targetDirectory"); + File target; + if (targetDir != null && !targetDir.isBlank()) { + Map<String, Object> targetGuardError = ProjectPathGuard.requireInOpenProject(targetDir); + if (targetGuardError != null) { + return targetGuardError; + } + target = new File(targetDir); + } else { + target = FileUtil.toFile(fo.getParent()); + } + if (target == null || !target.isDirectory()) { + return ToolResult.error("Target directory not found"); + } + + URL targetUrl; + try { + targetUrl = target.toURI().toURL(); + } catch (MalformedURLException ex) { + return ToolResult.error("Invalid target directory path"); + } + + Lookup lkp = Lookups.singleton(fo); + SingleCopyRefactoring refactoring = new SingleCopyRefactoring(lkp); + refactoring.setNewName(newName); + refactoring.setTarget(Lookups.singleton(targetUrl)); + + RefactoringResult rr = runRefactoring(refactoring, + "Copy " + fo.getNameExt() + " as " + newName); + if (rr.error != null) { + return rr.error; + } + + String newFilePath = new File(target, newName + "." + fo.getExt()).getAbsolutePath(); + Map<String, Object> out = ToolResult.ok("newFile", newFilePath); + if (!rr.warnings.isEmpty()) { + out.put("warnings", rr.warnings); + } + return out; + } + + /** + * Executes a refactoring through the standard preCheck/paramCheck/prepare/doRefactoring + * pipeline and returns affected files with any non-fatal warnings. + */ + private static Map<String, Object> executeRefactoring(AbstractRefactoring refactoring, + String sessionName) throws Exception { + RefactoringResult rr = runRefactoring(refactoring, sessionName); + if (rr.error != null) { + return rr.error; + } + + Map<String, Object> out = ToolResult.ok("affectedFiles", rr.affectedFiles, + "affectedCount", rr.affectedFiles.size()); + if (!rr.warnings.isEmpty()) { + out.put("warnings", rr.warnings); + } + return out; + } + + private static RefactoringResult runRefactoring(AbstractRefactoring refactoring, + String sessionName) throws Exception { + Problem preCheck = refactoring.preCheck(); + String preCheckMsg = collectProblems(preCheck); + if (preCheck != null && preCheck.isFatal()) { + return RefactoringResult.fail("Pre-check failed: " + preCheckMsg); + } + + Problem paramCheck = refactoring.checkParameters(); + String paramCheckMsg = collectProblems(paramCheck); + if (paramCheck != null && paramCheck.isFatal()) { + return RefactoringResult.fail("Parameter check failed: " + paramCheckMsg); + } + + RefactoringSession session = RefactoringSession.create(sessionName); + Problem prepare = refactoring.prepare(session); + String prepareMsg = collectProblems(prepare); + if (prepare != null && prepare.isFatal()) { + return RefactoringResult.fail("Prepare failed: " + prepareMsg); + } + + Collection<RefactoringElement> elements = session.getRefactoringElements(); + List<String> affectedFiles = collectAffectedFiles(elements); + + Problem result = session.doRefactoring(true); Review Comment: Non-fatal problems from `preCheck`, `checkParameters` and `prepare` are collected but only reported back after `doRefactoring` has already changed the files. In the IDE these are the warnings that the user sees and confirms in the refactoring dialog before anything happens. Together with `isEnabledByDefault()` being `true` for this provider (rename, move, copy, safe delete) and for the Java refactorings, an agent can change many files in the project without the user seeing a preview. Whether the agent asks first depends entirely on the agent's own permission policy. I'd suggest either making the write refactorings opt-in like the git tools, or routing them through a user confirmation (e.g. the ACP permission request the chat already has, or at least stopping on non-fatal problems and returning them instead of continuing). Minor: `executeRefactoring` is nearly identical in `JavaRefactoringToolProvider`, so a shared helper in `acp.mcp.spi` would keep both in sync. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected] For further information about the NetBeans mailing lists, visit: https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists
