Skip to content

Latest commit

 

History

History
88 lines (74 loc) · 26.6 KB

README.md

File metadata and controls

88 lines (74 loc) · 26.6 KB

claudecode.tools

Overview

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.

Interface

Registry (init.lua)

  • M.ERROR_CODES: PARSE_ERROR -32700, INVALID_REQUEST -32600, METHOD_NOT_FOUND -32601, INVALID_PARAMS -32602, and INTERNAL_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 calls register_all [tools/init.lua:M.setup]
  • M.register(tool_module): requires name and handler. Otherwise it calls vim.notify at 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 internal close_tab [tools/init.lua:M.register_all]
  • M.get_tool_list(): returns { name, description, inputSchema } only for tools that have a schema. It walks M.tools with pairs(), so the order is not defined [tools/init.lua:M.get_tool_list]
  • M.handle_invoke(client, params): looks up params.name and runs the tool with params.arguments, or with {} when the call has none. It expects the params shape that the server's tools/call handler checked [tools/init.lua:M.handle_invoke]
  • M.build_response(ok, value, err): maps a handler outcome, as pcall or utils.resume_tool_coroutine returns it, to { result } or { error }. handle_invoke uses it, and so does diff.open_diff_blocking when it resumes a deferred tool [tools/init.lua:M.build_response]

Registered tools

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].

Invariants

  • An unknown tool, an empty name included, 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 returns false, err. This holds for tools with requires_coroutine too, 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]. openDiff returns the value of diff.open_diff_blocking unchanged, and claudecode.diff builds that shape, or claudecode.diff_inline for the unified layout [tools/open_diff.lua:handler] [diff.lua:M._resolve_diff_as_saved]
  • A call without arguments runs the tool with {}. A tool with a required parameter then raises -32602, and getDiagnostics returns the diagnostics of all buffers. No handler enforces additionalProperties = false [tools/init.lua:M.handle_invoke] [tools/get_diagnostics.lua:handler]
  • Tools with requires_coroutine run in coroutine.create. If the coroutine yields, handle_invoke returns { _deferred = true, coroutine, client, params } and sends no response yet. Only openDiff sets requires_coroutine = true [tools/init.lua:M.handle_invoke]
  • handle_invoke and the answer to a deferred openDiff resume the tool's coroutine through utils.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 whose jit.version the 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 plain coroutine.resume [utils.lua:M.resume_tool_coroutine] [tools/init.lua:M.handle_invoke] [diff.lua:M.open_diff_blocking]
  • openDiff raises -32602 when a required parameter is missing or is not a string, and with data = "<name> must not contain a line break or a NUL" when old_file_path or new_file_path holds a line feed, a carriage return or a NUL. Outside a non-main coroutine it raises -32000 with message = "Internal server error" and data = "openDiff must run in coroutine context". It raises -32000 with data = "Failed to load diff module" when claudecode.diff does not load [tools/open_diff.lua:handler]
  • After a deferred openDiff yields, diff.open_diff_blocking maps the outcome with build_response and sends it through _G.claude_deferred_responses[tostring(co)], then clears that entry [diff.lua:M.open_diff_blocking]
  • openDiff calls diff.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, and saveDocument raise -32602 "Missing filePath parameter" when filePath is missing or is not a string [tools/open_file.lua:handler]
  • openFile raises -32602 with data = "filePath must not contain a line break or a NUL" when filePath holds a line feed, a carriage return or a NUL, before any other check reads the path: vim.fn.filereadable raises E976 on a NUL [tools/open_file.lua:handler]
  • openFile raises -32602 before it opens the file when startLine or endLine is given but is not an integer (false included), startLine is below 1 or past the last line, or endLine is below startLine. The last line comes from the loaded buffer that :edit would reuse, which bufexists() and bufadd() 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 than startLine, openFile selects its last line. An endLine past the last line selects through the last line, and the answer names the lines it selected [tools/open_file.lua:handler]
  • openFile raises -32000 with message = "File operation error" and data = "File not found: <path>" when the file is not readable, and with data = "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 -32000 and 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 are preview=false, makeFrontmost=true, and selectToEndOfLine=false [tools/open_file.lua:handler]
  • openFile expands ~ only when filePath is ~ or starts with ~/ (utils.expand_tilde). When only endLine is given, startLine is 1. When only startLine is given, endLine equals it [tools/open_file.lua:handler]
  • openFile finds startText and endText as plain text and takes the first match. It searches endText after the startText match, ignores an empty string, and applies selectToEndOfLine only when endText matches. A text selection replaces a line range. When startText is not found, the call succeeds, and with makeFrontmost=true its answer starts with Opened file, but text "<startText>" not found [tools/open_file.lua:handler]
  • With makeFrontmost=false, openFile answers 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_window scans nvim_list_wins(). With makeFrontmost=true, focusing it switches to that tab page [tools/open_file.lua:find_main_editor_window]
  • checkDocumentDirty and saveDocument return a success=false JSON result (not an error) with Document not open: <filePath> when vim.fn.bufnr(filePath) is -1. They pass filePath to bufnr() unchanged, and bufnr() matches it as a file pattern. So a relative path, or a part that only one buffer name contains, finds that buffer, and an empty filePath finds the current buffer. A buffer that exists but is unloaded counts as open [tools/save_document.lua:handler] [tools/check_document_dirty.lua:handler]
  • saveDocument reports a failed :write as a success=false result with Failed 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]
  • getDiagnostics raises -32602 when uri is given but is not a string, before any other check. It raises -32000 when vim.lsp, vim.diagnostic, or vim.diagnostic.get is missing. It raises -32001 "File not open" when no buffer exists for uri (vim.fn.bufnr(path) == -1). An unloaded buffer does not raise [tools/get_diagnostics.lua:handler]
  • getDiagnostics returns a JSON array with one { uri, diagnostics } entry per file. Each diagnostic has message, severity (Error, Warning, Info, or Hint), and range. It has source, and code as a string, only when the diagnostic has them. It drops a diagnostic that has no file path, so without uri the diagnostics of unnamed buffers are left out [tools/get_diagnostics.lua:append_diagnostic] [tools/get_diagnostics.lua:severity_name]
  • getLatestSelection returns a success=false JSON result when no selection exists. Otherwise it returns the stored selection without a success field [tools/get_latest_selection.lua:handler]
  • With no selection, getCurrentSelection returns success=false only when the active buffer has no name. When the Claude terminal is current, it answers from the window the user came from (winnr('#')), or success=false when 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, getCurrentSelection returns the same one as getLatestSelection (selection.get_latest_selection()) and does not check that it belongs to the active buffer. It adds success=true to each selection it returns [tools/get_current_selection.lua:handler] [selection.lua:M.get_latest_selection]
  • getCurrentSelection and getLatestSelection raise -32000 with message = "Internal server error" and data = "Failed to load selection module" when claudecode.selection does not load [tools/get_current_selection.lua:handler] [tools/get_latest_selection.lua:handler]
  • getCurrentSelection raises -32000 with message = "Internal server error" and data = "Failed to encode <context>: <err>" when vim.json.encode fails [tools/get_current_selection.lua:safe_json_encode]
  • getOpenEditors lists 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 (groupIndex is 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]
  • getWorkspaceFolders always returns one folder, built from vim.fn.getcwd(). It adds no LSP workspace folders [tools/get_workspace_folders.lua:handler]
  • close_tab raises -32602 when tab_name is missing or is not a string, like the other tools. It answers TAB_CLOSED when it closes the diff, when it keeps a diff the user accepted for another client, when no diff has that name, and when claudecode.diff does not load. When claudecode.logger does not load, it returns { code = -32603, message = "Internal error", data = "Failed to load logger module" } as a result, not as an error, and -32603 is not in M.ERROR_CODES [tools/close_tab.lua:handler]

Side Effects

  • openFile runs edit in the main editor window, the first window that is not floating, a terminal, prompt, or nofile buffer, 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 as pedit does when the tab page has none. Like pedit, 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 :edit does, 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 sets v:fcs_choice, so 'autoread' and a user's v:fcs_choice do 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 to acwrite, 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' to acwrite itself is undone. Neovim refuses :w of a buffer opened before its file existed once the file exists (E13), and a write of an acwrite buffer 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' or cpo+=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' lacking F the file message that :edit shows 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 as BufWriteCmd * 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 example autocmd 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. y writes the unsaved text over Claude's file. n or 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. After y the 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 :edit would 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 :w fails 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 as autocmd 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 :edit when 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 :checktime that 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 with makeFrontmost=false gives 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. makeFrontmost focuses that window, and with makeFrontmost=false the JSON answer describes its buffer. Visual mode exists only in the current window, so with makeFrontmost=false and 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. When endText is not found, it only places the cursor on the startText match. It never changes the buffer. It ends any Visual or Select mode before it selects, it always selects charwise, and gv is the last key it sends, so with 'selectmode' containing cmd the 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 as d that 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, which state() shows as S. 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 is v with 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 the makeFrontmost=false JSON. A register prefix such as "a looks 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 as g or CTRL-W blocks Neovim, which reads no request until the next key [tools/open_file.lua:handler]
  • openDiff opens a blocking diff through claudecode.diff. The response stays deferred until the user accepts or rejects the diff [tools/open_diff.lua:handler]. A diff that resolves before openDiff yields, for example from a ClaudeCodeDiffOpened handler, is answered at once [diff.lua:M.open_diff_blocking]
  • saveDocument runs write in the matching buffer with nvim_buf_call [tools/save_document.lua:handler]
  • closeAllDiffTabs calls diff.close_all_diffs("closeAllDiffTabs tool", client.id) and returns CLOSED_<n>_DIFF_TABS. n counts 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_tab calls diff.close_diff_by_tab_name with 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 openDiff with DIFF_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.lua creates the ClaudeCodeOpenFileNewFiles augroup (BufNewFile, BufReadPost/BufUnload, and BufWritePost autocmds) 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, and checkDocumentDirty only read editor state, with one exception. When no selection is stored, getCurrentSelection calls selection.is_claude_terminal_buffer, whose call to terminal.get_active_terminal_bufnr() can adopt a Claude terminal that an earlier copy of the plugin started (the first call after a plugin reload). The native provider then adds a TermClose autocmd to that buffer, and the snacks provider 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]
  • getDiagnostics reads editor state and writes debug log entries through claudecode.logger [tools/get_diagnostics.lua:handler]
  • handle_invoke writes debug log entries through claudecode.logger on the requires_coroutine path [tools/init.lua:M.handle_invoke]
  • close_tab writes debug and error log entries through claudecode.logger [tools/close_tab.lua:handler]

Verification

  • 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.sh runs each tests/integration/*_spec.lua file in headless Neovim with plenary.nvim. It runs tests/integration/open_file_selection_spec.lua, which busted only marks as pending