clangd-nav 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jérémy Dumoulin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,240 @@
1
+ Metadata-Version: 2.4
2
+ Name: clangd-nav
3
+ Version: 0.1.0
4
+ Summary: clangd for navigation only: an LSP proxy for coding agents that drops diagnostics and finds the right clangd and compile database
5
+ Keywords: clangd,lsp,c++,cmake,claude-code,opencode
6
+ Author: Jérémy Dumoulin
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: MacOS
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: C
15
+ Classifier: Programming Language :: C++
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Software Development
18
+ Requires-Python: >=3.11
19
+ Project-URL: Homepage, https://github.com/Meirdrarel/clangd-nav
20
+ Project-URL: Issues, https://github.com/Meirdrarel/clangd-nav/issues
21
+ Description-Content-Type: text/markdown
22
+
23
+ # clangd-nav
24
+
25
+ clangd for **navigation only**, for coding agents such as Claude Code and opencode:
26
+ definition, references, hover, symbols, implementations, call hierarchy. No diagnostics.
27
+
28
+ **Status: alpha.** The proxy and the clangd and compile database lookup work. `--doctor`,
29
+ `--self-test` and `install` are planned, see the [roadmap](#roadmap).
30
+
31
+ MIT licensed, see [LICENSE](LICENSE).
32
+
33
+ ## Why
34
+
35
+ - **Diagnostics are often owned elsewhere.** Many C and C++ projects run clang-format and
36
+ clang-tidy through their own scripts and enforce them in a commit hook or CI. Another stream of
37
+ the same findings after every edit is noise to an agent, and the two can disagree.
38
+ - **clangd has no switch to turn diagnostics off.** `--clang-tidy=false` stops clang-tidy, but
39
+ compiler errors are still pushed. So `clangd-nav` is a proxy on stdio between the client and
40
+ clangd that removes diagnostics and passes everything else through unchanged.
41
+ - **Claude Code can drop diagnostics by itself, opencode cannot.** A Claude Code plugin's
42
+ `lspServers` entry accepts `"diagnostics": false`. opencode has no such switch per server.
43
+ `clangd-nav` filters for every client; in a Claude plugin, set the flag as well.
44
+ - **Finding the right clangd and compile database.** An agent launches one fixed command. For a
45
+ CMake project, that command has to pick the clangd the project pins and the build tree that
46
+ holds `compile_commands.json`, or navigation silently stops at the first project header.
47
+ - **The IDE is unaffected.** An IDE starts its own clangd, with the project's `.clangd`, at full
48
+ features.
49
+
50
+ ## Install
51
+
52
+ Requires Python 3.11 or later, and clangd.
53
+
54
+ ```
55
+ uv tool install git+https://github.com/Meirdrarel/clangd-nav
56
+ ```
57
+
58
+ This puts `clangd-nav` in `~/.local/bin`, with its own Python. `pipx install` works too.
59
+
60
+ ### Claude Code
61
+
62
+ In a plugin's `.claude-plugin/plugin.json` (or its marketplace entry):
63
+
64
+ ```json
65
+ "lspServers": {
66
+ "clangd-nav": {
67
+ "command": "clangd-nav",
68
+ "extensionToLanguage": {
69
+ ".c": "c", ".h": "cpp", ".cc": "cpp", ".cpp": "cpp", ".cxx": "cpp", ".hpp": "cpp", ".hxx": "cpp"
70
+ },
71
+ "diagnostics": false
72
+ }
73
+ }
74
+ ```
75
+
76
+ Disable any other clangd plugin, such as the official `clangd-lsp`.
77
+
78
+ ### opencode
79
+
80
+ In `~/.config/opencode/opencode.json`:
81
+
82
+ ```json
83
+ "lsp": {
84
+ "clangd": { "disabled": true },
85
+ "clangd-nav": {
86
+ "command": ["clangd-nav"],
87
+ "extensions": [".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx"]
88
+ }
89
+ }
90
+ ```
91
+
92
+ ## How it works
93
+
94
+ ### Project root
95
+
96
+ The launch directory if it holds a `.clangd`, else its git repository (`git rev-parse
97
+ --show-toplevel`), else the launch directory. It is fixed at startup: a session that moves to
98
+ another repository keeps navigating the first one.
99
+
100
+ ### Which clangd
101
+
102
+ 1. `$CLANGD`.
103
+ 2. If the project pins a clang major N (`$CLANG_VERSION`, else `clang_version` in
104
+ `.clangd-nav.toml`): `/opt/homebrew/opt/llvm@N/bin/clangd`, `/usr/lib/llvm-N/bin/clangd`,
105
+ then `clangd-N` on `PATH`.
106
+ 3. If the build was configured with clang (read from the compile database below, skipping
107
+ `ccache`-style launchers): the `clangd` next to that compiler, then the same places as in 2
108
+ for its major. The major comes from the compiler's name (`clang++-22`) or from CMake's
109
+ record in `CMakeFiles/<version>/CMake<LANG>Compiler.cmake`. No configuration is needed.
110
+ 4. `/opt/homebrew/opt/llvm/bin/clangd`, then `clangd` on `PATH`. For navigation any recent
111
+ major will do, so GCC builds land here.
112
+
113
+ If none is found, it exits with a message saying what to install.
114
+
115
+ ### Which compile database
116
+
117
+ It is passed to clangd as `--compile-commands-dir`, which overrides `.clangd`'s
118
+ `CompilationDatabase`. The first that applies:
119
+
120
+ 1. `$CLANGD_NAV_BUILD_DIR`, else `build_dir` in `.clangd-nav.toml`, relative to the project.
121
+ 2. `build/`, if it holds `compile_commands.json`.
122
+ 3. The most recently configured `build-*/` or `cmake-build-*/` holding one.
123
+
124
+ Without one, clangd guesses flags and finds no project header. CMake writes the database only
125
+ with `CMAKE_EXPORT_COMPILE_COMMANDS=ON`.
126
+
127
+ ### clangd arguments
128
+
129
+ `--clang-tidy=false --background-index --compile-commands-dir=DIR`, then the arguments given to
130
+ `clangd-nav`, then `clangd_args` from `.clangd-nav.toml`.
131
+
132
+ ### What is filtered
133
+
134
+ From clangd to the client:
135
+
136
+ - `textDocument/publishDiagnostics` notifications are dropped.
137
+ - `diagnosticProvider` is removed from the `initialize` result.
138
+
139
+ From the client to clangd:
140
+
141
+ - `textDocument/diagnostic` and `workspace/diagnostic` requests are answered with an empty
142
+ report and never forwarded.
143
+
144
+ Everything else passes byte for byte. The exit status is clangd's.
145
+
146
+ ## Configuration
147
+
148
+ Environment variables win over the file.
149
+
150
+ | Variable | Effect |
151
+ |---|---|
152
+ | `CLANGD` | clangd executable |
153
+ | `CLANG_VERSION` | pinned clang major, only needed to override the build's own clang |
154
+ | `CLANGD_NAV_BUILD_DIR` | compile database directory, relative to the project |
155
+
156
+ Optional `.clangd-nav.toml` at the project root. Unknown keys are an error.
157
+
158
+ ```toml
159
+ clang_version = 22
160
+ build_dir = "cmake-build-debug"
161
+ clangd_args = ["--header-insertion=never"]
162
+ ```
163
+
164
+ ## Known limits
165
+
166
+ - **One build configuration at a time.** clangd uses one compile command per file. Code in the
167
+ inactive branch of an `#if` is not indexed, for example a platform-specific path on another
168
+ platform. Choose the configuration with `build_dir`; for the other branch, use text search or
169
+ an IDE on that platform.
170
+ - **Generated headers need a build.** Navigation through moc, uic or `configure_file` output
171
+ works only once the build tree has produced them.
172
+ - **Switching configuration needs a restart** of the LSP server.
173
+ - **One project per server.**
174
+
175
+ ## Roadmap
176
+
177
+ 1. **Done.** Package the proxy: console script, `uv tool install`, configuration file.
178
+ 2. **Project override:** if the project ships its own `scripts/clangd-nav`, exec it instead.
179
+ 3. **`clangd-nav --doctor`:** explain what serve would do and what is wrong:
180
+ - the project root, the clangd chosen with its version, and whether it came from a pin,
181
+ the build's compiler or the fallback;
182
+ - the compile database chosen and which rule chose it;
183
+ - the database older than any `CMakeLists.txt` or `cmake/*.cmake`;
184
+ - `CMAKE_EXPORT_COMPILE_COMMANDS` not set, so only an IDE's build tree has a database;
185
+ - project headers present in no include directory: generated headers that need a build;
186
+ - `.cache/` (clangd's background index) not ignored by git;
187
+ - competing clangd servers still enabled in Claude Code or opencode.
188
+ 4. **Robustness:**
189
+ - buffered message reading, and headers other than `Content-Length`;
190
+ - stop clangd when the client's input ends, and pass SIGTERM and SIGINT on;
191
+ - answer `workspace/diagnostic/refresh` locally;
192
+ - with `CLANGD_NAV_DEBUG=1`, log each dropped message on stderr.
193
+ 5. **CMake presets and `--query-driver`:**
194
+ - `preset = "debug"` or `$CLANGD_NAV_PRESET` selects a preset's `binaryDir`;
195
+ - pass the database's compiler as `--query-driver`, so standard-library headers resolve
196
+ with `-stdlib=libstdc++` on Linux.
197
+ 6. **`clangd-nav --self-test`**, and a fixture CMake project:
198
+ - open a translation unit in memory with an error appended;
199
+ - ask for a definition through the proxy, and check that no diagnostics come through;
200
+ - `--raw` runs the same against plain clangd, which must report the error: that control is
201
+ what makes a pass mean something.
202
+ 7. **`clangd-nav install` / `uninstall [--claude] [--opencode]`:** write the Claude plugin entry
203
+ and the opencode configuration, and disable competing servers. The Claude plugin will ship in
204
+ this repository.
205
+ 8. **CI:** macOS and Linux, clangd 20 to 22.
206
+
207
+ ## Related projects
208
+
209
+ Checked in December 2026. None combines the diagnostics filter with clangd and CMake discovery.
210
+
211
+ | Project | What it does |
212
+ |---|---|
213
+ | Claude Code `lspServers.*.diagnostics: false` | Built in: no diagnostics pushed after edits. Claude Code only. |
214
+ | [stay-fresh-lsp-proxy](https://github.com/iloom-ai/stay-fresh-lsp-proxy) (MIT, TypeScript) | Drops or severity-filters `publishDiagnostics` for any server; Claude Code plugins for TypeScript, Python, Rust. No clangd or CMake logic. |
215
+ | [clangd-lsp-proxy](https://github.com/barbedo/clangd-lsp-proxy) (MIT, Python) | Switches clangd binary and compile database at runtime through an MCP control channel. No filtering. |
216
+ | [lsp-filter](https://github.com/jacobdufault/lsp-filter) (Apache-2.0, Go, inactive) | Rewrites a server's `initialize` capabilities. |
217
+ | [clangd-mcp-server](https://github.com/felipeerias/clangd-mcp-server) and similar | Navigation as MCP tools rather than through LSP. |
218
+
219
+ ## Development
220
+
221
+ Python standard library only at runtime. `uv` for the environment, pytest and ruff for
222
+ development.
223
+
224
+ ```
225
+ uv sync # creates .venv, usable as the IDE's interpreter
226
+ uv run pytest
227
+ uv run ruff check && uv run ruff format --check
228
+ uv tool install --editable . # clangd-nav on PATH runs the working copy
229
+ ```
230
+
231
+ Layout:
232
+
233
+ ```
234
+ src/clangd_nav/
235
+ cli.py entry point, builds the clangd command
236
+ project.py project root, configuration file, clangd and compile database lookup
237
+ lsp.py message framing
238
+ proxy.py the filter
239
+ tests/unit/ a fake LSP server for the filter, temporary directories for the lookups
240
+ ```
@@ -0,0 +1,218 @@
1
+ # clangd-nav
2
+
3
+ clangd for **navigation only**, for coding agents such as Claude Code and opencode:
4
+ definition, references, hover, symbols, implementations, call hierarchy. No diagnostics.
5
+
6
+ **Status: alpha.** The proxy and the clangd and compile database lookup work. `--doctor`,
7
+ `--self-test` and `install` are planned, see the [roadmap](#roadmap).
8
+
9
+ MIT licensed, see [LICENSE](LICENSE).
10
+
11
+ ## Why
12
+
13
+ - **Diagnostics are often owned elsewhere.** Many C and C++ projects run clang-format and
14
+ clang-tidy through their own scripts and enforce them in a commit hook or CI. Another stream of
15
+ the same findings after every edit is noise to an agent, and the two can disagree.
16
+ - **clangd has no switch to turn diagnostics off.** `--clang-tidy=false` stops clang-tidy, but
17
+ compiler errors are still pushed. So `clangd-nav` is a proxy on stdio between the client and
18
+ clangd that removes diagnostics and passes everything else through unchanged.
19
+ - **Claude Code can drop diagnostics by itself, opencode cannot.** A Claude Code plugin's
20
+ `lspServers` entry accepts `"diagnostics": false`. opencode has no such switch per server.
21
+ `clangd-nav` filters for every client; in a Claude plugin, set the flag as well.
22
+ - **Finding the right clangd and compile database.** An agent launches one fixed command. For a
23
+ CMake project, that command has to pick the clangd the project pins and the build tree that
24
+ holds `compile_commands.json`, or navigation silently stops at the first project header.
25
+ - **The IDE is unaffected.** An IDE starts its own clangd, with the project's `.clangd`, at full
26
+ features.
27
+
28
+ ## Install
29
+
30
+ Requires Python 3.11 or later, and clangd.
31
+
32
+ ```
33
+ uv tool install git+https://github.com/Meirdrarel/clangd-nav
34
+ ```
35
+
36
+ This puts `clangd-nav` in `~/.local/bin`, with its own Python. `pipx install` works too.
37
+
38
+ ### Claude Code
39
+
40
+ In a plugin's `.claude-plugin/plugin.json` (or its marketplace entry):
41
+
42
+ ```json
43
+ "lspServers": {
44
+ "clangd-nav": {
45
+ "command": "clangd-nav",
46
+ "extensionToLanguage": {
47
+ ".c": "c", ".h": "cpp", ".cc": "cpp", ".cpp": "cpp", ".cxx": "cpp", ".hpp": "cpp", ".hxx": "cpp"
48
+ },
49
+ "diagnostics": false
50
+ }
51
+ }
52
+ ```
53
+
54
+ Disable any other clangd plugin, such as the official `clangd-lsp`.
55
+
56
+ ### opencode
57
+
58
+ In `~/.config/opencode/opencode.json`:
59
+
60
+ ```json
61
+ "lsp": {
62
+ "clangd": { "disabled": true },
63
+ "clangd-nav": {
64
+ "command": ["clangd-nav"],
65
+ "extensions": [".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx"]
66
+ }
67
+ }
68
+ ```
69
+
70
+ ## How it works
71
+
72
+ ### Project root
73
+
74
+ The launch directory if it holds a `.clangd`, else its git repository (`git rev-parse
75
+ --show-toplevel`), else the launch directory. It is fixed at startup: a session that moves to
76
+ another repository keeps navigating the first one.
77
+
78
+ ### Which clangd
79
+
80
+ 1. `$CLANGD`.
81
+ 2. If the project pins a clang major N (`$CLANG_VERSION`, else `clang_version` in
82
+ `.clangd-nav.toml`): `/opt/homebrew/opt/llvm@N/bin/clangd`, `/usr/lib/llvm-N/bin/clangd`,
83
+ then `clangd-N` on `PATH`.
84
+ 3. If the build was configured with clang (read from the compile database below, skipping
85
+ `ccache`-style launchers): the `clangd` next to that compiler, then the same places as in 2
86
+ for its major. The major comes from the compiler's name (`clang++-22`) or from CMake's
87
+ record in `CMakeFiles/<version>/CMake<LANG>Compiler.cmake`. No configuration is needed.
88
+ 4. `/opt/homebrew/opt/llvm/bin/clangd`, then `clangd` on `PATH`. For navigation any recent
89
+ major will do, so GCC builds land here.
90
+
91
+ If none is found, it exits with a message saying what to install.
92
+
93
+ ### Which compile database
94
+
95
+ It is passed to clangd as `--compile-commands-dir`, which overrides `.clangd`'s
96
+ `CompilationDatabase`. The first that applies:
97
+
98
+ 1. `$CLANGD_NAV_BUILD_DIR`, else `build_dir` in `.clangd-nav.toml`, relative to the project.
99
+ 2. `build/`, if it holds `compile_commands.json`.
100
+ 3. The most recently configured `build-*/` or `cmake-build-*/` holding one.
101
+
102
+ Without one, clangd guesses flags and finds no project header. CMake writes the database only
103
+ with `CMAKE_EXPORT_COMPILE_COMMANDS=ON`.
104
+
105
+ ### clangd arguments
106
+
107
+ `--clang-tidy=false --background-index --compile-commands-dir=DIR`, then the arguments given to
108
+ `clangd-nav`, then `clangd_args` from `.clangd-nav.toml`.
109
+
110
+ ### What is filtered
111
+
112
+ From clangd to the client:
113
+
114
+ - `textDocument/publishDiagnostics` notifications are dropped.
115
+ - `diagnosticProvider` is removed from the `initialize` result.
116
+
117
+ From the client to clangd:
118
+
119
+ - `textDocument/diagnostic` and `workspace/diagnostic` requests are answered with an empty
120
+ report and never forwarded.
121
+
122
+ Everything else passes byte for byte. The exit status is clangd's.
123
+
124
+ ## Configuration
125
+
126
+ Environment variables win over the file.
127
+
128
+ | Variable | Effect |
129
+ |---|---|
130
+ | `CLANGD` | clangd executable |
131
+ | `CLANG_VERSION` | pinned clang major, only needed to override the build's own clang |
132
+ | `CLANGD_NAV_BUILD_DIR` | compile database directory, relative to the project |
133
+
134
+ Optional `.clangd-nav.toml` at the project root. Unknown keys are an error.
135
+
136
+ ```toml
137
+ clang_version = 22
138
+ build_dir = "cmake-build-debug"
139
+ clangd_args = ["--header-insertion=never"]
140
+ ```
141
+
142
+ ## Known limits
143
+
144
+ - **One build configuration at a time.** clangd uses one compile command per file. Code in the
145
+ inactive branch of an `#if` is not indexed, for example a platform-specific path on another
146
+ platform. Choose the configuration with `build_dir`; for the other branch, use text search or
147
+ an IDE on that platform.
148
+ - **Generated headers need a build.** Navigation through moc, uic or `configure_file` output
149
+ works only once the build tree has produced them.
150
+ - **Switching configuration needs a restart** of the LSP server.
151
+ - **One project per server.**
152
+
153
+ ## Roadmap
154
+
155
+ 1. **Done.** Package the proxy: console script, `uv tool install`, configuration file.
156
+ 2. **Project override:** if the project ships its own `scripts/clangd-nav`, exec it instead.
157
+ 3. **`clangd-nav --doctor`:** explain what serve would do and what is wrong:
158
+ - the project root, the clangd chosen with its version, and whether it came from a pin,
159
+ the build's compiler or the fallback;
160
+ - the compile database chosen and which rule chose it;
161
+ - the database older than any `CMakeLists.txt` or `cmake/*.cmake`;
162
+ - `CMAKE_EXPORT_COMPILE_COMMANDS` not set, so only an IDE's build tree has a database;
163
+ - project headers present in no include directory: generated headers that need a build;
164
+ - `.cache/` (clangd's background index) not ignored by git;
165
+ - competing clangd servers still enabled in Claude Code or opencode.
166
+ 4. **Robustness:**
167
+ - buffered message reading, and headers other than `Content-Length`;
168
+ - stop clangd when the client's input ends, and pass SIGTERM and SIGINT on;
169
+ - answer `workspace/diagnostic/refresh` locally;
170
+ - with `CLANGD_NAV_DEBUG=1`, log each dropped message on stderr.
171
+ 5. **CMake presets and `--query-driver`:**
172
+ - `preset = "debug"` or `$CLANGD_NAV_PRESET` selects a preset's `binaryDir`;
173
+ - pass the database's compiler as `--query-driver`, so standard-library headers resolve
174
+ with `-stdlib=libstdc++` on Linux.
175
+ 6. **`clangd-nav --self-test`**, and a fixture CMake project:
176
+ - open a translation unit in memory with an error appended;
177
+ - ask for a definition through the proxy, and check that no diagnostics come through;
178
+ - `--raw` runs the same against plain clangd, which must report the error: that control is
179
+ what makes a pass mean something.
180
+ 7. **`clangd-nav install` / `uninstall [--claude] [--opencode]`:** write the Claude plugin entry
181
+ and the opencode configuration, and disable competing servers. The Claude plugin will ship in
182
+ this repository.
183
+ 8. **CI:** macOS and Linux, clangd 20 to 22.
184
+
185
+ ## Related projects
186
+
187
+ Checked in December 2026. None combines the diagnostics filter with clangd and CMake discovery.
188
+
189
+ | Project | What it does |
190
+ |---|---|
191
+ | Claude Code `lspServers.*.diagnostics: false` | Built in: no diagnostics pushed after edits. Claude Code only. |
192
+ | [stay-fresh-lsp-proxy](https://github.com/iloom-ai/stay-fresh-lsp-proxy) (MIT, TypeScript) | Drops or severity-filters `publishDiagnostics` for any server; Claude Code plugins for TypeScript, Python, Rust. No clangd or CMake logic. |
193
+ | [clangd-lsp-proxy](https://github.com/barbedo/clangd-lsp-proxy) (MIT, Python) | Switches clangd binary and compile database at runtime through an MCP control channel. No filtering. |
194
+ | [lsp-filter](https://github.com/jacobdufault/lsp-filter) (Apache-2.0, Go, inactive) | Rewrites a server's `initialize` capabilities. |
195
+ | [clangd-mcp-server](https://github.com/felipeerias/clangd-mcp-server) and similar | Navigation as MCP tools rather than through LSP. |
196
+
197
+ ## Development
198
+
199
+ Python standard library only at runtime. `uv` for the environment, pytest and ruff for
200
+ development.
201
+
202
+ ```
203
+ uv sync # creates .venv, usable as the IDE's interpreter
204
+ uv run pytest
205
+ uv run ruff check && uv run ruff format --check
206
+ uv tool install --editable . # clangd-nav on PATH runs the working copy
207
+ ```
208
+
209
+ Layout:
210
+
211
+ ```
212
+ src/clangd_nav/
213
+ cli.py entry point, builds the clangd command
214
+ project.py project root, configuration file, clangd and compile database lookup
215
+ lsp.py message framing
216
+ proxy.py the filter
217
+ tests/unit/ a fake LSP server for the filter, temporary directories for the lookups
218
+ ```
@@ -0,0 +1,66 @@
1
+ [project]
2
+ name = "clangd-nav"
3
+ version = "0.1.0"
4
+ description = "clangd for navigation only: an LSP proxy for coding agents that drops diagnostics and finds the right clangd and compile database"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = []
10
+ keywords = [
11
+ "clangd",
12
+ "lsp",
13
+ "c++",
14
+ "cmake",
15
+ "claude-code",
16
+ "opencode",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Environment :: Console",
21
+ "Intended Audience :: Developers",
22
+ "Operating System :: MacOS",
23
+ "Operating System :: POSIX :: Linux",
24
+ "Programming Language :: C",
25
+ "Programming Language :: C++",
26
+ "Programming Language :: Python :: 3",
27
+ "Topic :: Software Development",
28
+ ]
29
+
30
+ [[project.authors]]
31
+ name = "Jérémy Dumoulin"
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/Meirdrarel/clangd-nav"
35
+ Issues = "https://github.com/Meirdrarel/clangd-nav/issues"
36
+
37
+ [project.scripts]
38
+ clangd-nav = "clangd_nav.cli:main"
39
+
40
+ [dependency-groups]
41
+ dev = [
42
+ "pytest>=8",
43
+ "ruff>=0.8",
44
+ ]
45
+
46
+ [build-system]
47
+ requires = ["uv_build>=0.9,<0.14"]
48
+ build-backend = "uv_build"
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["tests"]
52
+
53
+ [tool.ruff]
54
+ line-length = 100
55
+ target-version = "py311"
56
+
57
+ [tool.ruff.lint]
58
+ select = [
59
+ "E",
60
+ "F",
61
+ "W",
62
+ "I",
63
+ "B",
64
+ "UP",
65
+ "SIM",
66
+ ]
@@ -0,0 +1,46 @@
1
+ [project]
2
+ name = "clangd-nav"
3
+ version = "0.1.0"
4
+ description = "clangd for navigation only: an LSP proxy for coding agents that drops diagnostics and finds the right clangd and compile database"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Jérémy Dumoulin" }]
9
+ requires-python = ">=3.11"
10
+ dependencies = []
11
+ keywords = ["clangd", "lsp", "c++", "cmake", "claude-code", "opencode"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Environment :: Console",
15
+ "Intended Audience :: Developers",
16
+ "Operating System :: MacOS",
17
+ "Operating System :: POSIX :: Linux",
18
+ "Programming Language :: C",
19
+ "Programming Language :: C++",
20
+ "Programming Language :: Python :: 3",
21
+ "Topic :: Software Development",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/Meirdrarel/clangd-nav"
26
+ Issues = "https://github.com/Meirdrarel/clangd-nav/issues"
27
+
28
+ [project.scripts]
29
+ clangd-nav = "clangd_nav.cli:main"
30
+
31
+ [dependency-groups]
32
+ dev = ["pytest>=8", "ruff>=0.8"]
33
+
34
+ [build-system]
35
+ requires = ["uv_build>=0.9,<0.14"]
36
+ build-backend = "uv_build"
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
40
+
41
+ [tool.ruff]
42
+ line-length = 100
43
+ target-version = "py311"
44
+
45
+ [tool.ruff.lint]
46
+ select = ["E", "F", "W", "I", "B", "UP", "SIM"]
@@ -0,0 +1,3 @@
1
+ """clangd for navigation only, for coding agents."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,39 @@
1
+ """clangd-nav: clangd for navigation only, for coding agents.
2
+
3
+ Arguments are passed on to clangd.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from .project import (
13
+ ClangdNotFound,
14
+ ConfigError,
15
+ compile_commands_dir,
16
+ find_clangd,
17
+ load_config,
18
+ project_root,
19
+ )
20
+ from .proxy import serve
21
+
22
+
23
+ def clangd_command(cwd: Path, env: dict[str, str], extra: list[str]) -> list[str]:
24
+ root = project_root(cwd)
25
+ config = load_config(root)
26
+ ccdir = compile_commands_dir(root, env, config)
27
+ cmd = [find_clangd(env, config, ccdir), "--clang-tidy=false", "--background-index"]
28
+ if ccdir:
29
+ cmd.append(f"--compile-commands-dir={ccdir}")
30
+ return cmd + extra + config.get("clangd_args", [])
31
+
32
+
33
+ def main(argv: list[str] | None = None) -> None:
34
+ args = sys.argv[1:] if argv is None else argv
35
+ try:
36
+ cmd = clangd_command(Path.cwd(), dict(os.environ), args)
37
+ except (ClangdNotFound, ConfigError) as e:
38
+ sys.exit(f"clangd-nav: {e}")
39
+ sys.exit(serve(cmd, sys.stdin.buffer, sys.stdout.buffer))
@@ -0,0 +1,100 @@
1
+ """The compiler a build tree was configured with, read from the tree itself.
2
+
3
+ The compile database names the compiler of each entry; CMake also records the compiler's
4
+ identity and version under CMakeFiles/<cmake version>/. From these, a clangd that matches
5
+ the project's clang can be found without any per-project configuration.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import shlex
14
+ import shutil
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ # Launchers that prefix the real compiler in a compile command.
19
+ WRAPPERS = frozenset({"ccache", "sccache", "distcc", "icecc", "buildcache"})
20
+
21
+ # clang, clang++, clang-cl, clang-cpp, optionally with a -N major suffix.
22
+ CLANG_NAME = re.compile(r"^clang(?:\+\+|-cl|-cpp)?(?:-(\d+))?$")
23
+
24
+ CMAKE_ID = re.compile(r'^set\(CMAKE_(?:CXX|C)_COMPILER_ID "([^"]*)"\)', re.M)
25
+ CMAKE_VERSION = re.compile(r'^set\(CMAKE_(?:CXX|C)_COMPILER_VERSION "(\d+)[^"]*"\)', re.M)
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class BuildCompiler:
30
+ path: str
31
+ is_clang: bool
32
+ major: str | None
33
+ """The LLVM major, when known. None for Apple clang, whose versions are not LLVM's."""
34
+
35
+
36
+ def database_compiler(ccdir: Path) -> str | None:
37
+ """The compiler of the first entry of ccdir/compile_commands.json, past any wrapper."""
38
+ try:
39
+ entries = json.loads((ccdir / "compile_commands.json").read_text())
40
+ except (OSError, ValueError):
41
+ return None
42
+ if not isinstance(entries, list):
43
+ return None
44
+ for entry in entries:
45
+ if not isinstance(entry, dict):
46
+ continue
47
+ args = entry.get("arguments") or shlex.split(entry.get("command", ""))
48
+ while args and Path(args[0]).name in WRAPPERS:
49
+ args = args[1:]
50
+ if not args:
51
+ continue
52
+ exe = args[0]
53
+ if os.sep in exe:
54
+ return str(Path(entry.get("directory", "")) / exe)
55
+ return shutil.which(exe) or exe
56
+ return None
57
+
58
+
59
+ def cmake_compiler_id(ccdir: Path) -> tuple[str | None, str | None]:
60
+ """(compiler id, major) as CMake recorded them in the build tree, C++ before C."""
61
+ files = [
62
+ *sorted(ccdir.glob("CMakeFiles/*/CMakeCXXCompiler.cmake")),
63
+ *sorted(ccdir.glob("CMakeFiles/*/CMakeCCompiler.cmake")),
64
+ ]
65
+ for f in files:
66
+ try:
67
+ text = f.read_text()
68
+ except OSError:
69
+ continue
70
+ ident = CMAKE_ID.search(text)
71
+ if ident:
72
+ version = CMAKE_VERSION.search(text)
73
+ return ident[1], version[1] if version else None
74
+ return None, None
75
+
76
+
77
+ def build_compiler(ccdir: Path) -> BuildCompiler | None:
78
+ path = database_compiler(ccdir)
79
+ if path is None:
80
+ return None
81
+ names = {Path(path).name, Path(path).resolve().name}
82
+ name_majors = [m[1] for n in names if (m := CLANG_NAME.match(n)) and m[1]]
83
+ cmake_id, cmake_major = cmake_compiler_id(ccdir)
84
+ is_clang = any(CLANG_NAME.match(n) for n in names) or cmake_id in ("Clang", "AppleClang")
85
+ if name_majors:
86
+ major = name_majors[0]
87
+ elif cmake_id == "Clang":
88
+ major = cmake_major
89
+ else:
90
+ major = None
91
+ return BuildCompiler(path, is_clang, major)
92
+
93
+
94
+ def sibling_clangds(compiler: BuildCompiler) -> list[str]:
95
+ """clangd next to a clang compiler, as named and with symlinks resolved."""
96
+ if not compiler.is_clang:
97
+ return []
98
+ named = Path(compiler.path).parent / "clangd"
99
+ resolved = Path(compiler.path).resolve().parent / "clangd"
100
+ return list(dict.fromkeys([str(named), str(resolved)]))
@@ -0,0 +1,30 @@
1
+ """LSP base-protocol framing over byte streams."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, BinaryIO
7
+
8
+ Message = dict[str, Any]
9
+
10
+
11
+ def read_message(stream: BinaryIO) -> tuple[bytes, Message] | None:
12
+ """One LSP message as (raw bytes, parsed body), or None at end of stream."""
13
+ head = b""
14
+ while not head.endswith(b"\r\n\r\n"):
15
+ byte = stream.read(1)
16
+ if not byte:
17
+ return None
18
+ head += byte
19
+ length = next(
20
+ int(line.split(b":", 1)[1])
21
+ for line in head.split(b"\r\n")
22
+ if line.lower().startswith(b"content-length:")
23
+ )
24
+ body = stream.read(length)
25
+ return head + body, json.loads(body)
26
+
27
+
28
+ def encode(msg: Message) -> bytes:
29
+ body = json.dumps(msg, separators=(",", ":")).encode()
30
+ return b"Content-Length: %d\r\n\r\n" % len(body) + body
@@ -0,0 +1,153 @@
1
+ """Where the project is, which clangd to run, which compile database to give it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import tomllib
9
+ from collections.abc import Mapping
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from .compiler import build_compiler, sibling_clangds
14
+
15
+ CONFIG_FILE = ".clangd-nav.toml"
16
+
17
+ # Key -> accepted types, for the configuration file.
18
+ CONFIG_KEYS: dict[str, tuple[type, ...]] = {
19
+ "clang_version": (int, str),
20
+ "build_dir": (str,),
21
+ "clangd_args": (list,),
22
+ }
23
+
24
+ Config = dict[str, Any]
25
+
26
+
27
+ class ClangdNotFound(Exception):
28
+ """No executable clangd among the candidates."""
29
+
30
+
31
+ class ConfigError(Exception):
32
+ """The configuration file cannot be read or holds an invalid value."""
33
+
34
+
35
+ def load_config(root: Path) -> Config:
36
+ """The project's .clangd-nav.toml, or {} when there is none."""
37
+ path = root / CONFIG_FILE
38
+ try:
39
+ with path.open("rb") as f:
40
+ config = tomllib.load(f)
41
+ except FileNotFoundError:
42
+ return {}
43
+ except (OSError, tomllib.TOMLDecodeError) as e:
44
+ raise ConfigError(f"{path}: {e}") from e
45
+ for key, value in config.items():
46
+ if key not in CONFIG_KEYS:
47
+ raise ConfigError(f"{path}: unknown key {key!r}")
48
+ if not isinstance(value, CONFIG_KEYS[key]):
49
+ raise ConfigError(f"{path}: {key!r} has the wrong type")
50
+ if not all(isinstance(a, str) for a in config.get("clangd_args", [])):
51
+ raise ConfigError(f"{path}: 'clangd_args' must be a list of strings")
52
+ return config
53
+
54
+
55
+ def project_root(cwd: Path) -> Path:
56
+ """The launch directory if it holds a .clangd, else its git repository, else itself."""
57
+ if (cwd / ".clangd").is_file():
58
+ return cwd
59
+ try:
60
+ top = subprocess.run(
61
+ ["git", "rev-parse", "--show-toplevel"],
62
+ cwd=cwd,
63
+ capture_output=True,
64
+ text=True,
65
+ check=True,
66
+ ).stdout.strip()
67
+ except (OSError, subprocess.CalledProcessError):
68
+ return cwd
69
+ return Path(top) if top else cwd
70
+
71
+
72
+ def pinned_major(env: Mapping[str, str], config: Config) -> str | None:
73
+ """The clang major the project pins: $CLANG_VERSION, else the configuration file."""
74
+ if env.get("CLANG_VERSION"):
75
+ return env["CLANG_VERSION"]
76
+ version = config.get("clang_version")
77
+ return str(version) if version is not None else None
78
+
79
+
80
+ def major_candidates(major: str) -> list[str]:
81
+ """Where clangd of one LLVM major is installed: Homebrew, apt.llvm.org, PATH."""
82
+ found = shutil.which(f"clangd-{major}")
83
+ return [
84
+ f"/opt/homebrew/opt/llvm@{major}/bin/clangd",
85
+ f"/usr/lib/llvm-{major}/bin/clangd",
86
+ *([found] if found else []),
87
+ ]
88
+
89
+
90
+ def wanted_major(env: Mapping[str, str], config: Config, ccdir: Path | None) -> str | None:
91
+ """The pinned major, else the major of the build's clang."""
92
+ pinned = pinned_major(env, config)
93
+ if pinned:
94
+ return pinned
95
+ compiler = build_compiler(ccdir) if ccdir else None
96
+ return compiler.major if compiler else None
97
+
98
+
99
+ def clangd_candidates(
100
+ env: Mapping[str, str], config: Config, ccdir: Path | None = None
101
+ ) -> list[str]:
102
+ """Paths to try, in order:
103
+
104
+ 1. the pinned major ($CLANG_VERSION, clang_version);
105
+ 2. the build's own clang: the clangd next to it, then its major's usual places;
106
+ 3. any clangd: for navigation a recent major will do, so it comes last, not never.
107
+ """
108
+ candidates: list[str] = []
109
+ pinned = pinned_major(env, config)
110
+ if pinned:
111
+ candidates += major_candidates(pinned)
112
+ compiler = build_compiler(ccdir) if ccdir else None
113
+ if compiler:
114
+ candidates += sibling_clangds(compiler)
115
+ if compiler.major:
116
+ candidates += major_candidates(compiler.major)
117
+ found = shutil.which("clangd")
118
+ candidates += ["/opt/homebrew/opt/llvm/bin/clangd", *([found] if found else [])]
119
+ return list(dict.fromkeys(candidates))
120
+
121
+
122
+ def find_clangd(env: Mapping[str, str], config: Config, ccdir: Path | None = None) -> str:
123
+ if env.get("CLANGD"):
124
+ return env["CLANGD"]
125
+ for c in clangd_candidates(env, config, ccdir):
126
+ if os.access(c, os.X_OK) and not os.path.isdir(c):
127
+ return c
128
+ major = wanted_major(env, config, ccdir)
129
+ raise ClangdNotFound(
130
+ "no clangd found (set CLANGD, or install llvm" + (f"@{major}" if major else "") + ")"
131
+ )
132
+
133
+
134
+ def compile_commands_dir(root: Path, env: Mapping[str, str], config: Config) -> Path | None:
135
+ """The directory holding the compile database clangd should use.
136
+
137
+ $CLANGD_NAV_BUILD_DIR, else the configuration file's build_dir, both relative to the
138
+ project; else build/; else the most recently configured build-*/ or cmake-build-*/
139
+ (another preset's or an IDE's tree).
140
+ """
141
+ build_dir = env.get("CLANGD_NAV_BUILD_DIR") or config.get("build_dir")
142
+ if build_dir:
143
+ return (root / build_dir).resolve()
144
+ if (root / "build/compile_commands.json").is_file():
145
+ return root / "build"
146
+ trees = sorted(
147
+ [
148
+ *root.glob("build-*/compile_commands.json"),
149
+ *root.glob("cmake-build-*/compile_commands.json"),
150
+ ],
151
+ key=lambda p: p.stat().st_mtime,
152
+ )
153
+ return trees[-1].parent if trees else None
@@ -0,0 +1,75 @@
1
+ """The diagnostics filter between the client and clangd.
2
+
3
+ Removed on the way out of clangd:
4
+ * textDocument/publishDiagnostics notifications (push diagnostics);
5
+ * diagnosticProvider from the initialize result (pull diagnostics).
6
+ Answered here, never forwarded to clangd:
7
+ * textDocument/diagnostic and workspace/diagnostic requests, with an empty report.
8
+ Everything else passes byte for byte.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import subprocess
14
+ import threading
15
+ from collections.abc import Sequence
16
+ from typing import BinaryIO
17
+
18
+ from .lsp import Message, encode, read_message
19
+
20
+ EMPTY_REPORTS: dict[str, Message] = {
21
+ "textDocument/diagnostic": {"kind": "full", "items": []},
22
+ "workspace/diagnostic": {"items": []},
23
+ }
24
+
25
+
26
+ def answer_locally(msg: Message) -> Message | None:
27
+ """The reply the proxy gives itself to a client message, or None to forward it."""
28
+ empty = EMPTY_REPORTS.get(msg.get("method"))
29
+ if empty is not None and "id" in msg:
30
+ return {"jsonrpc": "2.0", "id": msg["id"], "result": empty}
31
+ return None
32
+
33
+
34
+ def filter_server_message(msg: Message) -> tuple[bool, bool]:
35
+ """(keep, rewritten) for a message from clangd. Rewriting edits msg in place."""
36
+ if msg.get("method") == "textDocument/publishDiagnostics":
37
+ return False, False
38
+ result = msg.get("result")
39
+ caps = result.get("capabilities") if isinstance(result, dict) else None
40
+ if isinstance(caps, dict) and "diagnosticProvider" in caps:
41
+ del caps["diagnosticProvider"]
42
+ return True, True
43
+ return True, False
44
+
45
+
46
+ def serve(cmd: Sequence[str], client_in: BinaryIO, client_out: BinaryIO) -> int:
47
+ """Run clangd as cmd and proxy between it and the client. Returns clangd's exit status."""
48
+ server = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
49
+ assert server.stdin is not None and server.stdout is not None
50
+ out_lock = threading.Lock()
51
+
52
+ def send(data: bytes) -> None:
53
+ with out_lock:
54
+ client_out.write(data)
55
+ client_out.flush()
56
+
57
+ def client_to_server() -> None:
58
+ while (item := read_message(client_in)) is not None:
59
+ raw, msg = item
60
+ reply = answer_locally(msg)
61
+ if reply is not None:
62
+ send(encode(reply))
63
+ continue
64
+ server.stdin.write(raw)
65
+ server.stdin.flush()
66
+ server.stdin.close()
67
+
68
+ threading.Thread(target=client_to_server, daemon=True).start()
69
+
70
+ while (item := read_message(server.stdout)) is not None:
71
+ raw, msg = item
72
+ keep, rewritten = filter_server_message(msg)
73
+ if keep:
74
+ send(encode(msg) if rewritten else raw)
75
+ return server.wait()