jetbrains-index-mcp-plugin
CLAUDE.md375 starsChanged 4 months agoMITView on GitHub
An IntelliJ Platform plugin that exposes an MCP (Model Context Protocol) server, enabling coding agents to leverage the IDE's powerful indexing and refactoring capabilities. Works with JetBrains IDEs: IntelliJ IDEA, PyCharm, WebStorm, GoLand, PhpStorm, RubyMine, CLion, RustRover, DataGrip, and Android Studio.
In this repositoryOne other file it gives its agents.
- AGENTS.mdAGENTS.md
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
22 rules. About 0 are common, 11 are distinctive, and 11 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈11
Distinctive · estimate
This author's own choices. Worth a look.
11
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 10
Create an MCP server within an IntelliJ plugin that allows AI coding assistants to:
- Distinctive: line 15
Use code completion and inspection APIs
- Distinctive: line 235
Use Kotlin idioms (data classes, extension functions, coroutines where appropriate)
- Very specific: line 237
Use @RequiresBackgroundThread / @RequiresReadLock annotations where needed
- Very specific: line 240
Always check DumbService.isDumb() before accessing indexes
- Very specific: line 241
Use ReadAction / WriteAction for PSI modifications
- Very specific: line 243
Use ApplicationManager.getApplication().invokeLater() for UI updates
- Distinctive: line 249
When files are modified externally (e.g., by AI coding tools), PSI may not immediately reflect the changes.
- Very specific: line 252
Solution: When the "Sync external file changes" setting is enabled, AbstractMcpTool refreshes the VFS and commits documents before …
- Distinctive: line 260
Write tools do not depend on this setting: single-file edits reload their target file, and refactorings load external changes across the …
- Very specific: line 315
Add the tool to McpToolDispatcher.LONG_POLL_TOOLS so the dispatcher does not impose the ordinary 55-second deadline.
- Distinctive: line 318
Follow Kotlin coding conventions
- Distinctive: line 319
Use meaningful variable names
- Distinctive: line 320
Keep functions small and focused
- Very specific: line 325
All tool input schemas MUST use SchemaBuilder (in tools/schema/SchemaBuilder.kt).
- Distinctive: line 362
Run Verifications: - Run compatibility checks
- Very specific: line 372
Add to gradle/libs.versions.toml for version catalog
- Very specific: line 657
Check for cursor parameter → serve from cache via getPageFromCache()
- Very specific: line 698
Do not mix target with top-level selectors.
- Very specific: line 731
All search operations use the Processor pattern for efficient streaming and early termination:
- Distinctive: line 789
Read it before writing a single line of code.
- Distinctive: line 791
Before pushing, run the pre-push validation script to catch common mistakes automatically:
≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
IDE Index MCP Server - Development Guide
An IntelliJ Platform plugin that exposes an MCP (Model Context Protocol) server, enabling coding agents to leverage the IDE's powerful indexing and refactoring capabilities.
Works with JetBrains IDEs: IntelliJ IDEA, PyCharm, WebStorm, GoLand, PhpStorm, RubyMine, CLion, RustRover, DataGrip, and Android Studio.
Project Overview
Goal
Create an MCP server within an IntelliJ plugin that allows AI coding assistants to:
- Perform refactoring operations (rename, extract, move, etc.)
- Query type hierarchy and call hierarchy
- Access code navigation features (find usages, find definition)
- Leverage IDE indexes for fast code search and analysis
- Use code completion and inspection APIs
Technology Stack
- Language: Kotlin (JVM 21)
- Build System: Gradle 9.0 with Kotlin DSL
- IDE Platform: IntelliJ Platform 2025.3+ (
pluginSinceBuild = 253; builds against IntelliJ IDEA Ultimate (IU) — IC is not published for 2025.3+) - HTTP Server: Ktor CIO 3.2.3 (embedded, configurable port)
- Protocol: Model Context Protocol via the official MCP Kotlin SDK (
io.modelcontextprotocol:kotlin-sdk-server). Negotiates 2024-11-05 … 2025-11-25.
Key Documentation
IntelliJ Platform SDK
- Main Documentation: https://plugins.jetbrains.com/docs/intellij/welcome.html
- PSI (Program Structure Interface): https://plugins.jetbrains.com/docs/intellij/psi.html
- Indexing and PSI Stubs: https://plugins.jetbrains.com/docs/intellij/indexing-and-psi-stubs.html
- Rename Refactoring: https://plugins.jetbrains.com/docs/intellij/rename-refactoring.html
- Modifying the PSI: https://plugins.jetbrains.com/docs/intellij/modifying-psi.html
- Plugin Configuration: https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html
- Explore API: https://plugins.jetbrains.com/docs/intellij/explore-api.html
Model Context Protocol (MCP)
- Specification: https://spec.modelcontextprotocol.io/specification/2025-03-26/
- Tools API: https://modelcontextprotocol.io/specification/2025-03-26/server/tools
- Resources API: https://modelcontextprotocol.io/specification/2025-03-26/server/resources
- Legacy SSE Transport: https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/
- GitHub: https://github.com/modelcontextprotocol/modelcontextprotocol
Project Structure
src/
├── main/
│ ├── kotlin/com/github/hechtcarmel/jetbrainsindexmcpplugin/
│ │ ├── McpBundle.kt # Resource bundle accessor
│ │ ├── actions/ # IDE actions
│ │ ├── constants/ToolNames.kt # All tool name constants + ALL list
│ │ ├── exceptions/ # Plugin exception types
│ │ ├── handlers/ # Language-specific handlers
│ │ │ ├── LanguageHandler.kt # Handler interfaces & data classes
│ │ │ ├── LanguageHandlerRegistry.kt # Data-driven handler registry
│ │ │ ├── OptimizedSymbolSearch.kt # Symbol search using platform APIs
│ │ │ ├── java/JavaHandlers.kt # Java/Kotlin handlers
│ │ │ ├── python/PythonHandlers.kt # Python handlers (reflection)
│ │ │ ├── javascript/JavaScriptHandlers.kt # JS/TS handlers (reflection)
│ │ │ ├── go/GoHandlers.kt # Go handlers (reflection)
│ │ │ ├── php/PhpHandlers.kt # PHP handlers (reflection)
│ │ │ ├── rust/RustHandlers.kt # Rust handlers (reflection)
│ │ │ └── markdown/MarkdownHandlers.kt # Markdown handlers
│ │ ├── history/ # Per-project command history (bounded ring buffer)
│ │ ├── icons/ # Plugin icons
│ │ ├── lifecycle/ # ProjectModeService, LifecycleEventLog, focus tracking
│ │ ├── server/ # MCP server infrastructure
│ │ │ ├── McpServerService.kt # App-level service managing server lifecycle
│ │ │ ├── ProjectResolver.kt # Multi-project resolution with workspace support
│ │ │ ├── PaginationService.kt # Cursor cache for paginated search tools
│ │ │ ├── BuildDiagnosticsCacheService.kt # Cached build output for ide_diagnostics
│ │ │ ├── mcp/ # Bridge from the tool registry to the MCP SDK
│ │ │ │ ├── McpServerFactory.kt # Builds an SDK `Server` per connection
│ │ │ │ └── McpToolDispatcher.kt # Settings gate, project resolution, history, modality
│ │ │ └── transport/ # HTTP transport layer
│ │ │ ├── KtorMcpServer.kt # Embedded Ktor CIO server + SDK route wiring
│ │ │ ├── LegacySseRoutes.kt # 2024-11-05 HTTP+SSE endpoints
│ │ │ ├── LocalOriginGuard.kt # Loopback Origin/Host validation + CORS
│ │ ├── settings/ # McpSettings (app-level persisted state) + settings UI
│ │ ├── startup/ # Startup activities
│ │ ├── tools/ # MCP tool implementations
│ │ │ ├── McpTool.kt # Tool interface
│ │ │ ├── AbstractMcpTool.kt # Base class (PSI sync, threading, helpers)
│ │ │ ├── ToolRegistry.kt # Data-driven tool registry
│ │ │ ├── schema/ # Tool schema utilities
│ │ │ │ └── SchemaBuilder.kt # Fluent builder for input schemas
│ │ │ ├── editor/ # Editor interaction tools
│ │ │ ├── navigation/ # Navigation tools (multi-language)
│ │ │ ├── intelligence/ # Code analysis tools
│ │ │ ├── lifecycle/ # Lifecycle management tools
│ │ │ ├── models/ # Shared result models
│ │ │ ├── project/ # Project status tools
│ │ │ └── refactoring/ # Refactoring tools
│ │ ├── util/ # Utilities
│ │ │ ├── PluginDetector.kt # Generic plugin availability detector
│ │ │ ├── PluginDetectors.kt # Registry of all language detectors
│ │ │ ├── ClassResolver.kt # Class lookup by FQN (Java, PHP)
│ │ │ ├── ProjectUtils.kt # Project/workspace helpers
│ │ │ ├── PsiUtils.kt # PSI navigation helpers
│ │ │ ├── SymbolSignature.kt # Signature resolution strategy + result holder
│ │ │ ├── JavaSignatureExtractor.kt # FQN-resolved signatures from Java PSI
│ │ │ ├── SymbolDocumentation.kt # Quick-doc / doc-comment text as plain text
│ │ │ └── ThreadingUtils.kt # Threading utilities
│ │ └── ui/ # Tool window UI
│ └── resources/
│ ├── META-INF/
│ │ ├── plugin.xml # Plugin configuration
│ │ └── *-features.xml # Optional language-specific extensions
│ └── messages/McpBundle.properties # i18n messages
└── test/
├── kotlin/ # Test sources
└── testData/ # Test fixturesArchitecture Concepts
IntelliJ Platform Key Components
- PSI (Program Structure Interface)
- Core abstraction for parsing and representing code structure
PsiFile,PsiElement,PsiClass,PsiMethod, etc.PsiNamedElementfor elements that can be renamed/referenced
- Indexes
DumbService- query if IDE is in dumb mode (indexing) vs smart mode- File-based indexes for fast lookups
- PSI stubs for lightweight syntax trees
- Refactoring APIs
RenameHandler- custom rename UI/workflowPsiNamedElement.setName()- rename elementPsiReference.handleElementRename()- update references
- Services
- Application-level services (singleton across IDE)
- Project-level services (one per open project)
Workspace / Multi-Module Project Support
The plugin supports workspace projects where a single IDE window contains multiple sub-projects represented as modules with separate content roots:
- Project resolution (
ProjectResolver.resolve): Checks exact basePath → exact module content root → basePath subdirectory → module content-root subdirectory (longest root wins) - File resolution (
AbstractMcpTool.resolveFile): Tries basePath first (wins unconditionally), then module content roots (fails withAmbiguousFileExceptionif multiple roots match) - Reported paths (
ProjectUtils.getRelativePath): Relative to basePath for files under it; absolute for everything else, including files in content roots outside basePath (issue #441). Never strip a content root: every Maven module would reduce to the samesrc/main/....pathsglobs match the same names (PathGlobScope.matchingForm), so an absolute glob selects one workspace repository - VFS/PSI sync (
AbstractMcpTool.ensurePsiUpToDate): Refreshes all content roots, not just basePath - Error responses:
available_projectsdetail is configurable. Expanded mode includes workspace sub-projects with theirworkspaceparent name; compact mode returns only top-level project roots.
Key utility: ProjectUtils.getModuleContentRoots(project) returns all module content root paths.
MCP Server Architecture
MCP servers expose:
- Tools - Operations that can be invoked (e.g.,
rename_symbol,find_usages) - Prompts - Pre-defined interaction templates (optional)
Server Infrastructure:
- Custom embedded Ktor CIO HTTP server (not IntelliJ's built-in server)
- Configurable port with IDE-specific defaults (e.g., IntelliJ: 29170, PyCharm: 29172) via Settings → Tools → Index MCP Server → Server Port
- Binds to
127.0.0.1only (localhost) for security - Single server instance across all open projects
- Auto-restart on port change
Key Server Classes:
McpServerService- Application-level service managing server lifecycleKtorMcpServer- Embedded Ktor CIO engine; installs ContentNegotiation, the origin guard, and the SDK's route helpers. Owns no protocol logic.McpServerFactory- TurnsToolRegistryinto an SDKServer. A fresh server per connection, so toggling a tool in Settings takes effect on the nexttools/list— and so the per-request session does not accumulate. Stateless Streamable HTTP never closes what it creates, soKtorMcpServercloses each server when the HTTP call completes (StatelessServerLifecycleTestguards this).McpToolDispatcher- Everything between "client asked for tool X" and the tool running: enabled/disabled gate,project_pathresolution, command history, and the IDE modality context thatcommitAllDocumentsrequires.LocalOriginGuard- Loopback Origin/Host validation and CORS. Deliberately not the SDK'sDnsRebindingProtection: that implementation comparesHostincluding the port and rejects requests with noOriginheader at all, which would break curl and several clients.
What the SDK owns: JSON-RPC framing and error codes, initialize and protocol-version
negotiation, ping, tools/list, tools/call dispatch, SSE framing, session ids, batching.
Version pinning: mcpKotlinSdk and ktor in gradle/libs.versions.toml must stay within
the Kotlin generation the target IDE ships (2.2.x for 2025.3). kotlin-sdk 0.11.0+ is built
against Kotlin 2.3 and fails to compile against this platform. See the comment in the catalog.
Transport: This plugin supports two transports with JSON-RPC 2.0. Both require
Accept: application/json, text/event-stream and Content-Type: application/json on POSTs, as
the Streamable HTTP spec mandates:
Streamable HTTP (Primary, MCP 2025-03-26):
POST /index-mcp/streamable-http→ Stateless JSON-RPC requests/responsesGET /index-mcp/streamable-http→ 405 Method Not AllowedDELETE /index-mcp/streamable-http→ 405 Method Not Allowed
Legacy SSE (MCP 2024-11-05):
GET /index-mcp/sse→ Opens SSE stream, sendsendpointevent with POST URLPOST /index-mcp→ JSON-RPC requests/responses
Client Configuration (Cursor, Claude Desktop, etc.):
{
"mcpServers": {
"intellij-index": {
"url": "http://127.0.0.1:29170/index-mcp/streamable-http"
}
}
}Note: Server name and port are IDE-specific. Use the "Install on Coding Agents" button for automatic configuration.
Port Configuration: Settings → Tools → Index MCP Server → Server Port (IDE-specific defaults, range: 1024-65535)
IDE-Specific Defaults:
| IDE | Server Name | Default Port |
| IntelliJ IDEA | intellij-index | 29170 |
| Android Studio | android-studio-index | 29171 |
| PyCharm | pycharm-index | 29172 |
| WebStorm | webstorm-index | 29173 |
| GoLand | goland-index | 29174 |
| PhpStorm | phpstorm-index | 29175 |
| RubyMine | rubymine-index | 29176 |
| CLion | clion-index | 29177 |
| RustRover | rustrover-index | 29178 |
| DataGrip | datagrip-index | 29179 |
| Aqua | aqua-index | 29180 |
| DataSpell | dataspell-index | 29181 |
Development Guidelines
Kotlin Standards
- Use Kotlin idioms (data classes, extension functions, coroutines where appropriate)
- Leverage null safety features
- Use
@RequiresBackgroundThread/@RequiresReadLockannotations where needed
IntelliJ Platform Best Practices
- Always check
DumbService.isDumb()before accessing indexes - Use
ReadAction/WriteActionfor PSI modifications - Register extensions in
plugin.xml, not programmatically - Use
ApplicationManager.getApplication().invokeLater()for UI updates - Handle threading correctly (read actions on background threads, write actions on EDT)
PSI-Document Synchronization
The IntelliJ Platform maintains separate Document (text) and PSI (parsed structure) layers. When files are modified externally (e.g., by AI coding tools), PSI may not immediately reflect the changes. This can cause search APIs to miss references in newly created files.
Solution: When the "Sync external file changes" setting is enabled, AbstractMcpTool
refreshes the VFS and commits documents before executing any PSI-dependent tool, so PSI is
synchronized with external file changes. The setting is disabled by default.
User Setting: "Sync external file changes before operations" (Settings → Tools → Index MCP Server)
- Disabled (default): Best performance, suitable for most use cases
- Enabled: WARNING - SIGNIFICANT PERFORMANCE IMPACT. Use only when read-only tools (find-usages, search, navigation) miss references in files just changed externally. Each operation will take seconds instead of milliseconds on large repos.
Write tools do not depend on this setting: single-file edits reload their target file, and refactorings load external changes across the project before they run (see below).
For tool developers:
- Extend
AbstractMcpTooland implementdoExecute()(notexecute()) - PSI synchronization happens automatically before
doExecute()is called when the setting is enabled and the tool hasrequiresPsiSync = true - To opt-out (for tools that don't use PSI), override:
override val requiresPsiSync: Boolean = false - For per-call opt-out (e.g. long-poll attach calls that touch no PSI), override
needsPsiSync(arguments)instead. - A tool that edits one file's Document must call
syncFileForEdit(project, file)before it resolves PSI or computes offsets in that file, and apply the edit withsuspendingWriteActionAndSave(project, name, document) { ... }. Without the first, the edit lands on a stale Document whenever another program changed the file since the IDE's last VFS refresh. Without the second,FileDocumentManagerthen declines the save as a memory/disk conflict without reporting it, and the tool claims success for a file that never changed (issue #430). - A multi-file refactoring must call
syncProjectForRefactoring(project)before it resolves its target (apply paths only; a dry run must not save documents). CaptureFileDocumentManager.unsavedDocumentsjust before the processor runs, then save withsaveChangedDocuments(project, unsavedBefore)in place ofsaveAllDocuments(), and turn a non-empty result into an error withchangesNotSavedMessage.
Long-Running Tools (Long-Poll Pattern)
MCP clients enforce their own request timeout (60s by default in Claude Code / the MCP TypeScript SDK), and the stateless Streamable HTTP transport cannot send keep-alive progress notifications (kotlin-sdk 0.10.0 drops them in JSON response mode). No tool call may ever block past ~45–55s — a longer operation must long-poll (issue #277).
McpToolDispatcher gives ordinary tool execution a 55-second coroutine deadline and reports
expiry as an actionable tool error. The three long-poll tools retain their own budgets so their
operation IDs are not lost. Cancellation remains cooperative: use cancellable EDT dispatch and
cancellableBlockingAction for interruptible blocking analysis with a platform progress indicator.
An already-running write is not rolled back on timeout; callers must inspect it before retrying.
Shared infrastructure (used by ide_run_tests, ide_build_project, and ide_project_diagnostics):
tools/LongPoll.kt— the per-call wait-budget policy:waitSecondsparameter, default 45, ceiling 55.tools/project/LongPollRegistry.kt—LongPollOperation+LongPollRegistry: watchdog that enforces the operation deadline even when nobody polls, retention-based eviction (30 min), exactly-once cleanup, andawaitWithinBudget(completed result beats a stale timeout verdict, which beats waiting).
A new long-running tool plugs in with four pieces:
- An operation class extending
LongPollOperation— payload plusdeadlineMs/onDeadline(kill, or nothing) /onCleanup(disconnect, dispose) hooks. - A project-level
@Serviceregistry extendingLongPollRegistry<YourOp>(a few lines; seeActiveTestRunRegistry/ActiveBuildRegistry). - A poll parameter (
runId/buildId/ …): the start path registers the operation and both paths callawaitWithinBudget, returning either the tool's normal result (thenregistry.remove(id)) or an in-progress model (status: "running"+ the id + an actionable poll instruction). OverrideneedsPsiSync(arguments)to skip PSI sync on attach calls. - Add the tool to
McpToolDispatcher.LONG_POLL_TOOLSso the dispatcher does not impose the ordinary 55-second deadline.
Code Style
- Follow Kotlin coding conventions
- Use meaningful variable names
- Keep functions small and focused
- Extract reusable logic to utility classes
Tool Schema Guidelines
All tool input schemas MUST use SchemaBuilder (in tools/schema/SchemaBuilder.kt). This eliminates boilerplate and ensures consistency:
// ✓ Use SchemaBuilder for all tool schemas
override val inputSchema = SchemaBuilder.tool()
.projectPath()
.file()
.lineAndColumn()
.intProperty("maxResults", "Maximum results to return. Default: 100, max: 500.")
.build()
// For enum parameters:
.enumProperty("matchMode", "How to match the query.", listOf("substring", "prefix", "exact"))
// For complex properties that don't fit the builder, use the escape hatch:
.property("target_type", buildJsonObject { /* custom schema */ })Building and Running
# Build the plugin
./gradlew build
# Run IDE with plugin installed
./gradlew runIde
# Run tests (see the Testing section for the -Ptier split)
./gradlew test
# Run plugin verification
./gradlew verifyPluginRun Configurations (in .run/)
- Run Plugin - Launch IDE with plugin for manual testing
- Run Tests - Execute unit tests
- Run Verifications - Run compatibility checks
Plugin Configuration
Key files:
gradle.properties- Plugin metadata (version, IDs, platform version)plugin.xml- Extension points and dependenciesbuild.gradle.kts- Build configuration
Adding Dependencies
- Add to
gradle/libs.versions.tomlfor version catalog - Reference in
build.gradle.ktsusinglibs.xxxsyntax
Adding Extension Points
Register in plugin.xml:
<extensions defaultExtensionNs="com.intellij">
<your.extension implementation="com.your.ImplementationClass"/>
</extensions>Testing
Running Tests
# Everything (~40s locally). Safe to run — see "On running platform tests" below.
./gradlew test
# Fast tier only: headless, no IntelliJ Platform (~20s)
./gradlew test -Ptier=unit
# Platform tier only: BasePlatformTestCase fixtures with real indexing
./gradlew test -Ptier=platform
# One class
./gradlew test --tests "ToolManifestContractUnitTest"-Ptier exists because Gradle's --tests flag has no negation operator and OR-combines
repeated occurrences. The command this file used to document —
--tests "*Test" --tests "!*UnitTest*" — silently selected the entire suite: *Test already
matches every *UnitTest class, and !*UnitTest* is a literal pattern matching nothing. Do not
reintroduce it.
On running platform tests locally: you can. Earlier revisions of this file claimed they
"hang on headless machines"; that was never substantiated. The full suite, platform tests
included, runs locally in about 40 seconds, and CI runs ./gradlew check on ubuntu-latest
with no xvfb and no DISPLAY.
Test Architecture
Three tiers, selected by class-name suffix:
- Contract tests (
contract/*UnitTest.kt) — extendjunit.framework.TestCaseToolManifestContractUnitTestsnapshots each tool's name, description and complete input schema intosrc/test/resources/contract/tool-manifest.json. This is the regression net for large refactors: one assertion covers every registered tool × every schema property, so a droppedregister(...)call or a mutated parameter type fails here instead of shipping. Scope: 49 of the 52 tools inToolNames.ALL(the three needing the Kotlin or Maven plugin are covered by set-equality instead), and inputs only.ResultShapeContractUnitTestsnapshots the other half of the client contract — the response side — intosrc/test/resources/contract/result-shapes.txt: the wire key set, JSON value kind, nullability and optionality of all 66 serializable result models, every enum's wire values, and theUsageTypesliterals. Result models use plain Kotlin property names as their wire keys, so renamingUsageLocation.fileto.pathis a source-compatible refactor that breaks every MCP client; this is what turns red.TestTierConventionUnitTestenforces that no*UnitTestextendsBasePlatformTestCase.PluginDetectorLeakUnitTestenforces that no test-tree class impersonates a language plugin viaPluginDetector'sClass.forNamefallback.
- Unit tests (
*UnitTest.kt) — extendjunit.framework.TestCase- Headless. Serialization decisions, schema semantics, pure logic, registries.
- Platform tests (
*Test.kt,*BehaviorTest.kt,*IntegrationTest.kt)- Anything needing
project, PSI, indexes, or end-to-end tool execution. - New ones should extend
McpPlatformTestCase; older ones still extendBasePlatformTestCasedirectly and are migrated as they are touched.
- Anything needing
Changing a golden file is sometimes correct, but must always be deliberate:
./gradlew test -Ptier=unit --tests "*ToolManifestContractUnitTest" -Dcontract.update=true
./gradlew test -Ptier=unit --tests "*ResultShapeContractUnitTest" -Dcontract.update=trueReview the resulting diff as part of the change — for the result shapes it is the list of breaking changes the release notes owe clients.
Both commands intentionally exit non-zero after writing the golden file, so BUILD FAILED
there is expected. Re-run without the flag to confirm green.
Test-only platform dependencies
build.gradle.kts declares two things purely so tests can run; neither affects the shipped
plugin:
testFramework(TestFrameworkType.Plugin.Java)— Java test-framework classes.testBundledPlugin("JUnit")— without itTestFramework.EXTENSION_NAME.extensionListis empty (the Java plugin declares that extension point but ships no implementations), soide_list_testscould only ever answer "No test frameworks are registered" and would be untestable.
-PkotlinPluginTests=true additionally loads the bundled Kotlin plugin and the sources under
src/kotlinPluginTest/kotlin, including KotlinReplaceMemberFormattingBehaviorTest,
KotlinRenameBaseBehaviorTest,
KotlinChangeSignatureBehaviorTest, and the safe-delete parameter, qualified-target, and
synthetic-target behavior tests. The plugin's newer metadata is excluded from test compilation;
the test runtime uses the IDE's matching stdlib.
gradle.properties also adds JavaScript to platformBundledPlugins. That one is not
test-only in form — it is a compile/test classpath entry — but it does not change what the plugin
requires at runtime: plugin.xml already declared <depends optional="true">JavaScript</depends>.
Without it, 30 JS/TS tests silently pass while executing nothing.
Writing platform tests
Extend McpPlatformTestCase (src/test/kotlin/.../testutil/McpPlatformTestCase.kt). It provides
writeProjectFile, readProjectFileVfs, registerSourceRoot, assertToolSucceeded,
assertRenamedInFile, and friends.
Never use myFixture.addFileToProject for a fixture a tool must resolve from a path
argument. It writes into IntelliJ's in-memory TempFileSystem (temp:///src/...), but every
production entry point that turns a tool argument into a VirtualFile —
AbstractMcpTool.resolveFile, PsiUtils, the JS/TS symbol resolver — goes through
LocalFileSystem, which cannot see temp:// files. The tool then returns "file not found" and
any assertion looser than an exact-error check passes for the wrong reason. Use
writeProjectFile.
addFileToProject is still fine — and still used in ~45 places — where the test hands PSI to the
code under test directly rather than routing a path through resolveFile (e.g. a
LanguageHandlerRegistry handler, a Find-in-Files search, a ChooseByNameContributor).
Call registerSourceRoot whenever the assertion depends on index-backed search —
ReferencesSearch, inheritor search, ChangeSignatureProcessor.findUsages, JS/TS import
resolution. The default project_files scope only covers content roots, so without it a
refactoring silently updates the declaration and no call sites, and the tool still reports
success. That is how ChangeSignatureBehaviorTest came to certify non-compiling output.
Assertion rules
These are enforced by review, and violating them is how this suite previously accumulated ~1,000 tests that could not fail:
- A test must fail if the production code it covers is deleted or inverted. If it would still pass, delete it.
- Assert both directions on refactorings. A rename test that only checks the new name is
present passes when call-site updating is completely broken. Use
assertRenamedInFile. - Never simulate the system under test with a private helper and assert on the helper.
- Conditional skips use
org.junit.Assume.assumeTrue, never a barereturn. A bare return reports the test as passed. Gradle is configured to log skipped tests so they stay visible. - No asserting on production source text. Reading a
.ktfile off disk and checking for substrings passes on comments and breaks on behavior-preserving refactors.
Test Data
- Fixtures live in
src/test/testData/; golden files insrc/test/resources/ - Cover dumb mode with
DumbModeTestUtilsfor any index-backed tool
MCP Implementation Notes
Implemented Tools
Tools are organized by IDE availability.
Universal Tools (All Supported JetBrains IDEs):
ide_find_references- Find all usages of a symbol. Supportslanguage+symbolas alternative tofile+line+column. Includes generated sources by default (includeGenerated: true) so valid runtime references (Dagger/MapStruct/gRPC/serializers) aren't missed; setincludeGenerated: falseto drop generated DI factories/mappers/stubs when they dominate results. Optionalpathsrestricts results to project-relative globs (!prefix excludes).ide_find_definition- Find symbol definition location. Accepts top-levelsymbolId,language+symbol, orfile+line+column, plus an equivalent nestedtarget, and returns a reusablesymbolIdfor exact lookup after edits or rename.ide_symbol_info- Resolved signature and documentation for a symbol, without reading the file. Java parameter/return types are expanded to fully qualified names with structuredparameters; other languages fall back to the signature their own Quick Documentation renders.signatureSourcereports which (java_psi/quick_navigation/element_text). Accepts the same flat or nested targets aside_find_definitionand returns a reusablesymbolId. (disabled by default)ide_find_class- Search for classes/interfaces by name with camelCase/substring/wildcard matchingide_find_file- Search for files by name using IDE's file indexide_find_symbol- Search for symbols (classes, methods, fields, functions) by name with IntelliJ Go to Symbol matching (disabled by default)ide_search_text- Text search using IntelliJ Find in Files with context filtering (substring matching for plain text, regex matching when enabled). Optionalpathsrestricts the search to project-relative globs (!prefix excludes)ide_read_file- Read file content by path or qualified name, including library/jar sources (disabled by default)ide_diagnostics- Unified diagnostics tool: per-file code analysis (errors, warnings, intentions), build output from last build, and test results from open test run tabs. Supports onefileor up to 100 suppliedfiles(relative or in-project absolute, aliases deduplicated) under a shared timeout budget, plusmaxProblems,includeBuildErrors,includeTestResults,severity,testResultFilter,maxBuildErrors, andmaxTestResults. The result'sanalysisModereports which path produced single-file problems (open_daemonorclosed_batch); multi-filefileAnalysesuseanalyzed/timed_out/failed/skipped/not_analyzedplusnot_found. The timeout includes path resolution, disk refresh, PSI setup, and analysis-lock waits; a daemon that consumes it does not receive a second batch-fallback budget.ide_project_diagnostics- Batch/project-scope diagnostics for many files including unopened ones, with fail-closed coverage metadata (issue #246): every file in scope gets exactly one state (analyzed/timed_out/failed/skipped/not_analyzed) andcompleteis true only when every considered file was analyzed, so an empty problems list can never be mistaken for a clean project. Reuses the per-file analysis engine (open files get daemon highlights, closed files the public batch pass). Long analyses long-poll viaanalysisId(same pattern aside_build_project); one analysis per project at a time. (disabled by default)ide_index_status- Check indexing status (dumb/smart mode)ide_sync_files- Force sync IDE's virtual file system and PSI cache with external file changes. Absolute targets may match any project/content root. Relative targets try the project base then module content roots whenproject_pathis omitted or selects the project base; selecting a specific content root confines relative resolution there. The complete batch is validated before refresh; invalid entries fail together, known deleted targets refresh their nearest existing parent, andrefreshedRoots/deletedPathsdisclose what was refreshed. Calls fail explicitly when no safe project/content root is available.ide_reload_project- Force-reload the project build model (Maven, Gradle, or both) after modifying build files. Equivalent to "Reload All Maven Projects" / "Reload Gradle Project" in the IDE. Async — returns immediately, resolution happens in background. (disabled by default)ide_link_build_system- Link an unlinked Maven or Gradle project so the IDE resolves its dependencies. Use whenide_reload_projectreports "not linked". Detects build system automatically from build files. Uses the platform'sExternalSystemUnlinkedProjectAwareEP. (disabled by default)ide_import_modules- Import external Maven project directories as modules into the current IntelliJ window for cross-project code intelligence and refactoring. Already imported module roots are skipped. Requires Maven plugin. (disabled by default)ide_open_workspace- Scan a root directory for Maven projects and open them all in one IntelliJ window with full cross-project code intelligence, or provide an explicit list of Maven project paths viamodules.pathandmodulesare mutually exclusive;modulesuses SHA-based caching. Creates a temporary aggregator POM with relative module paths. Requires Maven plugin. Guards against one-call-per-repository use (issue #436): an open project that already contains every requested Maven project as a module is reused instead of opening another window, and otherwise a single Maven project is refused with a ready-to-useide_open_projectcall. (disabled by default)ide_build_project- Build project using IDE's build system (JPS, Gradle, Maven, CMake (CLion)). Returns structured errors/warnings with file locations when available (null counts = no messages captured, not 0). Uses CompilationStatusListener for JPS builds, BuildProgressListener (BuildViewManager) for Gradle/Maven builds, and for CLion — whose CMake builds bypass both — the cidr build-finished topic plus the build log from the Messages tool window, parsed for MSVC/Clang/CMake diagnostics. Supports workspace sub-project targeting viaproject_path. Each call blocks at mostwaitSeconds(default 45): a still-running call returns{"status": "running", "buildId": ...}and the agent polls withbuildIdwhile the build continues in the IDE. (disabled by default)ide_change_signature- Change method signature (name, return type, visibility, parameters) with automatic caller updates using IntelliJ's Change Signature refactoring. Java methods and Kotlin JVM functions; Kotlin position/handle targets resolve to the base declaration for override changes. (disabled by default)ide_create_file- Create a new source file with content, immediately indexed by IntelliJ. Created through IntelliJ's VFS, instantly available for all IDE tools without needingide_sync_files. Use instead of Write for.java,.kt,.ts,.tsx,.pyfiles. File must not already exist. (disabled by default)ide_replace_text_in_file- Find and replace text in a file using IntelliJ's Document API. Plain text or regex replacement through IntelliJ's document model, so changes are immediately visible to index, PSI, and all other IDE tools without needingide_sync_files. (disabled by default)ide_run_tests- Run tests via the IDE's run configuration infrastructure.targetaccepts an existing run config name (works for any language/framework) or a Java/Kotlin class/method FQN (com.example.MyTest/com.example.MyTest#testFoo). Creating a config from an FQN is Java/Kotlin-only — for Python/JS/TS/Go/PHP/Rust, pass an existing run-config name. Results are read directly from the IDE's test runner (any Service-Message-based framework: JUnit, TestNG, pytest, Jest, Go test, PHPUnit), returning structured pass/fail/error counts, exit code, per-test results, and console output (each test's own prints on its entry, unattributed framework/suite output on the result'soutputfield; stdout/stderr merged in print order, ANSI stripped, system messages excluded, size-budgeted). Each call blocks at mostwaitSeconds(default 45) so the MCP client's request timeout is never hit: a still-running call — including one whose pre-test build is still compiling, in which case the test process has not started yet — returns{"status": "running", "runId": ...}and the agent polls withrunIdwhile the run (bounded bytimeoutSecondscounted from process start, enforced by a registry watchdog) continues in the IDE. A running response also reports the tests finished so far, read off the live test tree:passed/failed/errorscounts and the first 50failureswith message and stack trace (issue #426). By default the run does not activate (pop open) the Run tool window; passactivateToolWindow: trueto open it. (disabled by default)ide_refactor_rename- Preview a symbol or file rename withdryRun, or apply it across the project with automatic related element renaming (getters/setters, overriding methods). Fully headless, works for ALL languages, and accepts legacy selectors,symbolId, or a nestedtarget. Two modes: symbol rename (file + line + column + newName) and file rename (file + newName, omit line/column). File rename mode works for all file types including binary files (images, etc.) and is especially useful for Android resource files where it updates all XML references. SupportsrelatedRenamingStrategyparameter to control automatic related renames:"all"(default),"none","accessors_and_tests", or"ask".ide_move_file- Move a file to a new directory using the IDE's refactoring engine. Automatically updates all references, imports, and package declarations across the project. Supports automatic directory creation and optional reference update toggle. Move conflicts come back aswarnings. On a same-package move between modules/source roots (issue #360), imports naming the unchanged package that the IDE's usage rewrite removed from consuming Java files are restored (JavaOnDemandImportGuard, plugged into the headless processor viaMoveUsageGuard) and reported inwarnings; a destination outside every source root is also warned about.ide_reformat_code- Reformat code using project code style (.editorconfig, IDE settings). Supports optional import optimization and code rearrangement. (disabled by default)ide_optimize_imports- Optimize imports (remove unused, organize) without reformatting code. Equivalent to IDE's Ctrl+Alt+O. (disabled by default)ide_structural_search_replace- Pattern-based code search and transformation using IntelliJ's Structural Search and Replace engine. Search-only whenreplacePatternis omitted. Optionalpathsrestricts matching (and rewriting) to project-relative globs (!prefix excludes). Java, Kotlin. (disabled by default)ide_get_active_file- Get the currently active file(s) in the editor (disabled by default)ide_open_file- Open a file in the editor with optional line/column navigation (disabled by default)ide_set_power_save_mode- Enable/disable IDE Power Save Mode (IDE-wide). Suspends background inspections and code analysis while keeping the index and code intelligence operational (disabled by default)ide_close_project- Close an open project window and free its memory. Non-blocking; refuses to close the last open project so the MCP server keeps a JSON-RPC context (disabled by default)ide_create_module- Add a directory as an IntelliJ module with a content root, enabling code intelligence for non-Maven projects (TypeScript, plain directories, etc.). Supports optional directory exclusions. For Maven projects, useide_import_modulesinstead. (disabled by default)ide_open_project- Open a project by absolute path and wait until indexing completes (timeoutSeconds, default 600). Idempotent for already-open projects. PassautoLink: trueto automatically link an unlinked Maven/Gradle build system after opening. PassexcludeDirectories: ["dir1", "dir2"]to exclude directories from indexing and refactoring scope (applied after autoLink). (disabled by default)ide_install_plugin- Install a plugin zip into the IDE, replacing any existing version; auto-detectsbuild/distributions/*.zipwhen no path is given (disabled by default)ide_restart- Restart the IDE. The MCP server shuts down during restart; pollide_index_statusafter ~30s to confirm it is back, then continue. Typical use:ide_install_plugin→ide_restart→ poll → verify. (disabled by default)
Lifecycle Management Tools (All Supported JetBrains IDEs):
Manage which open projects the MCP server keeps active, in the background, dormant, or closed (behavior gated on the lifecycleEnabled setting). Every tool call with participatesInLifecycle restarts the project's background→dormant countdown (ProjectModeService.wakeForMcp); the countdown only runs while the window is unfocused. A dormant transition closes the editor tabs but records them in the service's persisted state and reopens them on the next transition to active (window focus) or on release — never on an MCP wake (issue #369):
ide_project_status- Report the status of all known projects (open + lifecycle-managed) in one tableide_enroll_all_projects- Enroll all currently open projects in MCP lifecycle management (disabled by default)ide_get_project_modes- List all MCP-managed projects and their current lifecycle mode (disabled by default)ide_lifecycle_log- Return recent lifecycle events (state transitions, open/close, focus changes, timer firings) from the in-memory ring buffer (disabled by default)ide_release_all_projects- Release every managed project from MCP lifecycle management at once (disabled by default)ide_release_project- Release a project from MCP lifecycle management, returning full control to the user (disabled by default)ide_set_all_project_modes- Set the lifecycle mode for every currently managed open project at once (disabled by default)ide_set_lifecycle_log_file- Enable or disable writing lifecycle events to a log file on disk (disabled by default)ide_set_project_mode- Set the lifecycle mode (active/background/dormant/closed) for a specific managed project (disabled by default)
Extended Navigation Tools (Language-Aware):
These activate based on available language plugins (Java, Python, JavaScript/TypeScript, Go, PHP, Rust, Scala, Markdown):
ide_type_hierarchy- Get type hierarchy for a class with bounded BFS pages and cursors (Java, Kotlin, Python, JS/TS, Go, PHP, Rust, Scala)ide_call_hierarchy- Get call hierarchy for a method with bounded BFS pages and cursors (Java, Kotlin, Python, JS/TS, Go, PHP, Rust, Scala). Supportslanguage+symbolas an alternative tofile+line+column.ide_find_implementations- Find implementations of interface/method (Java, Kotlin, Python, JS/TS, PHP, Rust, Scala — not Go). Supportslanguage+symbolas alternative tofile+line+column.ide_find_super_methods- Find methods that a given method overrides/implements (Java, Kotlin, Python, JS/TS, PHP, Scala — not Go, Rust). Supportslanguage+symbolas alternative tofile+line+column.ide_file_structure- Get legacy file structure text; opt into structured nodes and exact handles withincludeNodes/includeSymbolIds(disabled by default)
Java/Kotlin-Only Tools:
ide_list_tests- List all test methods/classes discovered by the IDE's test framework extension points (JUnit, TestNG, etc.). Optionalfileparameter limits scan to a single file. Returns entries with className, methodName, framework, file path, and line number. Requires Java plugin — thecom.intellij.testFrameworkextension point is declared by the Java plugin. (disabled by default)ide_edit_member- Replace an entire member declaration (signature + body) with new content (disabled by default)ide_insert_member- Insert a new member at a structural position in a class or file (disabled by default)ide_refactor_safe_delete- Preview or safely delete a symbol/file after usage discovery; accepts legacy selectors,symbolId, or a nestedtarget(requires Java plugin)ide_replace_member- Replace method body or field initializer only, preserving the signature (disabled by default)
Kotlin Conversion Tools:
ide_convert_java_to_kotlin- Convert Java files to Kotlin using IntelliJ's built-in J2K converter. Supports full file conversion with automatic formatting and import optimization. Handles classes, interfaces, methods, generics, Java 8+ features (lambdas, streams). Returns list of created .kt files and conversion warnings. Requires both Java and Kotlin plugins. (disabled by default)
Multi-Language Architecture
The plugin uses a language handler pattern for multi-IDE support:
Core Components:
LanguageHandler<T>- Base interface for language-specific handlersLanguageHandlerRegistry- Central registry managing all language handlersPluginDetectors- Central registry of language plugin availability detectors (runs once at startup)
Language Handlers (in handlers/ package):
handlers/java/JavaHandlers.kt- Direct PSI access for Java/Kotlinhandlers/python/PythonHandlers.kt- Reflection-based Python PSI accesshandlers/javascript/JavaScriptHandlers.kt- Reflection-based JS/TS PSI accesshandlers/go/GoHandlers.kt- Reflection-based Go PSI accesshandlers/php/PhpHandlers.kt- Reflection-based PHP PSI accesshandlers/rust/RustHandlers.kt- Reflection-based Rust PSI accesshandlers/scala/ScalaHandlers.kt- Direct Scala PSI access (compiled against the Scala plugin's API; not reflection-based)
Handler Types:
TypeHierarchyHandler- Type hierarchy lookupImplementationsHandler- Find implementationsCallHierarchyHandler- Call hierarchy analysisSymbolReferenceHandler- Resolve fully qualified symbol references (e.g.,com.example.MyClass#method(String)) to PSI elementsSuperMethodsHandler- Method override hierarchyStructureHandler- Hierarchical file structure (Structure view)
Registration Flow:
LanguageHandlerRegistry.registerHandlers()- Registers handlers for available language pluginsToolRegistry.registerUniversalTools()- Registers universal tools includingide_refactor_rename,ide_sync_filesToolRegistry.registerLanguageNavigationTools()- Registers tools if any language handlers availableToolRegistry.registerJavaRefactoringTools()- Registerside_refactor_safe_deleteandide_list_testsif Java plugin available
Reflection Pattern: Python, JavaScript, Go, PHP, and Rust handlers use reflection to avoid compile-time dependencies on language-specific plugins. This prevents NoClassDefFoundError in IDEs without those plugins. Scala handlers instead compile directly against the Scala plugin's PSI API; PluginDetectors.scala still gates registration so the classes are never loaded when the Scala plugin is absent. BaseScalaHandler.safeScalaCall rethrows control-flow exceptions (cancellation, IndexNotReadyException) like every other handler, and each handler entry point runs inside scalaApiBoundary, which turns a LinkageError from Scala-plugin API drift into an explicit tool error (ScalaPluginApiMismatchException) instead of an empty result. The pinned org.intellij.scala version in gradle.properties must move with platformVersion.
Optimized Symbol Search
Symbol search across all languages uses OptimizedSymbolSearch (in handlers/OptimizedSymbolSearch.kt):
- Leverages IntelliJ's "Go to Symbol" APIs (
ChooseByNameContributor) - Uses
MinusculeMatcherfor CamelCase, substring, and typo-tolerant matching - Supports language filtering (e.g.,
languageFilter = setOf("Java", "Kotlin"))
Pagination
The plugin supports cursor-based pagination for search tools that return flat result lists:
ide_find_references, ide_search_text, ide_find_class, ide_find_file, ide_find_symbol, ide_find_implementations.
Key components:
PaginationService(server/PaginationService.kt): Application-level light service managing cursor cache- Cursor tokens are opaque, immutable, base64url-encoded strings containing
{entryId}:{offset}:{pageSize} - Same cursor token always returns the same page (idempotent, safe for retries)
- Responses include
nextCursoronly while the cached snapshot can safely serve another page;hasMore: truewith no cursor means the search may have more results but must be restarted with narrower parameters (for example, after staleness or the hard cache cap)
Cache lifecycle:
- Over-collection: tools collect 500 results internally, serve in configurable page sizes (default varies per tool)
- Inactivity-based TTL: 10 minutes of idle time before cursor expires
- LRU eviction: max 20 active cursors
- Max 5,000 cached results per cursor; at the cap,
hasMoreremains true butnextCursoris absent, so callers must start a narrower fresh search - Staleness detection via
PsiModificationTracker—stale: truein response if PSI changed
Tool integration pattern:
- Check for
cursorparameter → serve from cache viagetPageFromCache() - Fresh search → collect results, create cursor via
PaginationService.createCursor(), serve first page searchExtenderlambda enables lazy cache extension when pages are exhausted- Each tool has a
buildPaginatedResult()helper mappingGetPageResultto its own result model
Schema: All parameters are optional in the schema (no required array) because the Anthropic API does not support anyOf/oneOf at the top level. Validation is done at runtime — if cursor is absent, the tool checks for its required search params and returns an error if missing.
Backward compatibility: Old limit/maxResults parameters work as aliases for pageSize. Legacy cursors (without embedded pageSize) are still decodable but require an explicit pageSize parameter.
Bounded hierarchy pages with legacy tree compatibility
Without maxNodes or cursor, call/type hierarchies keep nested trees and legacy limits.
Explicit pagination returns bounded breadth-first pages with traversal-local nodeId,
parentId, and depth. Continuations are scoped to the project, tool, and server session.
A continuation budget limit preserves the computed page and reports truncationReason;
narrow the query when hasMore=true has no cursor. Cancellation and indexing transitions
propagate through reflective handlers instead of completing an empty hierarchy.
Symbol handles across navigation and member editing
Class, symbol, reference, implementation, and super-method queries expose opaque handles for
their exact declarations. Reference and implementation queries plus ide_edit_member and
ide_replace_member accept the shared target selectors. Cached search pages remain marked
stale=true after PSI edits and rebind handles from their exact smart pointers when returned;
deleted declarations and handles from another project or server session are rejected. Successful
member edits return current declaration metadata. Kotlin abstract/sealed declarations retain
ABSTRACT_CLASS, while anonymous implementations report a useful source location without an
invented qualified name.
ide_file_structure keeps the legacy structure response by default and avoids returning a
structured-node payload or allocating handles. Use includeNodes=true
for structured declarations, and includeSymbolIds=true when exact handles are needed (it implies
includeNodes). Handle allocation is opt-in and capped at 100 per response; lower it with
maxSymbolIds (1–100). Large responses report symbolIdsTruncated and symbolIdsOmitted.
Structured Lookup Targets
Definition, symbol-info, reference, implementation, and member-edit tools accept an additive
nested target with exactly one
variant: { "symbolId": "sym_..." }, { "position": { "file": "src/Foo.java", "line": 3,
"column": 8 } }, or { "qualifiedName": "com.example.Foo#bar", "language": "Java" }.
Do not mix target with top-level selectors. Existing top-level requests remain valid.
Validation runs before PSI synchronization, and target.symbolId routes to its owning project.
Rename Preview
ide_refactor_rename accepts dryRun: true with legacy selectors, symbolId, or a nested
target. It returns canApply, current target metadata, plannedChange, affectedFiles, usage
and conflict counts, warnings, and elapsedMs without entering the source-write phase, saving
documents, or creating an undo command. Preview and apply share conflict discovery and automatic
rename selection.
Safe-delete Preview
ide_refactor_safe_delete accepts the same dryRun: true preview contract with legacy selectors,
symbolId, or a nested target. It reports the planned symbol/file deletion, usage blockers, and
current applicability without deleting or saving anything or invalidating a handle. Successful
symbol deletion selected by an incoming handle returns it as invalidatedSymbolId. Files with no
discovered top-level declarations retain the existing apply eligibility but carry an
incomplete-discovery warning; force can explicitly override usages or a failed usage search.
Change-signature Preview
ide_change_signature accepts the same exact/nested targets and dryRun: true preview contract.
Preview reports the current and requested signatures, affected declarations/callers, conflicts,
read-only scope, missing required caller/delegate arguments, and interactive overrider decisions
without running the processor. Apply runs the same conflict and safety checks before editing.
Successful apply returns current updatedSymbol metadata. Return-type changes with overriders
are conservatively refused, even where narrower overriding return types could be retained.
Unlike Kotlin targets, Java override targets do not redirect to the base; select the Java base
explicitly for hierarchy-wide changes.
Search Collection Pattern (Processor)
All search operations use the Processor pattern for efficient streaming and early termination:
// ✗ Inefficient: loads all results into memory
val results = SomeSearch.search(element).findAll().take(100)
// ✓ Efficient: streams results with early termination
val results = mutableListOf<Result>()
SomeSearch.search(element).forEach(Processor { item ->
results.add(convertToResult(item))
results.size < 100 // Return false to stop iteration
})Useful IntelliJ Platform Classes
// PSI Navigation
PsiTreeUtil // Tree traversal utilities
PsiUtilCore // Core PSI utilities
ReferencesSearch // Find references to element
// Refactoring
RefactoringFactory // Create refactoring instances
RenameProcessor // Rename refactoring
RefactoringBundle // Refactoring messages
// Indexes
DumbService // Check index status
FileBasedIndex // Access file indexes
StubIndex // Access stub indexes
// Project Structure
ProjectRootManager // Project roots
ModuleManager // Module access
VirtualFileManager // Virtual file systemTroubleshooting
Common Issues
- IndexNotReadyException - Accessing indexes in dumb mode
- Solution: Use
DumbService.getInstance(project).runWhenSmart { ... }
- Solution: Use
- WriteAction required - Modifying PSI without write lock
- Solution: Wrap in
WriteCommandAction.runWriteCommandAction(project) { ... }
- Solution: Wrap in
- Must be called from EDT - UI operations on background thread
- Solution: Use
ApplicationManager.getApplication().invokeLater { ... }
- Solution: Use
- Search misses newly created files - PSI not synchronized with document (read-only tools; write tools sync themselves)
- Cause: External tools modified files but PSI tree hasn't been updated
- Solution: Enable "Sync external file changes" in Settings → Tools → Index MCP Server (WARNING: significant performance impact)
- For custom code:
PsiDocumentManager.getInstance(project).commitAllDocuments()
Contributing / PR Checklist
Every PR — without exception — must comply with CONTRIBUTING.md. Read it before writing a single line of code. It is the authoritative guide for this repo.
Before pushing, run the pre-push validation script to catch common mistakes automatically:
./scripts/check-pr.shQuick summary of the non-negotiables:
CHANGELOG.md— user-visible changes go under[Unreleased]; never add## [x.y.z]version sections (created at release time)- No
.idea/gradle.xml, noscripts/build-install.sh, nodocs/pr-*.md - New tools: registered in
ToolNames,ToolRegistry, and all six doc locations (README.md,USAGE.md,CLAUDE.md,SKILL.md,tools-reference.md,ToolNames.ALLsorted) - New opt-in tools: add to
McpSettings.DEFAULT_DISABLED_TOOLS, bump the settings schema, and add a migration so existing users also get the tool disabled by default - No
@InternalAPI, noModalityState.NON_MODAL(deprecated) - Tests pass:
./gradlew test— the whole suite, platform tier included. It takes ~40s. Use-Ptier=unitfor a faster inner loop, but do not push on the fast tier alone: 46% of the tests live in the platform tier, and that is where tool behavior is actually verified. - New tools: regenerate the golden manifest and review its diff (see the Testing section)
Template Source: JetBrains IntelliJ Platform Plugin Template
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

