claudecode.tools is the MCP tool registry and the set of tools that Claude Code can call in Neovim. The server (../server/README.md) sends each tools/list request to get_tool_list and each tools/call request to handle_invoke. Each tool file returns a table { name, schema, handler, requires_coroutine? }. init.lua registers these tables.
M.ERROR_CODES:PARSE_ERROR -32700,INVALID_REQUEST -32600,METHOD_NOT_FOUND -32601,INVALID_PARAMS -32602, andINTERNAL_ERROR -32000[tools/init.lua:M.ERROR_CODES]M.tools: a map from tool name to{ handler, schema, requires_coroutine }[tools/init.lua:M.tools]M.setup(server): stores the server and callsregister_all[tools/init.lua:M.setup]M.register(tool_module): requiresnameandhandler. Otherwise it callsvim.notifyat ERROR level and returns. It sends no MCP notification. A second module with the same name replaces the first without a warning [tools/init.lua:M.register]M.register_all(): registers 10 exposed tools and the internalclose_tab[tools/init.lua:M.register_all]M.get_tool_list(): returns{ name, description, inputSchema }only for tools that have aschema. It walksM.toolswithpairs(), so the order is not defined [tools/init.lua:M.get_tool_list]M.handle_invoke(client, params): looks upparams.nameand runs the tool withparams.arguments, or with{}when the call has none. It expects the params shape that the server'stools/callhandler checked [tools/init.lua:M.handle_invoke]M.build_response(ok, value, err): maps a handler outcome, aspcallorutils.resume_tool_coroutinereturns it, to{ result }or{ error }.handle_invokeuses it, and so doesdiff.open_diff_blockingwhen it resumes a deferred tool [tools/init.lua:M.build_response]
| MCP name | File | Required params | Exposed |
|---|---|---|---|
openFile |
open_file.lua |
filePath |
yes |
getCurrentSelection |
get_current_selection.lua |
none | yes |
getOpenEditors |
get_open_editors.lua |
none | yes |
openDiff |
open_diff.lua |
old_file_path, new_file_path, new_file_contents, tab_name |
yes |
getLatestSelection |
get_latest_selection.lua |
none | yes |
closeAllDiffTabs |
close_all_diff_tabs.lua |
none | yes |
getDiagnostics |
get_diagnostics.lua |
none (optional uri) |
yes |
getWorkspaceFolders |
get_workspace_folders.lua |
none | yes |
checkDocumentDirty |
check_document_dirty.lua |
filePath |
yes |
saveDocument |
save_document.lua |
filePath |
yes |
close_tab |
close_tab.lua |
tab_name |
no (schema = nil) |
Sources: [tools/init.lua:M.register_all], [tools/close_tab.lua:schema], [tools/open_diff.lua:requires_coroutine].
- An unknown tool, an empty
nameincluded, returns{ error = { code = -32601, message = "Tool not found: <name>" } }[tools/init.lua:M.handle_invoke] - An error that is a
{ code, message }table keeps its code, whether the handler raises it or returnsfalse, err. This holds for tools withrequires_coroutinetoo, also when the reply is sent after a deferred resume. Any other error maps to-32000[tools/init.lua:M.build_response] [diff.lua:M.open_diff_blocking] - A successful handler returns
{ result = <value> }[tools/init.lua:M.handle_invoke]. Each tool handler builds the MCP shape{ content = { { type = "text", text = ... } } }itself [tools/open_file.lua:handler].openDiffreturns the value ofdiff.open_diff_blockingunchanged, andclaudecode.diffbuilds that shape, orclaudecode.diff_inlinefor the unified layout [tools/open_diff.lua:handler] [diff.lua:M._resolve_diff_as_saved] - A call without
argumentsruns the tool with{}. A tool with a required parameter then raises-32602, andgetDiagnosticsreturns the diagnostics of all buffers. No handler enforcesadditionalProperties = false[tools/init.lua:M.handle_invoke] [tools/get_diagnostics.lua:handler] - Tools with
requires_coroutinerun incoroutine.create. If the coroutine yields,handle_invokereturns{ _deferred = true, coroutine, client, params }and sends no response yet. OnlyopenDiffsetsrequires_coroutine = true[tools/init.lua:M.handle_invoke] handle_invokeand the answer to a deferredopenDiffresume the tool's coroutine throughutils.resume_tool_coroutine. On a LuaJIT build older than 2023-09-21 (the release builds of Neovim 0.8 and 0.9 are such builds), or one whosejit.versionthe plugin cannot read, it turns the JIT off and flushes the compiled traces before it resumes the coroutine, and it gives the JIT back as it was when the resume returns. This guards against LuaJIT issue 1066, which aborts Neovim. On those builds each such resume discards the compiled traces of the whole editor, which LuaJIT compiles again when the code gets hot. Any other LuaJIT build gets a plaincoroutine.resume[utils.lua:M.resume_tool_coroutine] [tools/init.lua:M.handle_invoke] [diff.lua:M.open_diff_blocking]openDiffraises-32602when a required parameter is missing or is not a string, and withdata = "<name> must not contain a line break or a NUL"whenold_file_pathornew_file_pathholds a line feed, a carriage return or a NUL. Outside a non-main coroutine it raises-32000withmessage = "Internal server error"anddata = "openDiff must run in coroutine context". It raises-32000withdata = "Failed to load diff module"whenclaudecode.diffdoes not load [tools/open_diff.lua:handler]- After a deferred
openDiffyields,diff.open_diff_blockingmaps the outcome withbuild_responseand sends it through_G.claude_deferred_responses[tostring(co)], then clears that entry [diff.lua:M.open_diff_blocking] openDiffcallsdiff.open_diff_blocking(old, new, contents, tab_name, client.id). Structured errors pass through. Other errors become-32000"Error opening blocking diff" [tools/open_diff.lua:handler]openFile,checkDocumentDirty, andsaveDocumentraise-32602"Missing filePath parameter" whenfilePathis missing or is not a string [tools/open_file.lua:handler]openFileraises-32602withdata = "filePath must not contain a line break or a NUL"whenfilePathholds a line feed, a carriage return or a NUL, before any other check reads the path:vim.fn.filereadableraises E976 on a NUL [tools/open_file.lua:handler]openFileraises-32602before it opens the file whenstartLineorendLineis given but is not an integer (falseincluded),startLineis below 1 or past the last line, orendLineis belowstartLine. The last line comes from the loaded buffer that:editwould reuse, whichbufexists()andbufadd()find by name or by the inode Neovim cached for it, so a symlink or hard link finds it. Without one it comes from the file on disk. A buffer made before its file existed has no cached inode when another program creates the file, so a symlink to that file does not find it. For a loaded buffer without unsaved changes the file on disk counts too, because openFile loads the file again when it changed. When the buffer openFile then shows has fewer lines thanstartLine, openFile selects its last line. AnendLinepast the last line selects through the last line, and the answer names the lines it selected [tools/open_file.lua:handler]openFileraises-32000withmessage = "File operation error"anddata = "File not found: <path>"when the file is not readable, and withdata = "No preview window shows the file"when the preview window is closed or no longer has 'previewwindow' set after it gets the file, for example because an autocommand cleared it. It raises-32000and changes nothing while the command-line window is open, and when the user is in the middle of a command in the preview window, which openFile would reuse. Its defaults arepreview=false,makeFrontmost=true, andselectToEndOfLine=false[tools/open_file.lua:handler]openFileexpands~only whenfilePathis~or starts with~/(utils.expand_tilde). When onlyendLineis given,startLineis 1. When onlystartLineis given,endLineequals it [tools/open_file.lua:handler]openFilefindsstartTextandendTextas plain text and takes the first match. It searchesendTextafter thestartTextmatch, ignores an empty string, and appliesselectToEndOfLineonly whenendTextmatches. A text selection replaces a line range. WhenstartTextis not found, the call succeeds, and withmakeFrontmost=trueits answer starts withOpened file, but text "<startText>" not found[tools/open_file.lua:handler]- With
makeFrontmost=false,openFileanswers with JSON text{ success = true, filePath, languageId, lineCount }for the buffer it shows [tools/open_file.lua:handler] - The main editor window can be in another tab page, because
find_main_editor_windowscansnvim_list_wins(). WithmakeFrontmost=true, focusing it switches to that tab page [tools/open_file.lua:find_main_editor_window] checkDocumentDirtyandsaveDocumentreturn asuccess=falseJSON result (not an error) withDocument not open: <filePath>whenvim.fn.bufnr(filePath)is-1. They passfilePathtobufnr()unchanged, andbufnr()matches it as a file pattern. So a relative path, or a part that only one buffer name contains, finds that buffer, and an emptyfilePathfinds the current buffer. A buffer that exists but is unloaded counts as open [tools/save_document.lua:handler] [tools/check_document_dirty.lua:handler]saveDocumentreports a failed:writeas asuccess=falseresult withFailed to save file: <err>, not as an error.<err>is the Vim error (E<n>: …) when the message holds one, else the message's first line, so no Lua stack trace reaches Claude [tools/save_document.lua:handler]getDiagnosticsraises-32602whenuriis given but is not a string, before any other check. It raises-32000whenvim.lsp,vim.diagnostic, orvim.diagnostic.getis missing. It raises-32001"File not open" when no buffer exists foruri(vim.fn.bufnr(path) == -1). An unloaded buffer does not raise [tools/get_diagnostics.lua:handler]getDiagnosticsreturns a JSON array with one{ uri, diagnostics }entry per file. Each diagnostic hasmessage,severity(Error,Warning,Info, orHint), andrange. It hassource, andcodeas a string, only when the diagnostic has them. It drops a diagnostic that has no file path, so withouturithe diagnostics of unnamed buffers are left out [tools/get_diagnostics.lua:append_diagnostic] [tools/get_diagnostics.lua:severity_name]getLatestSelectionreturns asuccess=falseJSON result when no selection exists. Otherwise it returns the stored selection without asuccessfield [tools/get_latest_selection.lua:handler]- With no selection,
getCurrentSelectionreturnssuccess=falseonly when the active buffer has no name. When the Claude terminal is current, it answers from the window the user came from (winnr('#')), orsuccess=falsewhen there is none. When nothing is tracked (track_selection = false), it reads the editor at call time: the Visual or Select selection, or the cursor position [tools/get_current_selection.lua:handler] - When a selection is stored,
getCurrentSelectionreturns the same one asgetLatestSelection(selection.get_latest_selection()) and does not check that it belongs to the active buffer. It addssuccess=trueto each selection it returns [tools/get_current_selection.lua:handler] [selection.lua:M.get_latest_selection] getCurrentSelectionandgetLatestSelectionraise-32000withmessage = "Internal server error"anddata = "Failed to load selection module"whenclaudecode.selectiondoes not load [tools/get_current_selection.lua:handler] [tools/get_latest_selection.lua:handler]getCurrentSelectionraises-32000withmessage = "Internal server error"anddata = "Failed to encode <context>: <err>"whenvim.json.encodefails [tools/get_current_selection.lua:safe_json_encode]getOpenEditorslists only buffers that are loaded, listed, and named. It gives every buffer the handle of the current tab page, not its number, as its group (groupIndexis the handle minus 1), and puts the latest selection on the active buffer's entry without checking which file it came from [tools/get_open_editors.lua:handler]getWorkspaceFoldersalways returns one folder, built fromvim.fn.getcwd(). It adds no LSP workspace folders [tools/get_workspace_folders.lua:handler]close_tabraises-32602whentab_nameis missing or is not a string, like the other tools. It answersTAB_CLOSEDwhen it closes the diff, when it keeps a diff the user accepted for another client, when no diff has that name, and whenclaudecode.diffdoes not load. Whenclaudecode.loggerdoes not load, it returns{ code = -32603, message = "Internal error", data = "Failed to load logger module" }as a result, not as an error, and-32603is not inM.ERROR_CODES[tools/close_tab.lua:handler]
openFilerunseditin the main editor window, the first window that is not floating, a terminal, prompt, ornofilebuffer, a diff window, the preview window, or a file-explorer or outline sidebar. With preview it shows the file in the preview window of that tab page instead, and makes one aspeditdoes when the tab page has none. Likepedit, it shows the file there even when that window has 'winfixbuf' set. A buffer that is already loaded is not re-read, so its unsaved changes and the folds of other windows on it stay. When its file changed on disk, openFile loads a buffer without unsaved changes again, as:editdoes, and keeps a buffer with unsaved changes as it is, without asking the user. For that it adds a FileChangedShell autocommand for the buffer that runs after the user's and setsv:fcs_choice, so 'autoread' and a user'sv:fcs_choicedo not change the result. 'eventignore' or, on Neovim 0.11 and later, 'eventignorewin' can make Neovim skip that autocommand. For a window that already shows the buffer, openFile reads them as Neovim does, where 'eventignorewin' counts for the current window when it shows the buffer and otherwise only when every window that shows the buffer ignores the event. When the event is ignored there, openFile checks the file only with 'autoread', which loads it without asking, so with 'noautoread' the buffer keeps the old text. When openFile shows the buffer in a window that did not show it, and 'eventignore', or 'eventignorewin' of that window or of a window that shows the buffer, ignores the event, openFile turns Neovim's own check off for that step and then checks the file as for a window that shows the buffer. Autocommands that run during that step see the buffer's 'buftype' set toacwrite, which keeps 'modified' as it is. A plugin that skips buffers whose 'buftype' is set skips this one in those autocommands, until a window enters it again, and an autocommand that sets 'buftype' toacwriteitself is undone. Neovim refuses:wof a buffer opened before its file existed once the file exists (E13), and a write of anacwritebuffer skips that check. So for such a buffer the step also sets 'readonly', unless it is on already, and turns it off afterwards when it is still on. A write of it without!during the step then fails with E45 where Neovim gives E13. With 'confirm', Neovim asks "'readonly' option is set for ... Do you wish to write anyway?" where it would ask "Overwrite existing file ...?", and openFile answers Claude after the user does: yes writes. With 'writeany' orcpo+=O, Neovim would write that buffer, but the step still fails with E45. Autocommands of the step see 'readonly' on, one that sets 'readonly' itself is undone, and with 'shortmess' lackingFthe file message that:editshows during the step names[readonly]. A buffer renamed with:file, or one read with errors, gets 'readonly' only when openFile also tracks it as opened before its file existed, because no Neovim API tells such a buffer apart. Otherwise it gets no 'readonly' in the only step that runs for it, the one that 'eventignore' or 'eventignorewin' starts, and there the acwrite step skips the E13 that Neovim gives it outside the step. A write that 'readonly' does not stop goes to BufWriteCmd: without++nested, or without a user's BufWriteCmd autocommand that matches the file, none runs and the write fails with E676. In or out of openFile, a user's BufWriteCmd autocommand that matches the file, such asBufWriteCmd *that writes<afile>, writes the buffer over Claude's file when a write reaches it, because Neovim runs that autocommand before it checks whether the file changed. A write with!reaches it, and so does any write of a buffer whose file existed when the buffer was opened. That is how Neovim works, and openFile does not change it. Without such an autocommand, a write of a buffer with unsaved changes whose file Claude changed is a normal write outside the step. When a user's autocommand starts one while openFile switches buffers or windows, for exampleautocmd BufLeave * silent! wall, Neovim asks "The file has been changed since reading it!!! Do you really want to write to it (y/n)?", and openFile answers Claude only after the user does.ywrites the unsaved text over Claude's file.nor Escape writes nothing, and the buffer keeps its unsaved text. CTRL-C writes nothing, leaves the focus where it was, and fails openFile with "Keyboard interrupt". Other keys repeat the question. Afterythe answer to Claude also waits for Enter at Neovim's hit-enter prompt, on 0.8 and 0.10, and on 0.12 with the default 'messagesopt'. A buffer whose 'buftype' is already set is not checked, as Neovim does not check it. A buffer opened before its file existed, for which Neovim fired BufNewFile, gets the same step, because Neovim's question for it, W13, runs no FileChangedShell. Without unsaved changes openFile reads the file into it with:edit, except during Visual or Select mode that CTRL-O started, which:editwould end, and except when an autocommand showed another buffer in the window. Then the buffer keeps its text. With unsaved changes it keeps them, and a later:wfails with E13 until:w!. openFile knows such buffers from the time the Claude Code server starts. A buffer loaded before then counts when its file was missing at that time. No Neovim API tells such a buffer apart, so W13 can still come for one whose file appeared before the server started, or that was made while 'eventignore' ignored BufNewFile. A write that runs no BufWritePost does not end the tracking: one from an autocommand without++nested, such asautocmd BufLeave * update, or one through a BufWriteCmd handler. openFile then keeps running its acwrite step for that buffer, and reads the file into it again with:editwhen it has no unsaved changes. Neovim no longer asks W13 for that buffer, but it asks W12 when the buffer has unsaved text and its file changed. The acwrite step turns Neovim's check off, so no question comes, and unsaved text stays. Neovim can still ask when a user's FileChangedShell autocommand deletes openFile's: the user's autocommand then decides alone. An error in a user's autocommand fails openFile. Run from Lua, such an error during a reload stops the reload halfway and leaves the old text with empty lines added, while Neovim takes the file as read. So when the reload fails and the buffer has no unsaved changes, openFile reads the file again under:silent!, as a:checktimethat the user types would finish, before it fails: the buffer gets the whole file, and that read does not end Visual mode. This holds for an error in any autocommand of the reload, including BufReadPre, which stops the BufReadPre autocommands after it, and FileChangedShell, which Neovim runs before it reads. A buffer with unsaved changes keeps its text. When no suitable window exists, it can split or move windows. It splits instead of editing into a diff or preview window, splits the window below the preview window instead of the preview window itself, and withmakeFrontmost=falsegives the focus back to the window that had it. With preview it splits only to make the preview window when the tab page has none, so a terminal keeps one window. Then it works in the window that shows the file. For line or text ranges it searches that window's buffer and sets the visual marks and the cursor there.makeFrontmostfocuses that window, and withmakeFrontmost=falsethe JSON answer describes its buffer. Visual mode exists only in the current window, so withmakeFrontmost=falseand another window current, the marks are set but no selection stays on. With preview this holds even when the current window shows the same file, because the file goes to the preview window. With 'selection' set to inclusive, a range that ends on an empty line also covers that line's line break. WhenendTextis not found, it only places the cursor on thestartTextmatch. It never changes the buffer. It ends any Visual or Select mode before it selects, it always selects charwise, andgvis the last key it sends, so with 'selectmode' containingcmdthe selection is left in Select mode. When the user is in the middle of a command, it leaves the current window, its cursor, and the mode alone. That covers an operator such asdthat waits for its motion, Insert mode, Replace mode, CTRL-O from them, and the command line. On Neovim 0.10 and later it also covers Visual or Select mode that CTRL-O started, whichstate()shows asS. On 0.8 and 0.9 that mode looks like plain Visual mode, so openFile ends it and selects as usual: after the call the mode isvwith Claude's selection in the opened file, the user's next Visual command acts on that selection, and Insert mode then resumes in the opened file. It shows the file in the preview window, places the cursor there, selects nothing, does not focus it, and sends no keys, so the user's next keys finish the command where it started. When the command runs in the buffer of that file, the rules above can still load the file into it, and the user's next keys then act on the new text. The answer says so, except themakeFrontmost=falseJSON. A register prefix such as"alooks like Normal mode, so openFile works as usual and the user's next command acts in the opened file. A count or a prefix such asgor CTRL-W blocks Neovim, which reads no request until the next key [tools/open_file.lua:handler]openDiffopens a blocking diff throughclaudecode.diff. The response stays deferred until the user accepts or rejects the diff [tools/open_diff.lua:handler]. A diff that resolves beforeopenDiffyields, for example from aClaudeCodeDiffOpenedhandler, is answered at once [diff.lua:M.open_diff_blocking]saveDocumentrunswritein the matching buffer withnvim_buf_call[tools/save_document.lua:handler]closeAllDiffTabscallsdiff.close_all_diffs("closeAllDiffTabs tool", client.id)and returnsCLOSED_<n>_DIFF_TABS.ncounts only the diffs it closed: a diff the user accepted for another client stays open and is not counted [tools/close_all_diff_tabs.lua:handler] [diff.lua:M.close_all_diffs]close_tabcallsdiff.close_diff_by_tab_namewith the tab name and the calling client. It closes or deletes no other buffer, whatever the name [tools/close_tab.lua:handler]- Both close tools resolve a pending diff as rejected first, which resumes the waiting
openDiffwithDIFF_REJECTED. When an accepted diff closes, the buffers of its file that have no unsaved changes load the file again 100 ms later [diff.lua:M.close_diff_by_tab_name] - Loading
open_file.luacreates theClaudeCodeOpenFileNewFilesaugroup (BufNewFile,BufReadPost/BufUnload, andBufWritePostautocmds) that tracks buffers opened before their file existed, and marks each loaded buffer that has a name and an empty 'buftype' and whose file is not readable at that time [tools/open_file.lua:new_file_buffers] getCurrentSelection,getLatestSelection,getOpenEditors,getWorkspaceFolders, andcheckDocumentDirtyonly read editor state, with one exception. When no selection is stored,getCurrentSelectioncallsselection.is_claude_terminal_buffer, whose call toterminal.get_active_terminal_bufnr()can adopt a Claude terminal that an earlier copy of the plugin started (the first call after a plugin reload). Thenativeprovider then adds aTermCloseautocmd to that buffer, and thesnacksprovider patches the instance [tools/get_open_editors.lua:handler] [tools/get_current_selection.lua:handler] [selection.lua:M.is_claude_terminal_buffer] [terminal/native.lua:M.get_active_bufnr] [terminal/snacks.lua:M.get_active_bufnr]getDiagnosticsreads editor state and writes debug log entries throughclaudecode.logger[tools/get_diagnostics.lua:handler]handle_invokewrites debug log entries throughclaudecode.loggeron therequires_coroutinepath [tools/init.lua:M.handle_invoke]close_tabwrites debug and error log entries throughclaudecode.logger[tools/close_tab.lua:handler]
- Run:
mise run test - Targeted:
busted -v tests/unit/tools_spec.lua,busted -v tests/unit/tools/open_file_spec.lua,busted -v tests/unit/tools/open_diff_mcp_spec.lua,busted -v tests/unit/tools/get_diagnostics_spec.lua,busted -v tests/unit/tools/save_document_spec.lua,busted -v tests/unit/tools/close_tab_spec.lua,busted -v tests/unit/tools/get_current_selection_spec.lua,busted -v tests/unit/tools/get_open_editors_spec.lua,busted -v tests/integration/mcp_tools_spec.lua - Real Neovim:
scripts/run_integration_tests_individually.shruns eachtests/integration/*_spec.luafile in headless Neovim with plenary.nvim. It runstests/integration/open_file_selection_spec.lua, whichbustedonly marks as pending