diff --git a/.gitignore b/.gitignore index e89ca093a7..e7f901c13f 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,7 @@ hs_err_pid* servers/ target/ +build/ bin/ *.log *.log.*.gz diff --git a/CLAUDE.md b/CLAUDE.md index e1af35f391..eedcd1fb54 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,9 @@ sts4/ │ └── boot-dev-pack/ # Extension pack bundling Spring Boot extensions ├── nodejs-packages/ # Shared Node.js utilities └── claude-plugins/ # Claude Code plugin (standalone LS + MCP server) - ├── spring-tools/ # Plugin source + ├── spring-tools/ # Plugin source (skills, hooks, explanations/.md playbooks) + ├── tools/ # Node.js checker + tests keeping the playbooks in sync with the LS + ├── research-notes/ # TODO_quickfixes.md: problem code → quick fix → playbook coverage table └── update-local-jars.sh # Rebuilds the standalone LS JAR for the plugin ``` @@ -92,6 +94,13 @@ cd claude-plugins ./update-local-jars.sh # Rebuild and copy the standalone LS JAR into the plugin ``` +Every diagnostic code needs a playbook `claude-plugins/spring-tools/explanations/.md` and a row in `claude-plugins/research-notes/TODO_quickfixes.md`. When adding or renaming a problem type, run from the repository root (details in `claude-plugins/spring-tools/README.md`): + +```bash +node claude-plugins/tools/check-explanations.mjs --require-all --todo --links +npm --prefix claude-plugins/tools test +``` + ## Running Tests ```bash @@ -139,6 +148,7 @@ IDE Client (VSCode/Eclipse) ←—LSP over stdio/socket—→ Java Language Serv - The full Spring Boot LS (`spring-boot-language-server`) requires JDT Language Server in the same process for Java type resolution - The standalone variant (`spring-boot-language-server-standalone`) resolves types via Maven/Gradle classpath + Jandex indexing — used by the Claude Code plugin +- In the plugin the LSP transport is disabled (`-Dlanguageserver.enabled=false`), so no document is ever "open": the `getProjectDiagnostics` MCP tool only sees what the indexers produce — Java diagnostics from `SpringIndexerJava`, config-file diagnostics (`application*`, `bootstrap*`, `*.factories`) from `SpringIndexerConfigFiles`, plus the build-file version validation ### Key Commons Modules diff --git a/README.md b/README.md index fd199add56..debf3eca70 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Depending on your development environment, you can choose between: - __Visual Studio Code:__ We provide extensions for Visual Studio Code if you prefer this lightweight editor for your development. - __Cursor:__ We provide extensions for Cursor if you prefer this lightweight editor for agentic development. -- __Claude Code:__ The Spring Tools plugin for Claude Code brings more Spring smartness to Claude. +- __AI coding agents:__ The Spring Tools Language Server agent plugin provides Spring-aware MCP tools and skills for Claude Code, GitHub Copilot CLI and Codex; OpenCode can connect to the same server over MCP. - __Spring Tools for Eclipse distribution:__ a ready-to-use distribution of the latest Eclipse Desktop IDE, prepackaged with Spring Tools and a few additional third-party extensions. Download, unpack, and start. - __Spring Tools for Eclipse extensions:__ you can install the Spring Tools for Eclipse into an existing Eclipse Desktop IDE installation and use it from there. - __Eclipse Theia:__ You can install the same extensions into Theia-based environments like gitpod. diff --git a/RELEASE.md b/RELEASE.md index f5c882e203..e3d37225df 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -105,7 +105,7 @@ publishes atomically in one shot, so verification has to happen locally | # | Step | Workflow | Key inputs | |---|------|----------|------------| -| 1 | Test locally | — manual | Run [`claude-plugins/update-local-jars.sh`](claude-plugins/update-local-jars.sh) to build the standalone LS jar from the current `headless-services` snapshot and drop it into `spring-tools/language-server/`, then exercise the plugin through the local `spring-tools-local` marketplace ([`claude-plugins/.claude-plugin/marketplace.json`](claude-plugins/.claude-plugin/marketplace.json)) | +| 1 | Test locally | — manual | Run [`claude-plugins/update-local-jars.sh`](claude-plugins/update-local-jars.sh) to build the standalone LS jar from the current `headless-services` snapshot and drop it into `spring-tools/language-server/`, then run the automated checks from the repository root — `node claude-plugins/tools/check-explanations.mjs --require-all --todo --links`, `node claude-plugins/tools/check-plugin-config.mjs`, `node --test 'claude-plugins/tools/test/*.test.mjs'` and the end-to-end `node claude-plugins/tools/smoke/mcp-smoke.mjs` (the same checks CI runs in [`claude-plugin-check.yml`](.github/workflows/claude-plugin-check.yml)), run the behavioral eval suite with a logged-in Claude Code (`cd claude-plugins/spring-tools && claude plugin eval . --no-publish`, or dispatch the `plugin-evals` job of that workflow) — and exercise the plugin through the local `spring-tools-local` marketplace ([`claude-plugins/.claude-plugin/marketplace.json`](claude-plugins/.claude-plugin/marketplace.json)) | | 2 | Release (build + publish) | [`release-standalone-ls.yml`](.github/workflows/release-standalone-ls.yml) | `dist: release` — builds the standalone LS jar, uploads it to the CDN, tags the repo `v`, and updates the release marketplace's `marketplace.json` to point at that tag | (Nightly/on-demand snapshot builds of the plugin are handled separately by diff --git a/claude-plugins/spring-tools/.gitignore b/claude-plugins/spring-tools/.gitignore index 178e8c412f..d54cee59ec 100644 --- a/claude-plugins/spring-tools/.gitignore +++ b/claude-plugins/spring-tools/.gitignore @@ -1,2 +1,4 @@ language-server/ -node_modules/ \ No newline at end of file +node_modules/ +boot-ls.log +evals/results/ diff --git a/claude-plugins/spring-tools/README.md b/claude-plugins/spring-tools/README.md index 13a5c38c25..4e5a623aa1 100644 --- a/claude-plugins/spring-tools/README.md +++ b/claude-plugins/spring-tools/README.md @@ -1,15 +1,30 @@ -# Spring Tools Language Server — Claude Code Plugin +# Spring Tools Language Server — Agent Plugin -A [Claude Code](https://code.claude.com) plugin that contributes the Spring Tools Language Server, exposing Spring Boot diagnostics, bean/request-mapping lookups, and other project insights to Claude Code via MCP tools. +An agent plugin that contributes the Spring Tools Language Server, exposing Spring Boot diagnostics, bean/request-mapping lookups and other project insights as MCP tools, skills, hooks and a review subagent. The portable [Agent Plugins 1.0](https://agent-plugins.org) package (`plugin.json`, `mcp.json`, and `skills/`) is supported by GitHub Copilot CLI and Codex. Claude Code also reads its native `.claude-plugin/` manifest and `hooks/`; Copilot has its own hook and agent adapters under `com.github.copilot/`. OpenCode can use the same language server over MCP and discovers shared skills through its Agent Skills-compatible `.agents/skills/` path. Unlike the VS Code extension, this plugin uses the **standalone** variant of the language server which operates **without** JDT Language Server. Project classpath is computed directly via Maven and Gradle tooling; type indexing uses Jandex. ## Requirements -- Java 21+ on `PATH` +- Java 21+ — found via `SPRING_TOOLS_JAVA`, then `$JAVA_HOME/bin/java`, then `java` on `PATH` (the first candidate that reports Java 21 or newer is used) - Maven or Gradle projects in your workspace +- Claude Code, GitHub Copilot CLI 1.0.83+, Codex CLI, or OpenCode -## Usage +Optional environment variables: + +| Variable | Purpose | +|---|---| +| `SPRING_TOOLS_JAVA` | Path of the `java` executable to run the language server with | +| `SPRING_TOOLS_JAVA_OPTS` | Extra JVM options, e.g. `-Xmx2g`; appended after the defaults so they take precedence | +| `SPRING_TOOLS_LS_JAR` | Run a local language server JAR instead of the downloaded one (no download happens) | +| `SPRING_TOOLS_SOURCE_DIR` | Spring Tools repository root to use for a local Maven build if downloading the language server fails | +| `SPRING_TOOLS_PROJECT_DIR` | The directory to index, overriding the workspace the agent reports (see [How it works](#how-it-works)) | +| `SPRING_TOOLS_DATA_DIR` | Persistent location for the language-server log and runtime files; the downloaded JAR is stored in a subdirectory for the current plugin version. Defaults to `~/.spring-tools/data` when the host provides no plugin-data directory | +| `SPRING_TOOLS_LS_WATCH` | Set to `false` to turn off the language server's own file watcher (see [What the language server provides](#what-the-language-server-provides)); only Claude's MCP hooks provide a synchronous change-notification fast path | +| `HTTPS_PROXY` / `NO_PROXY` | The JAR download honors the usual proxy variables (`HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`, lower-case variants; HTTP proxies with optional basic auth) | +| `MCP_TIMEOUT` | Claude Code's MCP startup timeout in ms; raise it if the language server is reported as failed on a slow machine | + +## Installation in Claude Code ### 1. Add the Marketplace @@ -60,17 +75,17 @@ claude Then, ask Claude a test query to verify the MCP integration. For example: > "Check the project diagnostics for CoffeeController.java." -Claude will wait for the language server to initialize, call the `getProjectDiagnostics` MCP tool, and summarize the exact Spring Boot warnings and quick fixes it reports. +Claude calls the `getProjectDiagnostics` MCP tool and summarizes the exact Spring Boot warnings and quick fixes it reports. Note that the MCP server is available within a few seconds, but the project itself only shows up in `getProjectList` once the language server has resolved the Maven/Gradle project model - a few seconds with a warm dependency cache, up to a couple of minutes on a cold one. The `validate` skill retries `getProjectList` while the list is still empty. ### 5. Local Testing We maintain a local marketplace configuration (`claude-plugins/.claude-plugin/marketplace.json`) to make testing the plugin directly from the source tree easy. -1. Run the update script to build the standalone language server JAR and copy it into this plugin's directory (run this from the `claude-plugins` directory): +1. Run the update script to build the standalone language server JAR and copy it into the source plugin directory for local development (run this from the `claude-plugins` directory): ```bash ./update-local-jars.sh ``` -2. Add the local `claude-plugins` directory as a marketplace (run this from the `sts4` root directory): +2. Add the local `claude-plugins` directory as a marketplace (run this from the repository root): ```bash claude plugin marketplace add ./claude-plugins ``` @@ -79,6 +94,87 @@ We maintain a local marketplace configuration (`claude-plugins/.claude-plugin/ma claude plugin install spring-tools@spring-tools-local ``` +4. Start Claude Code with the locally built JAR selected explicitly (run from the repository root): + ```bash + SPRING_TOOLS_LS_JAR="$PWD/claude-plugins/spring-tools/language-server/spring-boot-language-server-standalone-exec.jar" claude + ``` + Normal installs keep the downloaded JAR in persistent, versioned plugin data; this environment override is only for local development and avoids downloading the published JAR. + +## Codex and GitHub Copilot CLI + +The root `plugin.json` and `mcp.json` are the portable Agent Plugins package. This repository includes a Codex marketplace catalog at [`.agents/plugins/marketplace.json`](../../.agents/plugins/marketplace.json). Register the checkout once, then install the plugin: + +```bash +codex plugin marketplace add /path/to/spring-tools +codex plugin add spring-tools@spring-tools-local +``` + +Use `/plugins` in Codex to manage the installed plugin. This checkout's catalog is repo-scoped. To use it from a different project, register this checkout as a marketplace with `codex plugin marketplace add /path/to/spring-tools`. If you maintain a separate repo-scoped catalog, keep the plugin copy inside that repository and set `source.path` to its `./`-relative path. GitHub Copilot CLI can install directly from this repository's plugin subdirectory: + +```bash +copilot plugin install spring-projects/spring-tools:claude-plugins/spring-tools +``` + +Both hosts get the shared `skills/` and launch the same `launcher.js`. The host-specific `com.github.copilot/` directory supplies Copilot's agent front matter and session-start hook. Its reviewer limits tools to read/search and this plugin's MCP server. The root Agent Plugins files are also the Codex entry point, so those capabilities do not need a second copy. + +### Codex local development and explicit workspace configuration + +A source checkout can declare a release version whose JAR and checksum have not been published yet. Installing the plugin copies its files into the Codex cache; it does not build the language server or retain access to the source checkout. A checksum download returning HTTP 404 cannot be fixed by increasing the startup timeout. + +Build the local JAR first, from the Spring Tools repository root: + +```bash +./claude-plugins/update-local-jars.sh +``` + +For local development, keep the plugin enabled for its skills, disable its bundled MCP server, and configure an explicit stdio server in the Spring Boot workspace's `.codex/config.toml`. Replace the absolute paths below with your checkout and project paths: + +```toml +[plugins."spring-tools@spring-tools-local".mcp_servers.spring-tools-mcp] +enabled = false + +[mcp_servers.spring-tools-mcp] +command = "node" +args = ["/absolute/path/to/spring-tools/claude-plugins/spring-tools/launcher.js"] +cwd = "/absolute/path/to/your-spring-boot-project" +startup_timeout_sec = 120 + +[mcp_servers.spring-tools-mcp.env] +SPRING_TOOLS_LS_JAR = "/absolute/path/to/spring-tools/claude-plugins/spring-tools/language-server/spring-boot-language-server-standalone-exec.jar" +SPRING_TOOLS_PROJECT_DIR = "/absolute/path/to/your-spring-boot-project" +``` + +Use the marketplace identifier you installed if it differs from `spring-tools-local`. Restart Codex in the trusted project after saving the configuration, then check `/mcp` and ask for the project list. The launcher should log the selected project path and `Using language server JAR from SPRING_TOOLS_LS_JAR`. + +Codex supports explicit `env`, forwarded `env_vars`, and `cwd` for configured stdio servers; see the [Codex MCP documentation](https://developers.openai.com/codex/mcp/). Do not rely on exporting `SPRING_TOOLS_*` only in the parent shell: the host may filter those variables. A plugin process can also start in its cache directory without a workspace path. The launcher refuses to index that directory and requires an explicit project path when detection fails. Configure `SPRING_TOOLS_JAVA` in the server's `env` as well if Java 21+ is not on its `PATH`. + +For published releases, omit `SPRING_TOOLS_LS_JAR` to use the checksum-verified download. A source-build fallback needs `SPRING_TOOLS_SOURCE_DIR` set in the server's `env` to the Spring Tools checkout; building ahead of time avoids doing a Maven build during the MCP startup timeout. Keep the release JAR and its `.sha256` file published together at the versioned URL produced by `install.js`; do not bypass checksum verification or silently substitute a snapshot for a release. + +## OpenCode + +OpenCode does not load Agent Plugins packages directly. Its ready-to-merge MCP config is [`opencode/opencode.jsonc`](opencode/opencode.jsonc), and its read-only reviewer adapter is in [`opencode/agents/spring-reviewer.md`](opencode/agents/spring-reviewer.md). Set `SPRING_TOOLS_PLUGIN_ROOT` to the installed plugin directory, then merge the config fragment into your existing `opencode.json` or `opencode.jsonc`: + +```jsonc +"mcp": { + "spring-tools": { + "type": "local", + "command": ["node", "{env:SPRING_TOOLS_PLUGIN_ROOT}/launcher.js"], + "enabled": true, + "timeout": 120000 + } +} +``` + +OpenCode discovers skills under `.agents/skills/` and agents under `.opencode/agents/`. From the workspace root, copy the plugin's shared skills and reviewer adapter into those locations: + +```sh +mkdir -p .agents/skills .opencode/agents +cp -R "$SPRING_TOOLS_PLUGIN_ROOT/skills/." .agents/skills/ +cp "$SPRING_TOOLS_PLUGIN_ROOT/opencode/agents/spring-reviewer.md" .opencode/agents/ +``` + +Invoke the reviewer with `@spring-reviewer`; the shared `spring-review` skill is available to the primary agent too. Set `SPRING_TOOLS_PROJECT_DIR` if OpenCode's MCP process working directory is not the project to index. OpenCode relies on the language-server watcher; it cannot use Claude's MCP-tool hooks. Diagnostic playbooks live beside `launcher.js` in `explanations/` and are named in the MCP server instructions. + ## Configuring language server preferences You can customize validation severities and other language server settings on a per-project basis by placing a settings file inside the `.claude/` directory of your project. Two formats are supported and may coexist — the properties file provides the base values and the JSON file overrides them. @@ -90,7 +186,8 @@ Flat `key=value` format where each key is the full dot-separated settings path. ```properties # Category enablement toggles (AUTO / ON / OFF) boot-java.validation.java.boot2=OFF -boot-java.validation.java.boot3=ON +boot-java.validation.java.boot3=AUTO +boot-java.validation.java.boot4=ON boot-java.validation.spel.on=ON boot-java.validation.java.version-validation=OFF @@ -109,10 +206,11 @@ Nested JSON matching the VSCode `boot-java` / `spring-boot` configuration struct "validation": { "java": { "boot2": "OFF", - "boot3": "ON" + "boot3": "AUTO", + "boot4": "ON", + "version-validation": "OFF" }, - "spel": { "on": "ON" }, - "version-validation": { "on": "OFF" } + "spel": { "on": "ON" } } }, "spring-boot": { @@ -130,43 +228,160 @@ Nested JSON matching the VSCode `boot-java` / `spring-boot` configuration struct ### Available settings -**Category enablement toggles** (`boot-java.validation.*`) accept `AUTO`, `ON`, or `OFF`. +**Category enablement toggles** (`boot-java.validation.*`) accept `AUTO`, `ON`, or `OFF`. `AUTO` (the default for the `boot2`/`boot3`/`boot4` categories) applies a category only when the project's Spring Boot version matches it, `ON` forces it on for every Spring Boot project regardless of version (for example to see Boot 4 findings while still on Boot 3), and `OFF` disables it. The `spring-aot`, `spel`, `version-validation`, `data-query`, `cron` and `spring-ai` categories only support `ON`/`OFF`; the `application-properties` and `application-yaml` categories have no toggle — silence individual codes with a severity of `IGNORE` instead. **Per-problem severity overrides** (`spring-boot.ls.problem..`) accept `IGNORE`, `HINT`, `INFO`, `WARNING`, or `ERROR`. -The full list of available categories and problem codes is embedded in the language server JAR as `problem-types.json`. They are the same keys used in the VSCode extension's settings. +**Per-problem parameters** (`spring-boot.ls.problem-parameters...`) tune individual checks, for example `spring-boot.ls.problem-parameters.spring-ai.SPRING_AI_TOOL_DESCRIPTION_TOO_SHORT.minimum-length=40`; the version-validation category has a category-wide parameter `spring-boot.ls.problem-parameters.version-validation.use-project-build-file=false` (look up available versions on spring.io instead of the project's Maven repositories). + +The full list of available categories, problem codes and parameters is embedded in the language server JAR as `problem-types.json` (inside the nested `spring-boot-language-server-*.jar`). They are the same keys used in the VSCode extension's settings, so the `boot-java.*` / `spring-boot.*` entries of `vscode-extensions/vscode-spring-boot/package.json` double as a reference. -Settings are applied once at startup. You must restart the language server (and therefore Claude Code) for changes to take effect. +Settings are applied once at startup. You must restart the language server for changes to take effect: restart Claude Code, or reconnect the `spring-tools-mcp` server from the `/mcp` menu. ## What the language server provides Via MCP tools: -- **Diagnostics** — Spring-specific warnings and quick fixes (missing annotations, incorrect bean wiring, etc.), including version validation results -- **Project insight** — bean, component, and request-mapping lookups; resolved project classpath +- **Diagnostics** — Spring-specific warnings and quick fixes (missing annotations, incorrect bean wiring, etc.), including version validation results and checks of `application.properties` / `application.yml` / `META-INF/spring.factories` (unknown or deprecated properties, type mismatches, structural errors, unsupported factories keys). Config files under test resources are only included when `boot-java.scan-java-test-sources.on=true` is set (see below) +- **Project insight** — bean, component, and request-mapping lookups; logical structure and architectural change tracking; resolved project classpath; Java and Spring Boot version; release and support information for Spring projects + +Skills are available by name to Codex, Copilot CLI and OpenCode, and are namespaced as `/spring-tools:` in Claude Code. Hosts can also select them automatically when relevant: + +- **`validate`** — collects the Spring Tools diagnostics for a project and drives the fixes +- **`quickfix`** — looks up the explanation and fix instructions for a diagnostic code in `explanations/` and applies them +- **`create-spring-boot-project`** — scaffolds a new project from start.spring.io +- **`beans`** — bean definitions, injection points and usages ("where is this bean injected?", "which beans implement X?") +- **`endpoints`** — request mappings, optionally filtered by HTTP method ("which endpoints exist?") +- **`architecture`** — logical structure and stereotypes; captures a baseline and reports the structural changes since +- **`spring-versions`** — the Spring Boot version in use versus the latest releases, support windows and upcoming releases +- **`project-info`** — project list, Java version, Boot version and resolved classpath ("is this project indexed?", "which dependency provides X?") +- **`refresh`** — forces the language server to re-index the workspace from disk (or a single file) when something was missed + +Agents (`agents/`) — the plugin also ships a reviewer subagent: + +- **`spring-reviewer`** — a read-only Spring review of the current changes: it combines the `getProjectDiagnostics` results with the bean, endpoint and structure tools and reports blocking issues, recommendations and notes without editing anything. Claude Code and Copilot CLI ship dedicated reviewer agents; Codex gets the shared `spring-review` skill; OpenCode can install its reviewer adapter as described above. Invoke the Copilot agent by its file-derived ID: `copilot --agent spring-reviewer`. + +The language server keeps its index current in two ways. It **watches** the workspace directory itself and re-indexes changed Java/Kotlin/Groovy, config and build files after a short quiet period — so edits made by an external editor, a code generator or a shell command show up on their own, as do Maven/Gradle projects created after the server started (e.g. by the `create-spring-boot-project` skill). Extra roots added with `/add-dir` are not watched, and neither are edits outside the project root. Set `SPRING_TOOLS_LS_WATCH=false` to turn this off, e.g. for a huge monorepo or a workspace on a network drive; the watcher also disables itself above 20,000 directories. In addition, hooks give the server a synchronous fast path for the agent's own actions: the file-change hooks fire after `Edit`/`Write` tool calls on Java/Kotlin/Groovy source files and build/config files (`.java`, `.kt`, `.kts`, `.groovy`, `.xml`, `.properties`, `.yml`, `.yaml`, `.factories`, `.gradle`) — edits to unrelated files don't trigger them — and the workspace-refresh hook fires after shell commands that change files without going through the file tools: `git`, `rm`, `mv`, `cp`, `sed`, `patch`, `tar`, `unzip` (and `git`, `Remove-Item`, `Move-Item`, `Copy-Item`, `Expand-Archive`, `tar` in PowerShell). A session-start hook runs `install.js --if-missing` so the language server JAR is downloaded before the MCP server needs it. Claude Code reads these from `hooks/hooks.json`; Copilot CLI reads `com.github.copilot/hooks/hooks.json`, which only contains the session-start download: Copilot hooks run shell commands and have no way to call a tool of a running MCP server, so there the file watcher alone keeps the index current. + +## Troubleshooting + +- **Codex reports `connection closed: initialize response`** — inspect the MCP server stderr for the underlying launcher error. HTTP 404 for the JAR's `.sha256` means the required artifact is unavailable; use a local JAR for an unpublished checkout as described in [Codex local development](#codex-local-development-and-explicit-workspace-configuration). `No Spring Tools source checkout found` means the cached plugin cannot build a fallback without `SPRING_TOOLS_SOURCE_DIR`. An undetected workspace needs `SPRING_TOOLS_PROJECT_DIR` in the server environment. + +- **`spring-tools-mcp` shows as failed in `/mcp`** — on the very first start the ~100 MB JAR has to be downloaded; if that takes longer than Claude Code's MCP startup timeout the server is marked failed. Reconnect it from `/mcp` (the download continues/completes in the background) or start Claude Code again; raise `MCP_TIMEOUT` on slow connections. +- **`No Java 21+ runtime found`** on stderr — the launcher lists every candidate it tried with the version it found. Install a JDK 21+ and expose it via `PATH`, `JAVA_HOME` or `SPRING_TOOLS_JAVA`. +- **`getProjectList` is empty** — the Maven/Gradle model is still resolving (up to a couple of minutes on a cold dependency cache); the `validate` skill retries. Use the `project-info` skill to check it; if a project still doesn't appear (for example it lives outside the host's workspace), use the `refresh` skill. In Claude Code, the corresponding commands are `/spring-tools:project-info`, `/add-dir`, and `/spring-tools:refresh`. +- **Changes made outside the agent aren't picked up** — the watcher logs `file watcher started for ` in `boot-ls.log`; if it logs `not started` instead (too many directories, unsupported file system, `SPRING_TOOLS_LS_WATCH=false`), use the `refresh` skill after external changes. Claude Code's shortcut is `/spring-tools:refresh`. +- **Download blocked by a corporate proxy** — set `HTTPS_PROXY`; the installer only downloads from `cdn.spring.io` over HTTPS and verifies the SHA-256 published next to the JAR. If download fails and a Spring Tools source checkout is available, the installer builds the standalone server with its Maven wrapper. For an installed plugin, set `SPRING_TOOLS_SOURCE_DIR` to the repository root; otherwise download the JAR yourself and point `SPRING_TOOLS_LS_JAR` at it. +- **Logs** — `boot-ls.log` in `SPRING_TOOLS_DATA_DIR`, the host's plugin-data directory, or `~/.spring-tools/data`. + +## Explanation playbooks + +Every diagnostic the language server can report through `getProjectDiagnostics` carries a `code` (for example `JAVA_PUBLIC_BEAN_METHOD`). For each code there is one Markdown playbook `explanations/.md` that the `quickfix` skill reads before touching the user's code. A playbook has two sections: + +- `## Explanations` — what the diagnostic flags, why it matters, when the language server raises it (Spring/Boot version range, required dependency, what exactly is inspected), and a `For more details, see:` list of official documentation links. +- `## Fixes` — one or more `**Fix N: …**` blocks with prose and *Before:* / *After:* code blocks. Cross-references to other diagnostics are written as backticked codes (for example ``see `JAVA_LAMBDA_DSL` ``) and must point to an existing playbook. + +The codes come from the `*ProblemType` enums of the language server (`Boot2JavaProblemType`, `Boot3JavaProblemType`, `Boot4JavaProblemType`, `SpringAotJavaProblemType`, `SpringAiProblemType`, `SpelProblemType`, `cron/CronProblemType`, `data/jpa/queries/QueryProblemType`, `properties/reconcile/ApplicationPropertiesProblemType`, `yaml/reconcile/ApplicationYamlProblemType`) plus two codes that are not enum constants: `BOOT_VERSION_VALIDATION_CODE`, which all Spring Boot version-validation diagnostics share, and `YamlSchemaProblem`, which the YAML reconciler inherits from `commons-yaml` for malformed `<<` merge keys. Coverage is tracked in [`research-notes/TODO_quickfixes.md`](../research-notes/TODO_quickfixes.md). + +### Keeping the playbooks consistent + +`claude-plugins/tools/` contains a Node.js checker and tests (Node 20+, no dependencies) that keep the playbooks and the plugin configuration in sync with the language server. Run them from the repository root: + +```bash +# every code has a playbook, no orphan files, structure/cross-references valid, TODO table in sync +node claude-plugins/tools/check-explanations.mjs --require-all --todo + +# additionally verify that every documentation link returns HTTP 200 +node claude-plugins/tools/check-explanations.mjs --require-all --links -Via hooks (`hooks/hooks.json`), the plugin also tracks file and project changes on disk to keep its internal index up to date, and exposes a command to refresh the index manually. These hooks are gated to Java/Kotlin/Groovy source files and build/config files (`.java`, `.kt`, `.kts`, `.groovy`, `.xml`, `.properties`, `.yml`, `.yaml`, `.gradle`) — edits to unrelated files don't trigger them. The workspace-refresh hook fires only on `git` commands. +# only a subset (e.g. while writing a new playbook) +node claude-plugins/tools/check-explanations.mjs --codes JAVA_PUBLIC_BEAN_METHOD,JAVA_LAMBDA_DSL --links + +# hooks, skills and agents reference only MCP tools the language server offers, every tool is reachable +# through a skill or hook, skills grant exactly the tools they document, the eval suite mocks every tool +node claude-plugins/tools/check-plugin-config.mjs + +# tests: checker behaviour (incl. negative-control fixtures), hooks/skills/agents/manifest consistency with the MCP tools, +# installer (against a local mock CDN) and launcher (Java selection, JVM arguments, server instructions) +node --test --test-reporter=spec 'claude-plugins/tools/test/*.test.mjs' + +# end-to-end: start launcher.js over MCP stdio like Claude Code does, index a sample project, exercise the +# diagnostics/bean/endpoint/structure tools, edit files with and without notifying the server (file watcher), +# create a project after startup and verify it is discovered (needs the JAR + Java 21+) +node claude-plugins/tools/smoke/mcp-smoke.mjs +``` + +The GitHub Actions workflow `.github/workflows/claude-plugin-check.yml` runs the same checks for changes under `claude-plugins/`, the `*ProblemType` enums, the MCP tool sources and the standalone language server, validates the manifest with `claude plugin validate --strict`, and runs the smoke test against a freshly built language server. + +When a new MCP tool is added to the language server, give it a home: mention it in the skill that covers its use case (its `allowed-tools` list and body) or in `hooks/hooks.json`; `check-plugin-config.mjs` fails until every tool is reachable through a skill or hook. + +### Behavioral evals + +`evals/` holds a [`claude plugin eval`](https://code.claude.com/docs/en/plugin-evals) suite: one case per skill and for the `spring-reviewer` agent, plus a negative control (an unrelated question must not trigger any skill). Each case is a prompt phrased the way a user would type it, with graders for the result (a regex or a judged rubric) and for the path (`tool_used` on the skill and on the MCP tool it should call). The language server is not started during a run: `evals/mocks/spring-tools-mcp/` answers every MCP tool from recordings taken against the real server on the `sf7-validation` test project (`_tools.json` carries the real tool descriptions and schemas), and the `validate` and reviewer cases override `getProjectDiagnostics` with a recording that contains a `JAVA_AUTOWIRED_CONSTRUCTOR` finding. + +```bash +# runs every case three times with the plugin and three times without it, judged with your Claude Code credentials +cd claude-plugins/spring-tools && claude plugin eval . --no-publish + +# one case, one arm, one run - cheap while iterating on a skill description +claude plugin eval . --case validate-finds-spring-problems --runs 1 --ablation none + +# re-record the mocks after the language server's tools or the fixture project changed (needs the JAR + Java 21+) +node claude-plugins/tools/evals/record-mocks.mjs +``` + +Every run and every `llm` grader is a model call on your account (Claude Code 2.1.269+, logged in or `ANTHROPIC_API_KEY`). `check-plugin-config.mjs` keeps the suite consistent offline: every tool has a mock, `_tools.json` matches the server's tool list, graders reference only existing tools/skills/agents, and every skill and agent has a case. The `create-project-routes-to-skill` case checks routing only — eval runs don't grant `Bash`, so the skill can't download from start.spring.io there. + +When a new diagnostic code is added to the language server: + +1. Create `explanations/.md` following the structure above; verify every fact against the reconciler that raises the code and against the current Spring documentation, and prefer the current API (state deprecation/removal versions when showing an older one). +2. Add a row to the coverage table in `research-notes/TODO_quickfixes.md`. +3. Run the checker with `--require-all --todo --links` until it passes. ## Plugin structure ``` spring-tools/ ├── .claude-plugin/ -│ └── plugin.json # Plugin manifest (MCP server config) -├── launcher.js # Node.js script that downloads the JAR (if missing) and starts Java -├── install.js # Node.js script that downloads the JAR -├── hooks/ # Hooks that notify the language server of file/project changes -├── language-server/ # Populated by install.js on first run (gitignored) -│ └── spring-boot-language-server-standalone-exec.jar -├── skills/ # Claude Code skills +│ └── plugin.json # Claude Code manifest (metadata + MCP server config + hooks) +├── plugin.json # Agent Plugins 1.0 manifest (metadata), used by Copilot CLI and Codex +├── mcp.json # Agent Plugins 1.0 MCP server config, used by Copilot CLI and Codex +├── com.github.copilot/ # Copilot-specific extensions (client namespace of the Agent Plugins spec) +│ ├── agents/ +│ │ └── spring-reviewer.agent.md # Same agent, front matter Copilot understands +│ └── hooks/ +│ └── hooks.json # sessionStart JAR download +├── launcher.js # Node.js script that picks a Java 21+ runtime, downloads the JAR (if missing) and starts it +├── install.js # Node.js script that downloads and verifies the JAR (also run by the session-start hook) +├── hooks/ +│ └── hooks.json # Claude Code hooks: SessionStart JAR download + notifications about Claude's file/project changes +├── agents/ +│ └── spring-reviewer.md # Read-only Spring review subagent built on the MCP tools +├── skills/ # Portable shared skills (namespaced as /spring-tools: in Claude Code) │ ├── validate/ -│ └── quickfix/ -├── explanations/ # Markdown files with problem explanations and fixes +│ ├── quickfix/ +│ ├── create-spring-boot-project/ +│ ├── beans/ +│ ├── endpoints/ +│ ├── architecture/ +│ ├── spring-versions/ +│ ├── project-info/ +│ ├── refresh/ +│ └── spring-review/ # Canonical review procedure for Codex and other skill hosts +├── opencode/ # OpenCode MCP config fragment and reviewer agent adapter +├── explanations/ # One Markdown playbook per diagnostic code (explanation + fixes) +├── evals/ # Behavioral eval suite: one case per skill/agent + recorded MCP mocks (results/ is gitignored) └── README.md ``` +The manifests describe one plugin for different hosts. `install.js` stores the checksum-verified JAR in the persistent data directory, isolated under the plugin version; it does not write into the installed plugin tree. `check-plugin-config.mjs` fails if shared metadata drifts, if a reviewer adapter differs from `skills/spring-review/SKILL.md`, or if `mcp.json` stops launching `launcher.js`. Run `node claude-plugins/tools/sync-agent-adapters.mjs --write` after changing the shared review procedure to refresh Claude, Copilot and OpenCode adapters. Hooks cannot be one shared file: Claude supports MCP-tool hooks, Copilot supports command hooks, and Codex/OpenCode rely on the language-server watcher. Codex and Copilot consume the portable root `plugin.json`, `mcp.json`, and `skills/`, so those capabilities are defined once. + +The sibling directory `claude-plugins/tools/` (not part of the published plugin) holds `check-explanations.mjs`, `check-plugin-config.mjs`, `lib/plugin-config.mjs`, the `test/` suite, the `smoke/mcp-smoke.mjs` end-to-end test, the `evals/record-mocks.mjs` recorder and the `evals/run-with-copilot.mjs` runner described above. + ## How it works -Claude Code parses the MCP configuration in `plugin.json` at startup. This triggers `launcher.js`, which checks if the heavy Java JAR is downloaded. If not, it executes `install.js` to download it from Spring's CDN. Then it boots the standalone Spring Tools Language Server, instructing it to expose its MCP tools over `stdio` (the language server's own LSP socket transport is disabled, since nothing in this plugin connects to it). +The agent parses the MCP configuration of the plugin at startup (`.claude-plugin/plugin.json` in Claude Code, portable `mcp.json` in Copilot CLI and Codex, or the OpenCode fragment). This triggers `launcher.js`, which selects a Java 21+ runtime and checks if the heavy Java JAR is downloaded. If not, it downloads it from Spring's CDN (`install.js`, SHA-256 verified, written atomically; normally a session-start hook has already done this). Then it boots the standalone Spring Tools Language Server, instructing it to expose its MCP tools over `stdio` and passing server instructions that tell the agent which tools to start with and where the explanation playbooks live. + +The directory the server indexes is resolved in this order: `SPRING_TOOLS_PROJECT_DIR`, then `CLAUDE_PROJECT_DIR` (Claude Code), then the workspace Copilot records for the session in `~/.copilot/session-state//workspace.yaml`, then `PWD`, then the working directory the MCP server was started in. An invalid explicit override is an error. If none of the detected paths identifies a directory outside the plugin root, the launcher stops with configuration instructions. The chosen directory and its source are logged. The server watches that directory for changes unless `SPRING_TOOLS_LS_WATCH=false`. Logs go to `SPRING_TOOLS_DATA_DIR`, the host's plugin-data directory, or `~/.spring-tools/data`. -The launcher sets `languageserver.standalone.project-dir` to the current working directory. The standalone server uses that Spring Boot property for project discovery, settings-file loading, and file watching. Watcher behavior can be configured with `languageserver.standalone.filewatcher.enabled`, `languageserver.standalone.filewatcher.debounce-ms`, and `languageserver.standalone.filewatcher.max-directories`. +The standalone server uses the resolved project directory for project discovery, settings-file loading, and file watching. Watcher behavior can be configured with `languageserver.standalone.filewatcher.enabled`, `languageserver.standalone.filewatcher.debounce-ms`, and `languageserver.standalone.filewatcher.max-directories`. diff --git a/claude-plugins/spring-tools/commands/refresh.md b/claude-plugins/spring-tools/commands/refresh.md deleted file mode 100644 index f9b3514f2a..0000000000 --- a/claude-plugins/spring-tools/commands/refresh.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -description: Refresh the Spring Tools workspace so the language server re-indexes files on disk (use after /rewind, git checkout, external edits, etc.). -allowed-tools: - - mcp__spring-tools-mcp__refreshWorkspace ---- - -Call the `refreshWorkspace` tool on the `spring-tools-mcp` MCP server to force the Spring Tools language server to re-read project state from disk. Do not do anything else. After the tool returns, briefly confirm to the user that the Spring Tools workspace was refreshed. diff --git a/claude-plugins/spring-tools/hooks/hooks.json b/claude-plugins/spring-tools/hooks/hooks.json index 79fa3798ba..d452f1b58d 100644 --- a/claude-plugins/spring-tools/hooks/hooks.json +++ b/claude-plugins/spring-tools/hooks/hooks.json @@ -1,85 +1,240 @@ { + "description": "Downloads the language server JAR on first start and keeps the Spring Tools index in sync with files Claude edits (synchronously, before the next tool call) and after shell commands that rewrite the working tree. The language server additionally watches the workspace directory, so these hooks are the fast path, not the only path.", "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume|fork", + "hooks": [ + { + "type": "command", + "command": "node", + "args": ["${CLAUDE_PLUGIN_ROOT}/install.js", "--if-missing"], + "timeout": 900, + "statusMessage": "Spring Tools: preparing the language server" + } + ] + } + ], "PostToolUse": [ { - "matcher": "Write", + "matcher": "Edit|Write", "hooks": [ { "type": "mcp_tool", - "if": "Write(**/*.{java,kt,kts,groovy,xml,properties,yml,yaml,gradle})", + "if": "Edit(*.java)", "server": "plugin:spring-tools:spring-tools-mcp", "tool": "fileChanged", "input": { "filePath": "${tool_input.file_path}" - } - } - ] - }, - { - "matcher": "StrReplace", - "hooks": [ + }, + "timeout": 30 + }, { "type": "mcp_tool", - "if": "StrReplace(**/*.{java,kt,kts,groovy,xml,properties,yml,yaml,gradle})", + "if": "Edit(*.kt)", "server": "plugin:spring-tools:spring-tools-mcp", "tool": "fileChanged", "input": { "filePath": "${tool_input.file_path}" - } - } - ] - }, - { - "matcher": "Edit", - "hooks": [ + }, + "timeout": 30 + }, { "type": "mcp_tool", - "if": "Edit(**/*.{java,kt,kts,groovy,xml,properties,yml,yaml,gradle})", + "if": "Edit(*.kts)", "server": "plugin:spring-tools:spring-tools-mcp", "tool": "fileChanged", "input": { "filePath": "${tool_input.file_path}" - } - } - ] - }, - { - "matcher": "Replace", - "hooks": [ + }, + "timeout": 30 + }, { "type": "mcp_tool", - "if": "Replace(**/*.{java,kt,kts,groovy,xml,properties,yml,yaml,gradle})", + "if": "Edit(*.groovy)", "server": "plugin:spring-tools:spring-tools-mcp", "tool": "fileChanged", "input": { "filePath": "${tool_input.file_path}" - } - } - ] - }, - { - "matcher": "Delete", - "hooks": [ + }, + "timeout": 30 + }, { "type": "mcp_tool", - "if": "Delete(**/*.{java,kt,kts,groovy,xml,properties,yml,yaml,gradle})", + "if": "Edit(*.xml)", "server": "plugin:spring-tools:spring-tools-mcp", - "tool": "fileDeleted", + "tool": "fileChanged", "input": { "filePath": "${tool_input.file_path}" - } + }, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Edit(*.properties)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "fileChanged", + "input": { + "filePath": "${tool_input.file_path}" + }, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Edit(*.yml)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "fileChanged", + "input": { + "filePath": "${tool_input.file_path}" + }, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Edit(*.yaml)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "fileChanged", + "input": { + "filePath": "${tool_input.file_path}" + }, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Edit(*.factories)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "fileChanged", + "input": { + "filePath": "${tool_input.file_path}" + }, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Edit(*.gradle)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "fileChanged", + "input": { + "filePath": "${tool_input.file_path}" + }, + "timeout": 30 } ] }, { - "matcher": "Bash", + "matcher": "Bash|PowerShell", "hooks": [ { "type": "mcp_tool", "if": "Bash(git *)", "server": "plugin:spring-tools:spring-tools-mcp", "tool": "refreshWorkspace", - "input": {} + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Bash(rm *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Bash(mv *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Bash(cp *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Bash(sed *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Bash(patch *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Bash(tar *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "Bash(unzip *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "PowerShell(git *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "PowerShell(Remove-Item *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "PowerShell(Move-Item *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "PowerShell(Copy-Item *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "PowerShell(Expand-Archive *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 + }, + { + "type": "mcp_tool", + "if": "PowerShell(tar *)", + "server": "plugin:spring-tools:spring-tools-mcp", + "tool": "refreshWorkspace", + "input": {}, + "timeout": 30 } ] } diff --git a/claude-plugins/spring-tools/install.js b/claude-plugins/spring-tools/install.js index 349c43c963..648168ce29 100644 --- a/claude-plugins/spring-tools/install.js +++ b/claude-plugins/spring-tools/install.js @@ -1,102 +1,445 @@ +#!/usr/bin/env node +/******************************************************************************* + * Copyright (c) 2026 Broadcom + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Broadcom - initial API and implementation + *******************************************************************************/ +// Downloads the Spring Boot language server JAR matching the plugin version and verifies its +// SHA-256. Used in-process by launcher.js and as a CLI by the SessionStart hook: +// node install.js [--if-missing] [--dest ] +// Only stderr is used for logging so the launcher's stdout stays a clean MCP channel. +'use strict'; + const fs = require('fs'); const path = require('path'); +const http = require('http'); const https = require('https'); +const net = require('net'); +const tls = require('tls'); const crypto = require('crypto'); - -const pluginJsonPath = path.join(__dirname, '.claude-plugin', 'plugin.json'); -const pluginData = JSON.parse(fs.readFileSync(pluginJsonPath, 'utf8')); -const version = pluginData.version; +const os = require('os'); +const { spawnSync } = require('child_process'); +const { Transform } = require('stream'); +const { pipeline } = require('stream/promises'); const JAR_NAME = 'spring-boot-language-server-standalone-exec.jar'; -const jarDir = path.join(__dirname, 'language-server'); -const jarPath = path.join(jarDir, JAR_NAME); - -const ALLOWED_HOST = 'cdn.spring.io'; +const DEFAULT_DOWNLOAD_BASE = 'https://cdn.spring.io/spring-tools'; const MAX_REDIRECTS = 5; +const SOCKET_IDLE_TIMEOUT_MS = 60000; +const LOCK_STALE_MS = 30 * 60 * 1000; +const LOCK_WAIT_MAX_MS = 20 * 60 * 1000; +const LOCK_POLL_MS = 500; +const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']); -if (!fs.existsSync(jarDir)) { - fs.mkdirSync(jarDir, { recursive: true }); +// The Agent Plugins manifest at the plugin root is the one both clients can read; the Claude Code +// manifest in .claude-plugin/ is the fallback for older layouts. +function pluginVersion(pluginRoot) { + const manifestPath = [path.join(pluginRoot, 'plugin.json'), path.join(pluginRoot, '.claude-plugin', 'plugin.json')] + .find((candidate) => fs.existsSync(candidate)); + if (!manifestPath) { + throw new Error(`no plugin.json found in ${pluginRoot}`); + } + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + if (typeof manifest.version !== 'string' || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(manifest.version)) { + throw new Error('plugin.json has no valid version'); + } + return manifest.version; } -function get(url, redirectCount = 0) { - return new Promise((resolve, reject) => { - let parsed; - try { - parsed = new URL(url); - } catch (err) { - reject(new Error(`Invalid URL: ${url}`)); - return; - } - if (parsed.protocol !== 'https:' || parsed.hostname !== ALLOWED_HOST) { - reject(new Error(`Refusing to fetch from untrusted host: ${url}`)); - return; +function defaultInstallDir(pluginRoot = __dirname, env = process.env, home = os.homedir()) { + const dataDir = env.SPRING_TOOLS_DATA_DIR || env.CLAUDE_PLUGIN_DATA || env.PLUGIN_DATA || path.join(home, '.spring-tools', 'data'); + // Keep artifacts from different plugin releases isolated; an old JAR must never satisfy + // --if-missing after the plugin version changes. + return path.resolve(dataDir, 'language-server', pluginVersion(pluginRoot)); +} + +/** Release versions live under release//, anything with a qualifier under snapshot/. */ +function downloadUrls(version, base = process.env.SPRING_TOOLS_LS_DOWNLOAD_BASE || DEFAULT_DOWNLOAD_BASE) { + const root = base.replace(/\/+$/, ''); + const jarUrl = version.includes('-') + ? `${root}/snapshot/language-server/spring-boot/${JAR_NAME}` + : `${root}/release/language-server/spring-boot/${version}/${JAR_NAME}`; + return { jarUrl, sha256Url: `${jarUrl}.sha256` }; +} + +/** Hosts a download may come from: the CDN, plus a configured mirror. Plain HTTP only for loopback (tests). */ +function assertAllowedUrl(url, base = process.env.SPRING_TOOLS_LS_DOWNLOAD_BASE || DEFAULT_DOWNLOAD_BASE) { + let parsed; + try { + parsed = new URL(url); + } catch { + throw new Error(`Invalid URL: ${url}`); + } + const allowedHosts = new Set([new URL(DEFAULT_DOWNLOAD_BASE).hostname, new URL(base).hostname]); + if (!allowedHosts.has(parsed.hostname)) { + throw new Error(`Refusing to fetch from untrusted host: ${url}`); + } + if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))) { + throw new Error(`Refusing insecure download URL: ${url}`); + } + return parsed; +} + +function hostMatchesNoProxy(hostname, noProxy) { + if (!noProxy) { + return false; + } + return noProxy.split(',').map((e) => e.trim().toLowerCase()).filter(Boolean).some((entry) => { + if (entry === '*') { + return true; } - https.get(url, (res) => { - if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { - res.resume(); - if (redirectCount >= MAX_REDIRECTS) { - reject(new Error(`Too many redirects while fetching ${url}`)); - return; - } - resolve(get(new URL(res.headers.location, url).toString(), redirectCount + 1)); - } else if (res.statusCode === 200) { - resolve(res); - } else { - reject(new Error(`Failed to fetch ${url}: ${res.statusCode}`)); - } - }).on('error', reject); + const pattern = entry.replace(/^\./, '').replace(/:\d+$/, ''); + return hostname === pattern || hostname.endsWith(`.${pattern}`); }); } -async function fetchText(url) { - const res = await get(url); +/** Proxy URL for a target, following curl's HTTPS_PROXY/HTTP_PROXY/ALL_PROXY and NO_PROXY conventions. */ +function proxyFor(targetUrl, env = process.env) { + const target = new URL(targetUrl); + const hostname = target.hostname.toLowerCase(); + if (LOOPBACK_HOSTS.has(hostname) || hostMatchesNoProxy(hostname, env.NO_PROXY || env.no_proxy)) { + return null; + } + const candidates = target.protocol === 'https:' + ? [env.HTTPS_PROXY, env.https_proxy, env.ALL_PROXY, env.all_proxy] + : [env.HTTP_PROXY, env.http_proxy, env.ALL_PROXY, env.all_proxy]; + const proxy = candidates.find((value) => value && value.trim()); + if (!proxy) { + return null; + } + const parsed = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(proxy) ? proxy : `http://${proxy}`); + if (parsed.protocol !== 'http:') { + throw new Error(`Unsupported proxy protocol ${parsed.protocol} (only http:// proxies are supported)`); + } + return parsed; +} + +function proxyAuthHeader(proxy) { + if (!proxy.username && !proxy.password) { + return null; + } + const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + return `Basic ${Buffer.from(credentials).toString('base64')}`; +} + +/** Opens a CONNECT tunnel through an HTTP proxy and wraps it in TLS for the target host. */ +function connectThroughProxy(proxy, target) { return new Promise((resolve, reject) => { - let data = ''; - res.on('data', chunk => data += chunk); - res.on('end', () => resolve(data.trim())); - res.on('error', reject); + const port = target.port || 443; + const socket = net.connect({ host: proxy.hostname, port: Number(proxy.port) || 80 }); + socket.setTimeout(SOCKET_IDLE_TIMEOUT_MS, () => { + socket.destroy(new Error(`Timed out connecting to proxy ${proxy.host}`)); + }); + socket.once('error', reject); + socket.once('connect', () => { + const auth = proxyAuthHeader(proxy); + socket.write(`CONNECT ${target.hostname}:${port} HTTP/1.1\r\nHost: ${target.hostname}:${port}\r\n` + + (auth ? `Proxy-Authorization: ${auth}\r\n` : '') + 'Connection: keep-alive\r\n\r\n'); + }); + let response = ''; + const onData = (chunk) => { + response += chunk.toString('latin1'); + const end = response.indexOf('\r\n\r\n'); + if (end === -1) { + return; + } + socket.removeListener('data', onData); + const statusLine = response.slice(0, response.indexOf('\r\n')); + if (!/^HTTP\/1\.[01] 200\b/.test(statusLine)) { + socket.destroy(); + reject(new Error(`Proxy ${proxy.host} refused CONNECT to ${target.hostname}:${port}: ${statusLine}`)); + return; + } + const leftover = response.slice(end + 4); + if (leftover.length) { + socket.destroy(); + reject(new Error(`Proxy ${proxy.host} sent unexpected data after the CONNECT response`)); + return; + } + socket.pause(); + const secure = tls.connect({ socket, servername: target.hostname }); + secure.once('secureConnect', () => resolve(secure)); + secure.once('error', reject); + }; + socket.on('data', onData); }); } -async function downloadFile(url, dest) { - console.error(`Downloading: ${url}`); - const res = await get(url); +function urlToOptions(target) { + return { + protocol: target.protocol, + hostname: target.hostname, + port: target.port || undefined, + path: `${target.pathname}${target.search}`, + method: 'GET', + }; +} + +function createTunnelAgent(socket) { + const agent = new https.Agent({ keepAlive: false }); + agent.createConnection = () => socket; + return agent; +} + +/** GET with redirects, host allow-list and proxy support; resolves with a 200 response stream. */ +async function get(url, redirectCount = 0) { + const target = assertAllowedUrl(url); + const proxy = proxyFor(url); + const headers = { 'user-agent': 'spring-tools-claude-plugin' }; + let request; + if (proxy && target.protocol === 'https:') { + const socket = await connectThroughProxy(proxy, target); + request = https.request({ ...urlToOptions(target), headers, agent: createTunnelAgent(socket) }); + } else if (proxy) { + const auth = proxyAuthHeader(proxy); + request = http.request({ + host: proxy.hostname, port: Number(proxy.port) || 80, method: 'GET', path: target.href, + headers: { ...headers, host: target.host, ...(auth ? { 'proxy-authorization': auth } : {}) }, + }); + } else { + request = (target.protocol === 'https:' ? https : http).request({ ...urlToOptions(target), headers }); + } + const response = await new Promise((resolve, reject) => { + request.setTimeout(SOCKET_IDLE_TIMEOUT_MS, () => request.destroy(new Error(`Timed out fetching ${url}`))); + request.once('response', resolve); + request.once('error', reject); + request.end(); + }); + if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) { + response.resume(); + if (redirectCount >= MAX_REDIRECTS) { + throw new Error(`Too many redirects while fetching ${url}`); + } + return get(new URL(response.headers.location, url).toString(), redirectCount + 1); + } + if (response.statusCode !== 200) { + response.resume(); + throw new Error(`Failed to fetch ${url}: HTTP ${response.statusCode}`); + } + return response; +} + +async function fetchText(url) { + const response = await get(url); + let data = ''; + for await (const chunk of response) { + data += chunk; + if (data.length > 4096) { + throw new Error(`Unexpectedly large checksum file at ${url}`); + } + } + return data.trim(); +} + +/** Streams the URL into dest while hashing; resolves with the hex SHA-256 of what was written. */ +async function downloadFile(url, dest, log) { + const response = await get(url); + const total = Number(response.headers['content-length']) || 0; const hash = crypto.createHash('sha256'); - const fileStream = fs.createWriteStream(dest); - return new Promise((resolve, reject) => { - res.on('data', chunk => hash.update(chunk)); - res.on('error', reject); - fileStream.on('error', reject); - fileStream.on('finish', () => resolve(hash.digest('hex'))); - res.pipe(fileStream); + let received = 0; + let nextReport = 0; + const meter = new Transform({ + transform(chunk, encoding, callback) { + hash.update(chunk); + received += chunk.length; + if (total && received >= nextReport) { + log(` ${Math.floor((received / total) * 100)}% (${Math.round(received / 1048576)} of ${Math.round(total / 1048576)} MB)`); + nextReport += Math.max(total / 10, 1); + } + callback(null, chunk); + }, }); + await pipeline(response, meter, fs.createWriteStream(dest, { flags: 'wx' })); + if (total && received !== total) { + throw new Error(`Download of ${url} ended after ${received} of ${total} bytes`); + } + return hash.digest('hex'); +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** Creates .lock exclusively; waits while another installer holds it, breaks stale locks. */ +async function acquireLock(lockPath) { + const started = Date.now(); + for (;;) { + try { + fs.writeFileSync(lockPath, `${process.pid} ${new Date().toISOString()}\n`, { flag: 'wx' }); + return () => { try { fs.unlinkSync(lockPath); } catch { /* already gone */ } }; + } catch (error) { + if (error.code !== 'EEXIST') { + throw error; + } + } + try { + const lock = fs.statSync(lockPath); + const ownerPid = Number(fs.readFileSync(lockPath, 'utf8').trim().split(/\s+/, 1)[0]); + const hasOwnerPid = Number.isSafeInteger(ownerPid) && ownerPid > 0; + let ownerAlive = false; + if (hasOwnerPid) { + try { + process.kill(ownerPid, 0); + ownerAlive = true; + } catch (ownerError) { + if (ownerError.code === 'EPERM') { + ownerAlive = true; + } else if (ownerError.code !== 'ESRCH') { + throw ownerError; + } + } + } + if ((hasOwnerPid && !ownerAlive) || Date.now() - lock.mtimeMs > LOCK_STALE_MS) { + fs.unlinkSync(lockPath); + continue; + } + } catch (lockError) { + if (lockError.code !== 'ENOENT') { + throw lockError; + } + } + if (Date.now() - started > LOCK_WAIT_MAX_MS) { + throw new Error(`Gave up waiting for another installer holding ${lockPath}`); + } + await sleep(LOCK_POLL_MS); + } } -async function install() { - console.error(`Installing Spring Boot Language Server v${version}...`); +function removeStalePartials(dir) { + for (const entry of fs.readdirSync(dir)) { + if (entry.startsWith(JAR_NAME) && entry.endsWith('.part')) { + try { fs.unlinkSync(path.join(dir, entry)); } catch { /* best effort */ } + } + } +} - const isSnapshot = version.includes('-'); - const baseUrl = isSnapshot - ? `https://cdn.spring.io/spring-tools/snapshot/language-server/spring-boot/${JAR_NAME}` - : `https://cdn.spring.io/spring-tools/release/language-server/spring-boot/${version}/${JAR_NAME}`; - const sha256Url = `${baseUrl}.sha256`; +function findSourceRoot(pluginRoot, env = process.env) { + const candidates = [env.SPRING_TOOLS_SOURCE_DIR, path.resolve(pluginRoot, '..', '..')].filter(Boolean); + return candidates.map((candidate) => path.resolve(candidate)).find((root) => + fs.existsSync(path.join(root, 'headless-services', 'pom.xml')) + && (fs.existsSync(path.join(root, 'headless-services', 'mvnw')) || fs.existsSync(path.join(root, 'headless-services', 'mvnw.cmd')))); +} +function buildJar(pluginRoot, dest, log) { + const sourceRoot = findSourceRoot(pluginRoot); + if (!sourceRoot) { + throw new Error('No Spring Tools source checkout found for a local build. Set SPRING_TOOLS_SOURCE_DIR to the repository root, or install the JAR manually and set SPRING_TOOLS_LS_JAR.'); + } + const servicesDir = path.join(sourceRoot, 'headless-services'); + const wrapper = path.join(servicesDir, process.platform === 'win32' ? 'mvnw.cmd' : 'mvnw'); + const args = ['-pl', 'spring-boot-language-server-standalone', '-am', '-DskipTests', 'package']; + log(`Building Spring Boot Language Server from ${sourceRoot}`); + // Maven must not read MCP requests or write build output to the MCP stdout transport. + const result = spawnSync(wrapper, args, { cwd: servicesDir, stdio: ['ignore', 2, 2], shell: process.platform === 'win32' }); + if (result.error || result.status !== 0) { + throw new Error(`Local language server build failed${result.error ? `: ${result.error.message}` : ` (exit code ${result.status})`}`); + } + const targetDir = path.join(sourceRoot, 'headless-services', 'spring-boot-language-server-standalone', 'target'); + const builtJar = fs.readdirSync(targetDir).filter((name) => name.endsWith('-standalone-exec.jar')).sort().at(-1); + if (!builtJar) throw new Error(`Maven build completed but no standalone JAR was found in ${targetDir}`); + const temporary = path.join(dest, `${JAR_NAME}.${process.pid}.part`); try { - const expectedSha256 = await fetchText(sha256Url); - const actualSha256 = await downloadFile(baseUrl, jarPath); + fs.copyFileSync(path.join(targetDir, builtJar), temporary, fs.constants.COPYFILE_EXCL); + fs.renameSync(temporary, path.join(dest, JAR_NAME)); + } finally { + try { fs.unlinkSync(temporary); } catch { /* already renamed or absent */ } + } + log(`Built Spring Boot Language Server and installed it to ${path.join(dest, JAR_NAME)}`); +} - if (actualSha256.toLowerCase() !== expectedSha256.toLowerCase()) { - fs.unlinkSync(jarPath); - throw new Error(`Checksum mismatch for ${JAR_NAME}: expected ${expectedSha256}, got ${actualSha256}`); +/** + * Makes sure / exists for the given plugin version. + * @returns {Promise<{status: 'present'|'downloaded', jarPath: string}>} + */ +async function ensureJar({ pluginRoot = __dirname, dest = defaultInstallDir(pluginRoot), ifMissing = false, log = (line) => console.error(line) } = {}) { + const jarPath = path.join(dest, JAR_NAME); + if (ifMissing && fs.existsSync(jarPath)) { + return { status: 'present', jarPath }; + } + const version = pluginVersion(pluginRoot); + fs.mkdirSync(dest, { recursive: true }); + const release = await acquireLock(`${jarPath}.lock`); + try { + if (ifMissing && fs.existsSync(jarPath)) { + return { status: 'present', jarPath }; } + removeStalePartials(dest); + try { + const { jarUrl, sha256Url } = downloadUrls(version); + log(`Downloading Spring Boot Language Server ${version} from ${jarUrl}`); + const expected = (await fetchText(sha256Url)).split(/\s+/)[0].toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(expected)) { + throw new Error(`Checksum file ${sha256Url} does not contain a SHA-256 digest`); + } + const partPath = `${jarPath}.${process.pid}.part`; + try { + const actual = await downloadFile(jarUrl, partPath, log); + if (actual !== expected) throw new Error(`Checksum mismatch for ${JAR_NAME}: expected ${expected}, got ${actual}`); + fs.renameSync(partPath, jarPath); + } finally { + try { fs.unlinkSync(partPath); } catch { /* renamed away or never created */ } + } + log(`Installed Spring Boot Language Server ${version} to ${jarPath}`); + return { status: 'downloaded', jarPath }; + } catch (downloadError) { + log(`Language server download failed: ${downloadError.message}`); + try { + buildJar(pluginRoot, dest, log); + return { status: 'built', jarPath }; + } catch (buildError) { + throw new Error(`Could not download or build the Spring Tools language server. Download error: ${downloadError.message}. Build error: ${buildError.message}`); + } + } + } finally { + release(); + } +} + +function parseArgs(argv) { + const options = { ifMissing: false, dest: undefined, help: false }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--if-missing') options.ifMissing = true; + else if (arg === '--dest') { + if (!argv[i + 1] || argv[i + 1].startsWith('--')) { + throw new Error('--dest requires a directory path'); + } + options.dest = path.resolve(argv[++i]); + } + else if (arg === '--help' || arg === '-h') options.help = true; + else throw new Error(`unknown argument: ${arg}`); + } + return options; +} - console.error(`Successfully installed version ${version} to ${jarPath}`); - } catch (err) { - throw new Error(`Failed to download JAR from ${baseUrl}\nError: ${err.message}`); +async function main() { + const options = parseArgs(process.argv.slice(2)); + if (options.help) { + console.error('usage: node install.js [--if-missing] [--dest ]'); + return 0; } + if (process.env.SPRING_TOOLS_LS_JAR) { + console.error(`SPRING_TOOLS_LS_JAR is set (${process.env.SPRING_TOOLS_LS_JAR}); nothing to download.`); + return 0; + } + const result = await ensureJar({ ifMissing: options.ifMissing, dest: options.dest }); + if (result.status === 'downloaded') { + // stdout of a SessionStart hook is added to Claude's context. + console.log(`Spring Tools downloaded its language server to ${result.jarPath}. If the Spring Tools MCP server is listed as failed, reconnect it or restart the agent client.`); + } + return 0; +} + +if (require.main === module) { + main().then((code) => process.exit(code), (error) => { + console.error(`Spring Tools language server installation failed: ${error.message}`); + process.exit(1); + }); } -install().catch(err => { - console.error("Installation failed:", err); - process.exit(1); -}); +module.exports = { JAR_NAME, DEFAULT_DOWNLOAD_BASE, downloadUrls, assertAllowedUrl, proxyFor, hostMatchesNoProxy, ensureJar, pluginVersion, defaultInstallDir, parseArgs, findSourceRoot, createTunnelAgent }; diff --git a/claude-plugins/spring-tools/launcher.js b/claude-plugins/spring-tools/launcher.js index 4e974f9fd6..194b2ab504 100644 --- a/claude-plugins/spring-tools/launcher.js +++ b/claude-plugins/spring-tools/launcher.js @@ -1,65 +1,305 @@ -/* Copyright (c) 2026 Broadcom, Inc. */ +#!/usr/bin/env node +/******************************************************************************* + * Copyright (c) 2026 Broadcom + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Broadcom - initial API and implementation + *******************************************************************************/ +// Starts the standalone Spring Boot language server as an MCP stdio server for Claude Code, +// GitHub Copilot CLI, Codex and OpenCode. +// Environment (all optional): +// SPRING_TOOLS_JAVA java executable to use (else $JAVA_HOME/bin/java, else java on PATH; first with Java 21+ wins) +// SPRING_TOOLS_JAVA_OPTS extra JVM options, e.g. "-Xmx2g" (appended after the defaults, so they override them) +// SPRING_TOOLS_LS_JAR path to a local language server JAR to run instead of the downloaded one +// SPRING_TOOLS_LS_WATCH "false" disables the built-in file watcher; use hooks or explicit change tools to update the index +// SPRING_TOOLS_PROJECT_DIR workspace directory to index, overriding the auto-detection below +// SPRING_TOOLS_DATA_DIR persistent log/runtime directory (else use client data dir or ~/.spring-tools/data) +'use strict'; const fs = require('fs'); +const os = require('os'); const path = require('path'); const { spawn, spawnSync } = require('child_process'); +const { ensureJar, JAR_NAME, defaultInstallDir } = require('./install.js'); -const jarDir = path.join(__dirname, 'language-server'); -const jarPath = path.join(jarDir, 'spring-boot-language-server-standalone-exec.jar'); +const MIN_JAVA_MAJOR = 21; -async function start() { - // 1. Download the JAR if it doesn't exist - if (!fs.existsSync(jarPath)) { - console.error("Spring Boot Language Server JAR not found. Downloading on first run..."); - try { - spawnSync('node', [path.join(__dirname, 'install.js')], { stdio: 'inherit' }); - } catch (e) { - console.error("Failed to download JAR:", e); - process.exit(1); +// Shown to the client alongside the tool names when MCP tool search defers the full tool list. +const SERVER_INSTRUCTIONS = [ + 'Spring Tools language server for the Spring Boot projects in this workspace.', + 'Start with getProjectList (use the projectName field, location is the project root directory; retry while the list is still empty right after startup, the project model is being resolved).', + 'getProjectDiagnostics reports Spring-specific problems with a code such as JAVA_PUBLIC_BEAN_METHOD; every code has a fix playbook. Use the quickfix skill when available, or read the matching explanations/.md file, then validate the project with the validate skill or getProjectDiagnostics.', + 'Bean wiring: getBeanDetails, findBeansByType, getBeanUsageInfo. Endpoints: getRequestMappings, findRequestMappingsByMethod. Build facts: getSpringBootVersion, getJavaVersion, getResolvedProjectClasspath.', + 'Architecture: getLogicalStructure, getStereotypesList, findComponentsByStereotype and the logical-structure baseline tools. Spring versions and support: getReleases, getGenerations, getUpcomingReleases, getLatestReleaseInformation.', + 'For guidance, use the quickfix or validate Spring Tools skill when available.', + 'The server watches the workspace directory, so edits, new files and new projects are picked up within a second without any notification; call fileChanged/fileDeleted only when a change might have been missed and refreshWorkspace when the index looks stale (e.g. after a large git checkout).', +].join(' '); + +/** + * Server instructions with the absolute location of the fix playbooks appended. Clients that do not + * substitute path placeholders in skill and agent files learn where the playbooks are this way. + */ +function serverInstructions(pluginRoot = __dirname) { + return `${SERVER_INSTRUCTIONS} The fix playbooks are the .md files in ${path.join(pluginRoot, 'explanations')}.`; +} + +/** Major Java version from `java -version` output; null when unparseable. */ +function parseJavaMajor(output) { + const match = /version "(\d+)(?:\.(\d+))?/.exec(output || ''); + if (!match) { + return null; + } + const major = Number(match[1]); + return major === 1 ? Number(match[2]) : major; +} + +/** Java executables to try, most specific first. */ +function javaCandidates(env = process.env, platform = process.platform) { + const exe = platform === 'win32' ? 'java.exe' : 'java'; + const candidates = []; + if (env.SPRING_TOOLS_JAVA) { + candidates.push({ java: env.SPRING_TOOLS_JAVA, source: 'SPRING_TOOLS_JAVA' }); + } + if (env.JAVA_HOME) { + candidates.push({ java: path.join(env.JAVA_HOME, 'bin', exe), source: 'JAVA_HOME' }); + } + candidates.push({ java: 'java', source: 'PATH' }); + return candidates; +} + +function probeJava(java) { + const result = spawnSync(java, ['-version'], { encoding: 'utf8', timeout: 20000, windowsHide: true }); + if (result.error) { + return { output: '', error: result.error.message }; + } + return { output: `${result.stderr || ''}${result.stdout || ''}` }; +} + +/** First candidate that runs and reports Java >= MIN_JAVA_MAJOR, plus what was tried. */ +function pickJava(candidates, probe = probeJava) { + const tried = []; + for (const candidate of candidates) { + const probed = probe(candidate.java); + const major = probed.error ? null : parseJavaMajor(probed.output); + tried.push({ ...candidate, major, error: probed.error }); + if (major !== null && major >= MIN_JAVA_MAJOR) { + return { ...candidate, major, tried }; + } + } + return { java: null, major: null, tried }; +} + +function describeTried(tried) { + return tried.map((t) => `${t.java} (${t.source}): ${t.error ? t.error : t.major === null ? 'no version reported' : `Java ${t.major}`}`).join('; '); +} + +/** Splits a JVM options string on whitespace, honoring single/double quotes (also inside a token). */ +function splitOpts(value) { + const opts = []; + let current = ''; + let quote = null; + let inToken = false; + for (const char of value || '') { + if (quote) { + if (char === quote) { + quote = null; + } else { + current += char; + } + } else if (char === '"' || char === "'") { + quote = char; + inToken = true; + } else if (/\s/.test(char)) { + if (inToken) { + opts.push(current); + } + current = ''; + inToken = false; + } else { + current += char; + inToken = true; + } + } + if (inToken) { + opts.push(current); + } + return opts; +} + +/** true unless SPRING_TOOLS_LS_WATCH is set to false/0/no/off (case-insensitive). */ +function watchEnabled(value) { + return !/^\s*(false|0|no|off)\s*$/i.test(value || ''); +} + +function resolveDataDir({ env = process.env, home = os.homedir() } = {}) { + return path.resolve(env.SPRING_TOOLS_DATA_DIR || env.CLAUDE_PLUGIN_DATA || env.PLUGIN_DATA || path.join(home, '.spring-tools', 'data')); +} + +function isDirectory(dir) { + try { + return fs.statSync(dir).isDirectory(); + } catch { + return false; + } +} + +/** An absolute, existing directory that is not the plugin's own root (which is never a workspace). */ +function usableProjectDir(dir, pluginRoot) { + return !!dir && path.isAbsolute(dir) && path.resolve(dir) !== path.resolve(pluginRoot) && isDirectory(dir); +} + +/** + * GitHub Copilot CLI starts plugin MCP servers with the plugin root as working directory and passes + * no workspace path, but it records the session's directory before starting them. + */ +function copilotWorkspaceDir(env, home) { + const session = env.COPILOT_AGENT_SESSION_ID; + // A session id is a single path segment; anything else would escape the session-state directory. + if (!session || !/^[\w.-]+$/.test(session) || session === '.' || session === '..') { + return null; + } + try { + const state = fs.readFileSync(path.join(home, '.copilot', 'session-state', session, 'workspace.yaml'), 'utf8'); + return /^cwd:[ \t]*(.+?)[ \t]*$/m.exec(state)?.[1] ?? null; + } catch { + return null; + } +} + +/** + * Workspace the language server should index. Claude Code exports CLAUDE_PROJECT_DIR; Copilot CLI + * runs it in the plugin directory, so the workspace has to be recovered from session state. Other + * plugin hosts may also change the MCP process cwd, so prefer the inherited PWD to that fallback. + * @returns {{dir: string, source: string, detected: boolean}} + */ +function resolveProjectDir({ env = process.env, cwd = process.cwd(), pluginRoot = __dirname, home = os.homedir() } = {}) { + const override = env.SPRING_TOOLS_PROJECT_DIR; + if (override) { + const dir = path.resolve(cwd, override); + if (!isDirectory(dir)) { + throw new Error(`SPRING_TOOLS_PROJECT_DIR is not an existing directory: ${dir}`); } + return { dir, source: 'SPRING_TOOLS_PROJECT_DIR', detected: true }; } + const candidates = [ + { dir: env.CLAUDE_PROJECT_DIR, source: 'CLAUDE_PROJECT_DIR' }, + { dir: copilotWorkspaceDir(env, home), source: 'Copilot session state' }, + { dir: env.PWD, source: 'PWD' }, + { dir: cwd, source: 'working directory' }, + ]; + for (const candidate of candidates) { + if (usableProjectDir(candidate.dir, pluginRoot)) { + return { dir: path.resolve(candidate.dir), source: candidate.source, detected: true }; + } + } + return { dir: path.resolve(cwd), source: 'working directory', detected: false }; +} - // 2. Launch the Java process. The plugin only exposes MCP tools over stdio - - // the LSP socket transport is disabled since nothing connects to it. - const javaArgs = [ - "-Xmx1024m", - "-Djdk.util.zip.disableZip64ExtraFieldValidation=true", - "-Dspring.config.location=classpath:/application.properties", - "-Dspring.profiles.active=file-logging", - `-Dlogging.file.name=${path.join(__dirname, 'boot-ls.log')}`, - "-Dlogging.level.root=INFO", - "-Dspring.ai.mcp.server.stdio=true", - "-Dlanguageserver.enabled=false", - `-Dlanguageserver.standalone.project-dir=${process.cwd()}`, - "-jar", - jarPath +function buildJavaArgs({ jarPath, dataDir, projectDir, watch = true, extraOpts = [], instructions = serverInstructions() }) { + return [ + '-Xmx1024m', + '-Djdk.util.zip.disableZip64ExtraFieldValidation=true', + '-Dspring.config.location=classpath:/application.properties', + '-Dspring.profiles.active=file-logging', + `-Dlogging.file.name=${path.join(dataDir, 'boot-ls.log')}`, + '-Dlogging.level.root=INFO', + '-Dspring.ai.mcp.server.stdio=true', + `-Dspring.ai.mcp.server.instructions=${instructions}`, + // Only the MCP tools are exposed over stdio; nothing connects to the LSP transport. + '-Dlanguageserver.enabled=false', + `-Dspring.boot.ls.project.dir=${projectDir}`, + // The server follows on-disk changes under the project dir itself (java.nio WatchService). + `-Dspring.boot.ls.project.watch=${watch ? 'true' : 'false'}`, + ...extraOpts, + '-jar', + jarPath, ]; +} - const child = spawn('java', javaArgs, { stdio: 'inherit' }); +async function resolveJar(log) { + if (process.env.SPRING_TOOLS_LS_JAR) { + const jarPath = path.resolve(process.env.SPRING_TOOLS_LS_JAR); + if (!fs.existsSync(jarPath)) { + throw new Error(`SPRING_TOOLS_LS_JAR points to a missing file: ${jarPath}`); + } + log(`Using language server JAR from SPRING_TOOLS_LS_JAR: ${jarPath}`); + return jarPath; + } + const jarDest = defaultInstallDir(__dirname); + const jarPath = path.join(jarDest, JAR_NAME); + if (!fs.existsSync(jarPath)) { + log(`${JAR_NAME} not found, downloading it (first start of this plugin version). If the client reports the MCP server as failed before the download finishes, reconnect it after the download completes.`); + } + return (await ensureJar({ pluginRoot: __dirname, dest: jarDest, ifMissing: true, log })).jarPath; +} + +async function start() { + const log = (line) => console.error(`[spring-tools] ${line}`); + // The plugin root changes on every plugin update, so runtime state such as the log file goes to + // the persistent data dir both clients export (PLUGIN_DATA is the Agent Plugins spelling). + const project = resolveProjectDir(); + const dataDir = resolveDataDir(); + if (project.detected) { + log(`Indexing ${project.dir} (from ${project.source})`); + } else { + throw new Error(`Could not determine the workspace directory; refusing to index the plugin directory ${project.dir}. Set SPRING_TOOLS_PROJECT_DIR in the MCP server environment to the workspace root. For Codex, configure the server env explicitly; exporting a variable in the parent shell may not forward it.`); + } + + const picked = pickJava(javaCandidates()); + if (!picked.java) { + throw new Error(`No Java ${MIN_JAVA_MAJOR}+ runtime found. Tried: ${describeTried(picked.tried)}. Install a JDK 21 or newer and put it on PATH, or point JAVA_HOME or SPRING_TOOLS_JAVA at it.`); + } + log(`Using Java ${picked.major} from ${picked.java} (${picked.source})`); + + const jarPath = await resolveJar(log); + fs.mkdirSync(dataDir, { recursive: true }); + const watch = watchEnabled(process.env.SPRING_TOOLS_LS_WATCH); + if (!watch) { + log('File watcher disabled by SPRING_TOOLS_LS_WATCH; the index only follows the plugin hooks and explicit fileChanged/refreshWorkspace calls.'); + } + const javaArgs = buildJavaArgs({ jarPath, dataDir, projectDir: project.dir, watch, extraOpts: splitOpts(process.env.SPRING_TOOLS_JAVA_OPTS) }); + const child = spawn(picked.java, javaArgs, { stdio: 'inherit', windowsHide: true }); - // When Claude Code exits, it sends a termination signal to this Node script. - // We must catch these signals and manually kill the heavy Java child process - // so it doesn't remain active as an orphan in the background. - ['SIGINT', 'SIGTERM', 'SIGQUIT'].forEach(signal => { - process.on(signal, () => { + // The client terminates this launcher when the session ends; forward that to the JVM so it + // does not linger as an orphan. The server shuts down gracefully within about a second. + let shutdownSignal = null; + let forceKillTimer; + for (const signal of ['SIGINT', 'SIGTERM', 'SIGQUIT']) { + process.once(signal, () => { + shutdownSignal = signal; if (!child.killed) { child.kill('SIGTERM'); } - process.exit(0); + // Give the language server time to flush logs and release workspace resources. + forceKillTimer = setTimeout(() => child.kill('SIGKILL'), 5000); + forceKillTimer.unref(); }); - }); + } - child.on('error', (err) => { - console.error('Failed to start Java process:', err); + child.on('error', (error) => { + log(`Failed to start the Java process: ${error.message}`); process.exit(1); }); + child.on('close', (code, signal) => { + clearTimeout(forceKillTimer); + if (shutdownSignal) { + process.exit(0); + } else if (code !== 0) { + log(`Language server exited with ${signal ? `signal ${signal}` : `code ${code}`}; see ${path.join(dataDir, 'boot-ls.log')}`); + } + process.exit(code ?? 1); + }); +} - child.on('close', (code) => { - process.exit(code); +if (require.main === module) { + start().catch((error) => { + console.error(`[spring-tools] ${error.message}`); + process.exit(1); }); } -start().catch(err => { - console.error("Failed to start launcher:", err); - process.exit(1); -}); \ No newline at end of file +module.exports = { MIN_JAVA_MAJOR, SERVER_INSTRUCTIONS, serverInstructions, parseJavaMajor, javaCandidates, pickJava, splitOpts, watchEnabled, buildJavaArgs, resolveProjectDir, resolveDataDir }; diff --git a/claude-plugins/spring-tools/skills/refresh/SKILL.md b/claude-plugins/spring-tools/skills/refresh/SKILL.md new file mode 100644 index 0000000000..976fb53e99 --- /dev/null +++ b/claude-plugins/spring-tools/skills/refresh/SKILL.md @@ -0,0 +1,15 @@ +--- +name: refresh +description: Refresh the Spring Tools workspace so the language server re-indexes files on disk (use after /rewind, a large git checkout, external edits the watcher may have missed, or when a project is missing from getProjectList). +allowed-tools: + - mcp__plugin_spring-tools_spring-tools-mcp__refreshWorkspace + - mcp__plugin_spring-tools_spring-tools-mcp__fileChanged + - mcp__plugin_spring-tools_spring-tools-mcp__fileDeleted +--- + +Bring the Spring Tools index back in sync with the files on disk. The language server watches the workspace directory and the plugin's hooks report Claude's own edits, so this is only needed when the index looks stale (a diagnostic refers to code that is gone, a new project or class is missing, the tree changed massively after `/rewind` or a branch switch). + +- Without arguments, or after a git checkout/pull/stash, `/rewind` or a build tool regenerating sources: call the `refreshWorkspace` tool on the `spring-tools-mcp` MCP server. It re-reads the project model (discovering added and removed projects) and re-indexes every source file. +- When the user names one file or a small set of files that changed or disappeared outside of Claude's edits: call `fileChanged` (absolute path) for each file that exists and `fileDeleted` for each file that was removed instead of a full refresh - this is much cheaper on large workspaces. + +Do not do anything else. After the tool returns, briefly confirm to the user what was refreshed. diff --git a/claude-plugins/tools/test/install.test.mjs b/claude-plugins/tools/test/install.test.mjs new file mode 100644 index 0000000000..a314dbae67 --- /dev/null +++ b/claude-plugins/tools/test/install.test.mjs @@ -0,0 +1,313 @@ +/******************************************************************************* + * Copyright (c) 2026 Broadcom + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Broadcom - initial API and implementation + *******************************************************************************/ + +// Exercises the plugin's JAR installer against a local HTTP server standing in for the CDN. + +import assert from 'node:assert/strict'; +import { execFile, spawnSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { after, afterEach, before, beforeEach, test } from 'node:test'; + +const require = createRequire(import.meta.url); +const here = dirname(fileURLToPath(import.meta.url)); +const pluginRoot = join(here, '..', '..', 'spring-tools'); +const installer = require(join(pluginRoot, 'install.js')); +const { JAR_NAME, ensureJar, downloadUrls, assertAllowedUrl, proxyFor, hostMatchesNoProxy, pluginVersion, defaultInstallDir, parseArgs, createTunnelAgent } = installer; + +const version = pluginVersion(pluginRoot); +// Download-failure tests must not resolve the build fallback against this file's own checkout +// (findSourceRoot would find it and kick off a real, multi-minute Maven build); give them a +// pluginRoot whose parent directories hold no source checkout. +const isolatedRoot = mkdtempSync(join(tmpdir(), 'spring-tools-isolated-')); +const isolatedPluginRoot = join(isolatedRoot, 'claude-plugins', 'spring-tools'); +mkdirSync(isolatedPluginRoot, { recursive: true }); +writeFileSync(join(isolatedPluginRoot, 'plugin.json'), JSON.stringify({ version })); +const jarBytes = randomBytes(3 * 1024 * 1024 + 123); +const jarDigest = createHash('sha256').update(jarBytes).digest('hex'); +const state = { mode: 'ok', requests: [] }; +let server; +let base; +let loopbackUnavailable = false; +const quiet = () => {}; + +test('installer defaults to persistent client data and rejects a missing --dest value', () => { + assert.equal(defaultInstallDir(pluginRoot, { PLUGIN_DATA: '/client/data' }, '/home/test'), join('/client/data', 'language-server', version)); + assert.equal(defaultInstallDir(pluginRoot, {}, '/home/test'), join('/home/test/.spring-tools/data', 'language-server', version)); + assert.throws(() => parseArgs(['--dest']), /requires a directory path/); + assert.throws(() => parseArgs(['--dest', '--if-missing']), /requires a directory path/); + assert.equal(parseArgs(['--dest', 'cache']).dest, join(process.cwd(), 'cache')); +}); + +test('plugin versions used in download paths cannot escape the plugin data directory', () => { + const root = mkdtempSync(join(tmpdir(), 'spring-tools-version-')); + try { + mkdirSync(join(root, '.claude-plugin')); + writeFileSync(join(root, '.claude-plugin', 'plugin.json'), JSON.stringify({ version: '../../outside' })); + assert.throws(() => pluginVersion(root), /valid version/); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +before(async () => { + server = createServer((req, res) => { + state.requests.push(req.url); + let { pathname } = new URL(req.url, 'http://127.0.0.1'); + if (state.mode === 'missing') { + res.writeHead(404); + res.end('not found'); + return; + } + const jarPath = `/spring-tools/release/language-server/spring-boot/${version}/${JAR_NAME}`; + if (state.mode === 'redirect' && pathname.startsWith(jarPath)) { + res.writeHead(302, { location: pathname.replace(jarPath, `/spring-tools/moved/${JAR_NAME}`) }); + res.end(); + return; + } + pathname = pathname.replace(`/spring-tools/moved/${JAR_NAME}`, jarPath); + if (pathname === `${jarPath}.sha256`) { + const digest = state.mode === 'bad-sum' ? 'f'.repeat(64) : jarDigest; + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(state.mode === 'sha256sum-format' ? `${digest} ${JAR_NAME}\n` : `${digest}\n`); + } else if (pathname === jarPath) { + res.writeHead(200, { 'content-type': 'application/java-archive', 'content-length': jarBytes.length }); + res.end(jarBytes); + } else { + res.writeHead(404); + res.end('not found'); + } + }); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }).catch((error) => { + if (error.code !== 'EPERM') throw error; + loopbackUnavailable = true; + }); + if (loopbackUnavailable) return; + base = `http://127.0.0.1:${server.address().port}/spring-tools`; + process.env.SPRING_TOOLS_LS_DOWNLOAD_BASE = base; + // This test file runs inside a real Spring Tools checkout, which the build fallback would + // otherwise find and use to run a real Maven build; point it at a directory with no checkout + // so download-failure tests see a clean failure instead of a multi-minute reactor build. + process.env.SPRING_TOOLS_SOURCE_DIR = join(tmpdir(), 'spring-tools-no-source-checkout'); +}); + +after(() => { + if (server?.listening) server.close(); + delete process.env.SPRING_TOOLS_LS_DOWNLOAD_BASE; + delete process.env.SPRING_TOOLS_SOURCE_DIR; +}); + +let dest; +beforeEach(() => { + state.mode = 'ok'; + state.requests = []; + dest = mkdtempSync(join(tmpdir(), 'spring-tools-install-')); +}); + +afterEach(() => { + if (dest) { + rmSync(dest, { recursive: true, force: true }); + dest = undefined; + } +}); + +const leftovers = () => readdirSync(dest).filter((n) => n !== JAR_NAME); +const skipWithoutLoopback = (t) => { + if (!loopbackUnavailable) return false; + t.skip('sandbox denies loopback server binding'); + return true; +}; + +test('downloads the JAR for the plugin version, verifies it and installs it atomically', async (t) => { + if (skipWithoutLoopback(t)) return; + const result = await ensureJar({ pluginRoot, dest, log: quiet }); + assert.equal(result.status, 'downloaded'); + assert.equal(result.jarPath, join(dest, JAR_NAME)); + assert.ok(readFileSync(result.jarPath).equals(jarBytes), 'installed bytes must match the download'); + assert.deepEqual(leftovers(), [], 'no .part or .lock files may remain'); + assert.deepEqual(state.requests.map((u) => u.endsWith('.sha256')), [true, false], 'checksum first, then the JAR'); +}); + +test('--if-missing is a no-op when the JAR is already there', async () => { + writeFileSync(join(dest, JAR_NAME), 'existing'); + const result = await ensureJar({ pluginRoot, dest, ifMissing: true, log: quiet }); + assert.equal(result.status, 'present'); + assert.equal(readFileSync(join(dest, JAR_NAME), 'utf8'), 'existing'); + assert.deepEqual(state.requests, [], 'must not contact the server'); +}); + +test('negative control: a checksum mismatch leaves no JAR and no partial file behind', async (t) => { + if (skipWithoutLoopback(t)) return; + state.mode = 'bad-sum'; + await assert.rejects(ensureJar({ pluginRoot: isolatedPluginRoot, dest, log: quiet }), /Checksum mismatch/); + assert.ok(!existsSync(join(dest, JAR_NAME)), 'a JAR that failed verification must not be installed'); + assert.deepEqual(leftovers(), []); +}); + +test('accepts the sha256sum "digest filename" checksum format', async (t) => { + if (skipWithoutLoopback(t)) return; + state.mode = 'sha256sum-format'; + await ensureJar({ pluginRoot: isolatedPluginRoot, dest, log: quiet }); + assert.ok(readFileSync(join(dest, JAR_NAME)).equals(jarBytes)); +}); + +test('follows redirects that stay on an allowed host', async (t) => { + if (skipWithoutLoopback(t)) return; + state.mode = 'redirect'; + await ensureJar({ pluginRoot, dest, log: quiet }); + assert.ok(readFileSync(join(dest, JAR_NAME)).equals(jarBytes)); + assert.ok(state.requests.some((u) => u.includes('/moved/')), 'the moved locations must have been fetched'); +}); + +test('concurrent installers serialize on the lock and the second one reuses the first download', async (t) => { + if (skipWithoutLoopback(t)) return; + const [a, b] = await Promise.all([ + ensureJar({ pluginRoot, dest, ifMissing: true, log: quiet }), + ensureJar({ pluginRoot, dest, ifMissing: true, log: quiet }), + ]); + assert.deepEqual([a.status, b.status].sort(), ['downloaded', 'present']); + assert.equal(state.requests.filter((u) => !u.endsWith('.sha256')).length, 1, 'the JAR must be downloaded once'); + assert.deepEqual(leftovers(), []); +}); + +test('stale partial downloads from an interrupted run are removed', async (t) => { + if (skipWithoutLoopback(t)) return; + writeFileSync(join(dest, `${JAR_NAME}.4242.part`), 'truncated'); + await ensureJar({ pluginRoot, dest, log: quiet }); + assert.deepEqual(leftovers(), []); +}); + +test('falls back to building the standalone JAR from an available source checkout', async (t) => { + if (skipWithoutLoopback(t)) return; + state.mode = 'missing'; + const root = mkdtempSync(join(tmpdir(), 'spring-tools-source-')); + const localPlugin = join(root, 'claude-plugins', 'spring-tools'); + const target = join(root, 'headless-services', 'spring-boot-language-server-standalone', 'target'); + mkdirSync(localPlugin, { recursive: true }); + mkdirSync(target, { recursive: true }); + writeFileSync(join(localPlugin, 'plugin.json'), JSON.stringify({ version })); + writeFileSync(join(root, 'headless-services', 'pom.xml'), ''); + writeFileSync(join(root, 'headless-services', 'mvnw'), `#!/bin/sh\nprintf "Maven build output\\n"\nmkdir -p spring-boot-language-server-standalone/target\nprintf built > spring-boot-language-server-standalone/target/test-standalone-exec.jar\n`); + chmodSync(join(root, 'headless-services', 'mvnw'), 0o755); + try { + const script = `require(${JSON.stringify(join(pluginRoot, 'install.js'))}).ensureJar({ + pluginRoot: ${JSON.stringify(localPlugin)}, dest: ${JSON.stringify(dest)} + }).then(result => process.stdout.write(JSON.stringify(result))).catch(error => { + console.error(error); process.exitCode = 1; + });`; + const output = await new Promise((resolve, reject) => { + execFile(process.execPath, ['-e', script], { + env: { ...process.env, SPRING_TOOLS_LS_DOWNLOAD_BASE: base, SPRING_TOOLS_SOURCE_DIR: root }, + }, (error, stdout, stderr) => error ? reject(error) : resolve({ stdout, stderr })); + }); + const result = JSON.parse(output.stdout); + assert.equal(result.status, 'built'); + assert.match(output.stderr, /Maven build output/); + assert.equal(readFileSync(result.jarPath, 'utf8'), 'built'); + assert.deepEqual(leftovers(), []); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test('the CLI reports a download on stdout for the SessionStart hook and stays silent when nothing was needed', async (t) => { + if (skipWithoutLoopback(t)) return; + const probe = spawnSync(process.execPath, ['-e', ''], { encoding: 'utf8' }); + if (probe.error?.code === 'EPERM') { + t.skip('sandbox denies child process creation'); + return; + } + const env = { ...process.env, SPRING_TOOLS_LS_DOWNLOAD_BASE: base }; + delete env.SPRING_TOOLS_LS_JAR; + // Must stay asynchronous: the mock server lives in this process and has to answer the child. + const run = (args) => new Promise((resolve) => { + execFile(process.execPath, [join(pluginRoot, 'install.js'), ...args], { env, encoding: 'utf8' }, (error, stdout, stderr) => { + resolve({ status: error ? error.code : 0, stdout, stderr }); + }); + }); + const first = await run(['--if-missing', '--dest', dest]); + assert.equal(first.status, 0, first.stderr); + assert.match(first.stdout, /downloaded its language server/); + assert.match(first.stderr, /Installed Spring Boot Language Server/); + const second = await run(['--if-missing', '--dest', dest]); + assert.equal(second.status, 0); + assert.equal(second.stdout, ''); + const unknown = await run(['--bogus']); + assert.equal(unknown.status, 1); + assert.match(unknown.stderr, /unknown argument/); +}); + +test('download URLs follow the CDN layout for releases and snapshots', () => { + assert.equal(downloadUrls('2.5.0', 'https://cdn.spring.io/spring-tools').jarUrl, + `https://cdn.spring.io/spring-tools/release/language-server/spring-boot/2.5.0/${JAR_NAME}`); + assert.equal(downloadUrls('2.5.0-SNAPSHOT', 'https://cdn.spring.io/spring-tools/').jarUrl, + `https://cdn.spring.io/spring-tools/snapshot/language-server/spring-boot/${JAR_NAME}`); + assert.equal(downloadUrls('2.5.0').sha256Url, `${downloadUrls('2.5.0').jarUrl}.sha256`); +}); + +test('negative control: downloads are refused from untrusted hosts and over plain HTTP to non-loopback hosts', () => { + assert.throws(() => assertAllowedUrl('https://evil.example.com/x.jar', 'https://cdn.spring.io/spring-tools'), /untrusted host/); + assert.throws(() => assertAllowedUrl('http://cdn.spring.io/x.jar', 'https://cdn.spring.io/spring-tools'), /insecure/); + assert.throws(() => assertAllowedUrl('http://mirror.example.com/x.jar', 'http://mirror.example.com/spring-tools'), /insecure/); + assert.equal(assertAllowedUrl('https://cdn.spring.io/spring-tools/x.jar', 'https://mirror.example.com/spring-tools').hostname, 'cdn.spring.io'); + assert.equal(assertAllowedUrl('https://mirror.example.com/spring-tools/x.jar', 'https://mirror.example.com/spring-tools').hostname, 'mirror.example.com'); + assert.equal(assertAllowedUrl('http://127.0.0.1:9/x.jar', 'http://127.0.0.1:9/spring-tools').hostname, '127.0.0.1'); +}); + +test('proxy selection follows HTTPS_PROXY, ALL_PROXY and NO_PROXY like curl', () => { + const target = 'https://cdn.spring.io/spring-tools/x.jar'; + assert.equal(proxyFor(target, {}), null); + assert.equal(proxyFor(target, { HTTPS_PROXY: 'http://proxy.example.com:3128' }).href, 'http://proxy.example.com:3128/'); + assert.equal(proxyFor(target, { https_proxy: 'proxy.example.com:3128' }).port, '3128', 'a bare host:port is an http proxy'); + assert.equal(proxyFor(target, { ALL_PROXY: 'http://user:pw@proxy.example.com:8080' }).username, 'user'); + assert.equal(proxyFor(target, { HTTP_PROXY: 'http://proxy.example.com:3128' }), null, 'HTTP_PROXY does not apply to https targets'); + assert.equal(proxyFor(target, { HTTPS_PROXY: 'http://proxy.example.com:3128', NO_PROXY: 'localhost,.spring.io' }), null); + assert.equal(proxyFor(target, { HTTPS_PROXY: 'http://proxy.example.com:3128', no_proxy: '*' }), null); + assert.equal(proxyFor('http://127.0.0.1:8080/x', { HTTP_PROXY: 'http://proxy.example.com:3128' }), null, 'loopback never goes through a proxy'); + assert.throws(() => proxyFor(target, { HTTPS_PROXY: 'socks5://proxy.example.com:1080' }), /only http:\/\/ proxies/); + assert.equal(hostMatchesNoProxy('cdn.spring.io', 'example.com, spring.io:443'), true); + assert.equal(hostMatchesNoProxy('cdn.spring.io', 'notspring.io'), false); +}); + +test('HTTPS requests reuse the established CONNECT tunnel', () => { + const socket = {}; + const agent = createTunnelAgent(socket); + assert.strictEqual(agent.createConnection({}), socket); + agent.destroy(); +}); + +test('recovers immediately when the installer that owns the lock has exited', async (t) => { + if (skipWithoutLoopback(t)) return; + const exited = spawnSync(process.execPath, ['-e', 'process.stdout.write(String(process.pid))'], { encoding: 'utf8' }); + assert.equal(exited.status, 0, exited.stderr); + const deadPid = Number(exited.stdout); + assert.ok(Number.isSafeInteger(deadPid) && deadPid > 0); + + const lockPath = join(dest, `${JAR_NAME}.lock`); + writeFileSync(lockPath, `${deadPid} ${new Date().toISOString()}\n`); + const result = await ensureJar({ pluginRoot, dest, log: quiet }); + + assert.equal(result.status, 'downloaded'); + assert.ok(readFileSync(result.jarPath).equals(jarBytes)); + assert.deepEqual(leftovers(), []); +}); + +after(() => { + rmSync(isolatedRoot, { recursive: true, force: true }); +}); diff --git a/claude-plugins/tools/test/launcher.test.mjs b/claude-plugins/tools/test/launcher.test.mjs new file mode 100644 index 0000000000..7bd7d692a1 --- /dev/null +++ b/claude-plugins/tools/test/launcher.test.mjs @@ -0,0 +1,207 @@ +/******************************************************************************* + * Copyright (c) 2026 Broadcom + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Broadcom - initial API and implementation + *******************************************************************************/ + +// Unit tests for the pure parts of launcher.js (Java selection, JVM arguments). The end-to-end +// behaviour against a real JVM is covered by tools/smoke/mcp-smoke.mjs. + +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, existsSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { test } from 'node:test'; + +const require = createRequire(import.meta.url); +const here = dirname(fileURLToPath(import.meta.url)); +const pluginRoot = join(here, '..', '..', 'spring-tools'); +const launcher = require(join(pluginRoot, 'launcher.js')); +const { defaultInstallDir, pluginVersion } = require(join(pluginRoot, 'install.js')); +const { MIN_JAVA_MAJOR, SERVER_INSTRUCTIONS, serverInstructions, parseJavaMajor, javaCandidates, pickJava, splitOpts, watchEnabled, buildJavaArgs, resolveProjectDir, resolveDataDir } = launcher; + +test('parses the major version from java -version output of old and new JDKs', () => { + assert.equal(parseJavaMajor('openjdk version "21.0.2" 2024-01-16\nOpenJDK Runtime Environment'), 21); + assert.equal(parseJavaMajor('java version "1.8.0_392"\nJava(TM) SE Runtime Environment'), 8); + assert.equal(parseJavaMajor('openjdk version "25" 2025-09-16'), 25); + assert.equal(parseJavaMajor('openjdk version "17.0.10" 2024-01-16 LTS'), 17); + assert.equal(parseJavaMajor(''), null); + assert.equal(parseJavaMajor('bash: java: command not found'), null); +}); + +test('persistent data directory prefers explicit and host-provided locations then falls back to the user home', () => { + assert.equal(resolveDataDir({ env: { SPRING_TOOLS_DATA_DIR: '/custom/data', CLAUDE_PLUGIN_DATA: '/claude' }, home: '/home/test' }), '/custom/data'); + assert.equal(resolveDataDir({ env: { CLAUDE_PLUGIN_DATA: '/claude', PLUGIN_DATA: '/plugin' }, home: '/home/test' }), '/claude'); + assert.equal(resolveDataDir({ env: { PLUGIN_DATA: '/plugin' }, home: '/home/test' }), '/plugin'); + assert.equal(resolveDataDir({ env: { SPRING_TOOLS_DATA_DIR: 'relative/data' }, home: '/home/test' }), join(process.cwd(), 'relative/data')); + assert.equal(resolveDataDir({ env: {}, home: '/home/test' }), '/home/test/.spring-tools/data'); +}); + +test('language server JAR is resolved under persistent data rather than the plugin installation', () => { + const dataDir = resolveDataDir({ env: { PLUGIN_DATA: '/client/data' }, home: '/home/test' }); + assert.equal(defaultInstallDir(pluginRoot, { PLUGIN_DATA: '/client/data' }, '/home/test'), join(dataDir, 'language-server', pluginVersion(pluginRoot))); +}); + +test('candidates are tried most specific first: SPRING_TOOLS_JAVA, JAVA_HOME, then PATH', () => { + const all = javaCandidates({ SPRING_TOOLS_JAVA: '/opt/jdk/bin/java', JAVA_HOME: '/usr/lib/jvm/17' }, 'linux'); + assert.deepEqual(all.map((c) => c.source), ['SPRING_TOOLS_JAVA', 'JAVA_HOME', 'PATH']); + assert.equal(all[1].java, join('/usr/lib/jvm/17', 'bin', 'java')); + assert.deepEqual(javaCandidates({}, 'linux').map((c) => c.java), ['java']); + assert.ok(javaCandidates({ JAVA_HOME: 'C:\\jdk' }, 'win32')[0].java.endsWith('java.exe')); +}); + +test('picks the first candidate that is Java 21 or newer and skips older or broken ones', () => { + const versions = { '/old/bin/java': 'openjdk version "17.0.10"', java: 'openjdk version "21.0.2"', '/new/bin/java': 'openjdk version "25"' }; + const probe = (java) => (java in versions ? { output: versions[java] } : { output: '', error: 'ENOENT' }); + const picked = pickJava(javaCandidates({ JAVA_HOME: '/old', SPRING_TOOLS_JAVA: '/missing/java' }, 'linux'), probe); + assert.equal(picked.java, 'java'); + assert.equal(picked.major, 21); + assert.deepEqual(picked.tried.map((t) => [t.source, t.major, t.error ?? null]), [ + ['SPRING_TOOLS_JAVA', null, 'ENOENT'], + ['JAVA_HOME', 17, null], + ['PATH', 21, null], + ]); + assert.equal(pickJava(javaCandidates({ SPRING_TOOLS_JAVA: '/new/bin/java' }, 'linux'), probe).major, 25); +}); + +test('negative control: no usable Java yields no pick but a full record of what was tried', () => { + const picked = pickJava(javaCandidates({ JAVA_HOME: '/old' }, 'linux'), () => ({ output: 'openjdk version "17.0.1"' })); + assert.equal(picked.java, null); + assert.equal(picked.tried.length, 2); + assert.ok(picked.tried.every((t) => t.major === 17 && t.major < MIN_JAVA_MAJOR)); +}); + +test('splits SPRING_TOOLS_JAVA_OPTS like a shell would', () => { + assert.deepEqual(splitOpts(undefined), []); + assert.deepEqual(splitOpts(' -Xmx2g -XX:+UseZGC '), ['-Xmx2g', '-XX:+UseZGC']); + assert.deepEqual(splitOpts('-Dfoo="a b" -Dbar=\'c d\''), ['-Dfoo=a b', '-Dbar=c d']); +}); + +test('JVM arguments put user options after the defaults so they win, and end with -jar ', () => { + const args = buildJavaArgs({ jarPath: '/p/ls.jar', dataDir: '/data', projectDir: '/proj', extraOpts: ['-Xmx2g'] }); + assert.ok(args.indexOf('-Xmx1024m') < args.indexOf('-Xmx2g')); + assert.deepEqual(args.slice(-2), ['-jar', '/p/ls.jar']); + assert.ok(args.includes('-Dspring.ai.mcp.server.stdio=true')); + assert.ok(args.includes('-Dlanguageserver.enabled=false')); + assert.ok(args.includes('-Dspring.boot.ls.project.dir=/proj')); + assert.ok(args.includes(`-Dlogging.file.name=${join('/data', 'boot-ls.log')}`)); + assert.ok(args.includes(`-Dspring.ai.mcp.server.instructions=${serverInstructions()}`)); +}); + +test('the file watcher is on by default and SPRING_TOOLS_LS_WATCH=false turns it off', () => { + const base = { jarPath: '/p/ls.jar', dataDir: '/data', projectDir: '/proj' }; + assert.ok(buildJavaArgs(base).includes('-Dspring.boot.ls.project.watch=true')); + assert.ok(buildJavaArgs({ ...base, watch: false }).includes('-Dspring.boot.ls.project.watch=false')); + for (const value of [undefined, '', 'true', 'yes', '1']) { + assert.equal(watchEnabled(value), true, `watchEnabled(${JSON.stringify(value)})`); + } + for (const value of ['false', 'FALSE', ' 0 ', 'no', 'off']) { + assert.equal(watchEnabled(value), false, `watchEnabled(${JSON.stringify(value)})`); + } + // The property must precede user options so SPRING_TOOLS_JAVA_OPTS can still override it. + const args = buildJavaArgs({ ...base, extraOpts: ['-Dspring.boot.ls.project.watch=false'] }); + assert.ok(args.indexOf('-Dspring.boot.ls.project.watch=true') < args.lastIndexOf('-Dspring.boot.ls.project.watch=false')); +}); + +test('server instructions name entry-point tools, use host-neutral skill guidance, and stay under 2 KB', () => { + for (const tool of ['getProjectList', 'getProjectDiagnostics', 'fileChanged', 'refreshWorkspace', 'getBeanDetails', 'getRequestMappings']) { + assert.ok(SERVER_INSTRUCTIONS.includes(tool), `${tool} should be mentioned`); + } + // Each host-neutral skill name must map to an installed skill in this package. + for (const skill of ['quickfix', 'validate']) { + assert.ok(existsSync(join(pluginRoot, 'skills', skill, 'SKILL.md')), `skill ${skill} referenced by the instructions is missing`); + } + assert.ok(SERVER_INSTRUCTIONS.includes('watches'), 'clients should know they need not notify the server about every edit'); + assert.ok(!SERVER_INSTRUCTIONS.includes('/spring-tools:'), 'host-specific slash invocations do not work on every client'); + assert.ok(SERVER_INSTRUCTIONS.includes('explanations/.md')); + assert.ok(Buffer.byteLength(SERVER_INSTRUCTIONS, 'utf8') < 2048); + assert.ok(!/["\n]/.test(SERVER_INSTRUCTIONS), 'quotes and newlines would complicate argv quoting on Windows'); +}); + +test('the instructions carry the absolute playbook directory for clients that do not expand path placeholders', () => { + const instructions = serverInstructions('/plugins/spring-tools'); + assert.ok(instructions.startsWith(SERVER_INSTRUCTIONS)); + assert.ok(instructions.includes(join('/plugins/spring-tools', 'explanations'))); + assert.ok(instructions.includes('.md')); + assert.ok(Buffer.byteLength(serverInstructions(pluginRoot), 'utf8') < 2048); + assert.ok(!/["\n]/.test(instructions)); + // The directory must really exist, otherwise every client is pointed at a dangling path. + assert.ok(existsSync(join(pluginRoot, 'explanations'))); +}); + +test('the project directory falls back from the explicit override down to the Copilot session state', () => { + const root = mkdtempSync(join(tmpdir(), 'spring-tools-projectdir-')); + try { + const plugin = join(root, 'plugin'); + const workspace = join(root, 'workspace'); + const other = join(root, 'other'); + const home = join(root, 'home'); + const session = join(home, '.copilot', 'session-state', 'sess-1'); + for (const dir of [plugin, workspace, other, session]) { + mkdirSync(dir, { recursive: true }); + } + writeFileSync(join(session, 'workspace.yaml'), `version: 1\ncwd: ${workspace}\nmodel: gpt\n`); + const resolve = (env, cwd) => resolveProjectDir({ env, cwd, pluginRoot: plugin, home }); + + // An explicit override always wins, even over a perfectly good working directory. + assert.deepEqual(resolve({ SPRING_TOOLS_PROJECT_DIR: other, CLAUDE_PROJECT_DIR: workspace }, workspace), { dir: other, source: 'SPRING_TOOLS_PROJECT_DIR', detected: true }); + // Claude Code exports the project directory; Copilot does not but starts the server in the plugin. + assert.deepEqual(resolve({ CLAUDE_PROJECT_DIR: workspace }, plugin), { dir: workspace, source: 'CLAUDE_PROJECT_DIR', detected: true }); + assert.deepEqual(resolve({}, workspace), { dir: workspace, source: 'working directory', detected: true }); + assert.deepEqual(resolve({ COPILOT_AGENT_SESSION_ID: 'sess-1' }, plugin), { dir: workspace, source: 'Copilot session state', detected: true }); + assert.deepEqual(resolve({ PWD: workspace }, plugin), { dir: workspace, source: 'PWD', detected: true }); + + assert.throws(() => resolve({ SPRING_TOOLS_PROJECT_DIR: join(root, 'gone'), PWD: workspace }, plugin), /SPRING_TOOLS_PROJECT_DIR is not an existing directory/); + + // Nothing usable: never index the plugin itself, and say that the detection failed. + assert.deepEqual(resolve({ CLAUDE_PROJECT_DIR: join(root, 'gone'), PWD: plugin, COPILOT_AGENT_SESSION_ID: 'nope' }, plugin), { dir: plugin, source: 'working directory', detected: false }); + // A session id must not be able to escape the session-state directory. + assert.equal(resolve({ COPILOT_AGENT_SESSION_ID: '../../..' }, plugin).detected, false); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test('the launcher fails fast with an actionable message when no Java 21+ runtime is available', (t) => { + const emptyBin = mkdtempSync(join(tmpdir(), 'spring-tools-nojava-')); + try { + const result = spawnSync(process.execPath, [join(pluginRoot, 'launcher.js')], { + encoding: 'utf8', + timeout: 30000, + env: { PATH: emptyBin, HOME: emptyBin, CLAUDE_PROJECT_DIR: emptyBin, CLAUDE_PLUGIN_DATA: emptyBin }, + }); + if (result.error?.code === 'EPERM') { + t.skip('sandbox denies child process creation'); + return; + } + assert.equal(result.status, 1); + assert.match(result.stderr, /No Java 21\+ runtime found/); + assert.match(result.stderr, /JAVA_HOME or SPRING_TOOLS_JAVA/); + assert.equal(result.stdout, '', 'stdout is the MCP channel and must stay silent'); + } finally { + rmSync(emptyBin, { recursive: true, force: true }); + } +}); + + +test('a cached plugin without a workspace exits before downloading and keeps MCP stdout clean', () => { + const result = spawnSync(process.execPath, [join(pluginRoot, 'launcher.js')], { + cwd: pluginRoot, + encoding: 'utf8', + timeout: 10000, + env: { PATH: process.env.PATH, PWD: pluginRoot }, + }); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /refusing to index the plugin directory/); + assert.match(result.stderr, /SPRING_TOOLS_PROJECT_DIR/); + assert.equal(result.stdout, ''); + assert.doesNotMatch(result.stderr, /Downloading/); +}); diff --git a/nohttp-whitelist.txt b/nohttp-whitelist.txt index d48974db18..3155fc0645 100644 --- a/nohttp-whitelist.txt +++ b/nohttp-whitelist.txt @@ -2,3 +2,4 @@ http://timestamp\.digicert\.com http://sha256timestamp\.ws\.symantec\.com/sha256/timestamp http://org\.eclipse\.ui\.intro/.* http://spring\.io/ +http://cdn\.spring\.io/x\.jar