{"repo_name": "mcphub.nvim", "file_name": "/mcphub.nvim/lua/mcphub/native/utils/server.lua", "inference_info": {"prefix_code": "local Request = require(\"mcphub.native.utils.request\")\nlocal Response = require(\"mcphub.native.utils.response\")\nlocal State = require(\"mcphub.state\")\nlocal buf_utils = require(\"mcphub.native.neovim.utils.buffer\")\nlocal log = require(\"mcphub.utils.log\")\n\n---@class MCPTool\n---@field name string Tool identifier\n---@field description string|fun():string Tool description or function returning description\n---@field inputSchema? table|fun():table JSON Schema for input validation or function returning schema\n---@field handler fun(req: ToolRequest, res: ToolResponse): nil | table Tool handler function\n---@field needs_confirmation_window? boolean Whether the tool requires a confirmation window before execution\n\n---@class MCPResource\n---@field name? string Resource identifier\n---@field description? string|fun():string Resource description or function returning description\n---@field mimeType? string Resource MIME type (e.g., \"text/plain\")\n---@field uri string Static URI (e.g., \"system://info\")\n---@field handler fun(req: ResourceRequest, res: ResourceResponse): nil | table Resource handler function\n\n---@class MCPPromptArgument\n---@field name string Argument name\n---@field description? string Argument description\n---@field required? boolean Whether the argument is required\n---@field default? string Default value for the argument\n\n---@class MCPPrompt\n---@field name? string Prompt identifier\n---@field description? string|fun():string Prompt description or function returning description\n---@field arguments? MCPPromptArgument[]|fun():MCPPromptArgument[] List of arguments\n---@field handler? fun(req: PromptRequest, res: PromptResponse): nil | table\n\n---@class MCPResourceTemplate\n---@field name? string Template identifier\n---@field description? string|fun():string Template description or function returning description\n---@field mimeType? string Template MIME type (e.g., \"text/plain\")\n---@field uriTemplate string URI with parameters (e.g., \"buffer://{bufnr}/lines\")\n---@field handler fun(req: ResourceRequest, res: ResourceResponse): nil | table Template handler function\n\n---@class MCPCapabilities\n---@field tools? MCPTool[] List of tools\n---@field resources? MCPResource[] List of resources\n---@field resourceTemplates? MCPResourceTemplate[] List of resource templates\n---@field prompts? MCPPrompt[] List of prompts\n\n---@class NativeServer\n---@field name string Server name\n---@field displayName? string Display name\n---@field description? string Server description\n---@field status string Server status (connected|disconnected|disabled)\n---@field error? string|nil Error message if any\n---@field capabilities MCPCapabilities Server capabilities\n---@field uptime? number Server uptime\n---@field lastStarted? number Last started timestamp\n---@field config_source string Include which config file this server came from\n---@field is_native boolean Flag to indicate this is a native server\nlocal NativeServer = {}\nNativeServer.__index = NativeServer\n\nlocal TIMEOUT = 5 -- seconds\n\n-- Helper function to extract params from uri using template\n-- Note: Parameter values containing slashes (/) or special characters must be URL encoded\n-- Example: For a template \"file/read/{path}\"\n-- - \"file/read/home%2Fuser%2Ffile.txt\" ✓ (correctly encoded)\n-- - \"file/read/home/user/file.txt\" ✗ (will not match)\n\nlocal function extract_params(uri, template)\n local params = {}\n\n -- Convert template into pattern with url-encoded char support\n local pattern = template:gsub(\"{([^}]+)}\", \"([^/]+)\")\n\n -- Get param names from template\n local names = {}\n for name in template:gmatch(\"{([^}]+)}\") do\n table.insert(names, name)\n end\n\n -- Match URI against pattern\n local values = { uri:match(\"^\" .. pattern .. \"$\") }\n if #values == 0 then\n return nil\n end\n\n -- Map matched values to param names and decode them\n for i, name in ipairs(names) do\n -- URL decode the parameter value\n local decoded = values[i]:gsub(\"%%(%x%x)\", function(hex)\n return string.char(tonumber(hex, 16))\n end)\n params[name] = decoded\n end\n\n return params\nend\n\n-- Helper function to find matching resource\nfunction NativeServer:find_matching_resource(uri)\n -- Check direct resources first\n for _, resource in ipairs(self.capabilities.resources) do\n if resource.uri == uri then\n log.debug(string.format(\"Matched uri\"))\n return resource, {}\n end\n end\n\n -- Check templates\n for _, template in ipairs(self.capabilities.resourceTemplates) do\n -- Extract params using template\n log.debug(string.format(\"Matching uri '%s' against template '%s'\", uri, template.uriTemplate))\n local params = extract_params(uri, template.uriTemplate)\n if params then\n log.debug(string.format(\"Matched uri template with params: %s\", vim.inspect(params)))\n return template, params\n end\n end\n\n return nil\nend\n\n--- Create a new native server instance\n---@param def table Server definition with name capabilities etc\n---@return NativeServer | nil Server instance or nil on error\nfunction NativeServer:new(def)\n -- Validate required fields\n if not def.name then\n log.warn(\"NativeServer definition must include name\")\n return\n end\n if not def.capabilities then\n log.warn(\"NativeServer definition must include capabilities\")\n return\n end\n\n log.debug({\n code = \"NATIVE_SERVER_INIT\",\n message = \"Creating new native server\",\n data = { name = def.name, capabilities = def.capabilities },\n })\n\n local instance = ", "suffix_code": "\n setmetatable(instance, self)\n\n -- Initialize capabilities\n instance:initialize(def)\n\n return instance\nend\n\n--- Initialize or reinitialize server capabilities\n---@param def table Server definition\nfunction NativeServer:initialize(def)\n -- Reset error state\n self.error = nil\n self.capabilities = {\n tools = def.capabilities.tools or {},\n resources = def.capabilities.resources or {},\n resourceTemplates = def.capabilities.resourceTemplates or {},\n prompts = def.capabilities.prompts or {},\n }\n\n local config_manager = require(\"mcphub.utils.config_manager\")\n -- Get server config\n local server_config = config_manager.get_server_config(self) or {}\n -- Check if server is disabled\n if server_config.disabled then\n self.status = \"disabled\"\n return\n end\n self.status = \"connected\"\n self.lastStarted = os.time()\nend\n\nfunction NativeServer:get_prompt(name, arguments, opts)\n opts = opts or {}\n -- Create output handler\n local got_prompt = false\n local prompt_result, prompt_error\n local function output_handler(result, err)\n if got_prompt then\n return\n end\n prompt_result = result\n prompt_error = err\n got_prompt = true\n if opts.callback then\n opts.callback(result, err)\n return\n end\n return result, err\n end\n log.debug(string.format(\"Getting prompt '%s' on server '%s'\", name, self.name))\n -- Check server state\n if self.status ~= \"connected\" then\n local err = string.format(\"Server '%s' is not connected (status: %s)\", self.name, self.status)\n log.warn(string.format(\"Server '%s' is not connected (status: %s)\", self.name, self.status))\n return output_handler(nil, err)\n end\n\n -- Find tool in capabilities\n local prompt\n for _, p in ipairs(self.capabilities.prompts) do\n if p.name == name then\n prompt = p\n break\n end\n end\n if not prompt then\n local err = string.format(\"Prompt '%s' not found\", name)\n log.warn(string.format(\"Prompt '%s' not found\", name))\n return output_handler(nil, err)\n end\n\n local editor_info = buf_utils.get_editor_info()\n -- Create req/res objects with full context\n local req = Request.PromptRequest:new({\n server = self,\n prompt = prompt,\n arguments = arguments,\n caller = opts.caller,\n editor_info = editor_info,\n })\n local res = Response.PromptResponse:new(output_handler, prompt.name, prompt.description)\n\n -- Execute tool with req/res\n local ok, result = pcall(prompt.handler, req, res)\n if not ok then\n log.warn(string.format(\"Tool execution failed: %s\", result))\n return res:error(result)\n end\n\n -- Handle synchronous return if any\n if result ~= nil then\n return output_handler(result)\n end\n -- If native_server:get_prompt is a synchronous call but the handler didn't return anything or is running asynchronously given the res:send() arch\n -- Wait for the handler to finish until TIMEOUT as if the user didn't call res:send() this will never finish\n -- The only place the nativeserver is called synchronously is while a chat resolving prompt\n local start_time = os.time()\n if not opts.callback then\n while not got_prompt do\n vim.wait(500)\n if os.time() - start_time > TIMEOUT then\n return output_handler(nil, \"Prompt access timed out\")\n end\n end\n return prompt_result, prompt_error\n end\nend\n\n--- Execute a tool by name\n---@param name string Tool name to execute\n---@param arguments table Arguments for the tool\n---@return table|nil result Tool execution result\n---@return string|nil error Error message if any\nfunction NativeServer:call_tool(name, arguments, opts)\n opts = opts or {}\n -- Create output handler\n -- Track if tool has completed to prevent double-handling\n local tool_finished = false\n local tool_result, tool_error\n local function output_handler(result, err)\n if tool_finished then\n return\n end\n tool_result = result\n tool_error = err\n tool_finished = true\n if opts.callback then\n opts.callback(result, err)\n return\n end\n return result, err\n end\n log.debug(string.format(\"Calling tool '%s' on server '%s'\", name, self.name))\n -- Check server state\n if self.status ~= \"connected\" then\n local err = string.format(\"Server '%s' is not connected (status: %s)\", self.name, self.status)\n log.warn(string.format(\"Server '%s' is not connected (status: %s)\", self.name, self.status))\n return output_handler(nil, err)\n end\n\n -- Find tool in capabilities\n local tool\n for _, t in ipairs(self.capabilities.tools) do\n if t.name == name then\n tool = t\n break\n end\n end\n if not tool then\n local err = string.format(\"Tool '%s' not found\", name)\n log.warn(string.format(\"Tool '%s' not found\", name))\n return output_handler(nil, err)\n end\n\n local editor_info = buf_utils.get_editor_info()\n -- Create req/res objects with full context\n local req = Request.ToolRequest:new({\n server = self,\n tool = tool,\n arguments = arguments,\n caller = opts.caller,\n editor_info = editor_info,\n })\n local res = Response.ToolResponse:new(output_handler)\n\n -- Execute tool with req/res\n local ok, result = pcall(tool.handler, req, res)\n if not ok then\n log.warn(string.format(\"Tool execution failed: %s\", result))\n return res:error(result)\n end\n\n -- Handle synchronous return if any\n if result ~= nil then\n return output_handler(result)\n end\n -- -- If native_server:call_tool is a synchronous call but the handler didn't return anything or is running asynchronously given the res:send() arch\n -- -- Wait for the handler to finish until TIMEOUT as if the user didn't call res:send() this will never finish\n -- -- The only place the nativeserver is called synchronously is while a chat resolving #resource variable in the chat when submitted\n local start_time = os.time()\n if not opts.callback then\n while not tool_finished do\n vim.wait(500)\n if os.time() - start_time > TIMEOUT then\n return output_handler(nil, \"Tool execution timed out\")\n end\n end\n return tool_result, tool_error\n end\nend\n\nfunction NativeServer:access_resource(uri, opts)\n opts = opts or {}\n -- Create output handler\n -- Track if resource has called to prevent double-handling\n local resource_accessed = false\n local resource_result, resource_error\n local function output_handler(result, err)\n if resource_accessed then\n return\n end\n resource_result = result\n resource_error = err\n resource_accessed = true\n if opts.callback then\n opts.callback(result, err)\n return\n end\n return result, err\n end\n -- Check server state\n if self.status ~= \"connected\" then\n return output_handler(nil, string.format(\"Server '%s' is not connected (status: %s)\", self.name, self.status))\n end\n\n log.debug(string.format(\"Accessing resource '%s' on server '%s'\", uri, self.name))\n -- Find matching resource/template and extract params\n local resource, params = self:find_matching_resource(uri)\n if not resource then\n local err = string.format(\"Resource '%s' not found\", uri)\n log.warn(string.format(\"Resource '%s' not found\", uri))\n return output_handler(nil, err)\n end\n\n -- Check if resource has handler\n if not resource.handler then\n local err = \"Resource has no handler\"\n log.warn(string.format(\"Resource '%s' has no handler\", uri))\n return output_handler(nil, err)\n end\n\n local editor_info = buf_utils.get_editor_info()\n -- Create req/res objects with full context\n local req = Request.ResourceRequest:new({\n server = self,\n resource = resource,\n uri = uri,\n template = resource.uriTemplate,\n editor_info = editor_info,\n params = params,\n caller = opts.caller,\n })\n local res = Response.ResourceResponse:new(output_handler, uri, resource.uriTemplate)\n\n -- Call resource handler with req/res\n local ok, result = pcall(resource.handler, req, res)\n if not ok then\n log.warn(string.format(\"Resource access failed: %s\", result))\n return res:error(result --[[@as string]])\n end\n\n -- Handle synchronous return if any\n if result ~= nil then\n return output_handler(result)\n end\n -- call_resource will be called synchronously when chat is trying to resolve #resourcevariable(that we populated dynamically based on available servers) when chat:submit(),\n -- If native_server:call_resource is a synchronous call but the handler didn't return anything or is running asynchronously given the res:send() arch\n -- Wait for the handler to finish until TIMEOUT as if the user didn't call res:send() this will never finish\n local start_time = os.time()\n if not opts.callback then\n while not resource_accessed do\n vim.wait(500)\n if (os.time() - start_time) > TIMEOUT then\n return output_handler(nil, \"Resource access timed out\")\n end\n end\n return resource_result, resource_error\n end\nend\n\nfunction NativeServer:start()\n -- Check server state\n if self.status == \"connected\" then\n return true\n end\n self.status = \"connected\"\n self.lastStarted = os.time()\n return true\nend\n\nfunction NativeServer:stop(disable)\n disable = disable or false\n -- if disable then\n self.status = \"disabled\"\n -- else\n -- self.status = \"disconnected\"\n -- end\nend\n\nreturn NativeServer\n", "middle_code": "{\n name = def.name,\n displayName = def.displayName or def.name,\n description = def.description or \"\",\n status = \"connected\",\n error = nil,\n capabilities = {\n tools = {},\n resources = {},\n resourceTemplates = {},\n prompts = {},\n },\n uptime = 0,\n lastStarted = os.time(),\n config_source = State.config.config,\n is_native = true, \n }", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "lua", "sub_task_type": null}, "context_code": [["/mcphub.nvim/lua/mcphub/hub.lua", "local Error = require(\"mcphub.utils.errors\")\nlocal Job = require(\"plenary.job\")\nlocal State = require(\"mcphub.state\")\nlocal config = require(\"mcphub.config\")\nlocal config_manager = require(\"mcphub.utils.config_manager\")\nlocal constants = require(\"mcphub.utils.constants\")\nlocal curl = require(\"plenary.curl\")\nlocal version = require(\"mcphub.utils.version\")\nlocal workspace_utils = require(\"mcphub.utils.workspace\")\n\nlocal handlers = require(\"mcphub.utils.handlers\")\nlocal log = require(\"mcphub.utils.log\")\nlocal native = require(\"mcphub.native\")\nlocal prompt_utils = require(\"mcphub.utils.prompt\")\nlocal utils = require(\"mcphub.utils\")\n\n-- Default timeouts\nlocal CONNECT_TIMEOUT = 1000 -- 1s for curl to connect to localhost\nlocal TOOL_TIMEOUT = 60000 -- 60s for tool calls\nlocal RESOURCE_TIMEOUT = 60000 -- 60s for resource access\nlocal PROMPT_TIMEOUT = 60000 -- 60s for tool calls\nlocal MCP_REQUEST_TIMEOUT = 60000 -- 60s for MCP requests\n\n--- @class MCPHub.Hub\n--- @field port number The port number for the MCP Hub server\n--- @field server_url string In case of hosting mcp-hub somewhere, the url with `https://mydomain.com:5858`\n--- @field config string Path to the MCP servers configuration file\n--- @field auto_toggle_mcp_servers boolean whether to enable LLM to start and stop MCP Servers\n--- @field shutdown_delay number Delay in seconds before shutting down the server\n--- @field cmd string The cmd to invoke the MCP Hub server\n--- @field cmdArgs table The args to pass to the cmd to spawn the server\n--- @field ready boolean Whether the connection to server is ready\n--- @field server_job Job|nil The server process job if we started it\n--- @field is_owner boolean Whether this instance started the server\n--- @field is_shutting_down boolean Whether we're in the process of shutting down\n--- @field mcp_request_timeout number --Max time allowed for a MCP tool or resource to execute in milliseconds, set longer for long running tasks\n--- @field on_ready fun(hub)\n--- @field on_error fun(error:string)\n--- @field setup_opts table Original options used to create this hub instance\nlocal MCPHub = {}\nMCPHub.__index = MCPHub\n\n--- Create a new MCPHub instance\n--- @param opts table Configuration options\n--- @return MCPHub.Hub\nfunction MCPHub:new(opts)\n local instance = setmetatable({\n port = opts.port,\n server_url = opts.server_url,\n config = opts.config,\n auto_toggle_mcp_servers = opts.auto_toggle_mcp_servers,\n shutdown_delay = opts.shutdown_delay,\n cmd = opts.cmd,\n cmdArgs = opts.cmdArgs,\n ready = false,\n server_job = nil,\n is_owner = false,\n is_shutting_down = false,\n is_starting = false,\n mcp_request_timeout = opts.mcp_request_timeout or MCP_REQUEST_TIMEOUT,\n on_ready = opts.on_ready or function() end,\n on_error = opts.on_error or function() end,\n setup_opts = opts,\n }, MCPHub)\n\n -- Setup global state tracking\n instance:_setup_global_state_tracking()\n\n return instance\nend\n\n--- Resolve context (workspace vs global) for the current directory\n--- @return MCPHub.JobContext|nil Context information or nil on error\nfunction MCPHub:resolve_context()\n if not State.config.workspace.enabled then\n return self:_resolve_global_context()\n end\n\n return self:_resolve_workspace_context()\nend\n\n--- Resolve workspace-specific context\n--- @return MCPHub.JobContext|nil Workspace context or nil to fall back to global\nfunction MCPHub:_resolve_workspace_context()\n local cwd = vim.fn.getcwd()\n\n -- Find workspace config\n local workspace_info = workspace_utils.find_workspace_config(State.config.workspace.look_for, cwd)\n\n if not workspace_info then\n -- No workspace config found, fall back to global mode\n log.debug(\"No workspace config found, falling back to global mode\")\n return self:_resolve_global_context()\n end\n\n log.debug(\"Found workspace config\" .. vim.inspect(workspace_info))\n\n local port\n\n -- Prepare config files (order matters: global first, then project)\n local global_config = self.config -- Original global config path\n local project_config = workspace_info.config_file\n local config_files = { global_config, project_config }\n\n -- Check for existing hub using root and config_file because using hashed port might not be reliable when we found next available port if a port is occupied\n local existing_hub = workspace_utils.find_matching_workspace_hub(workspace_info.root_dir, config_files)\n if existing_hub then\n port = existing_hub.port\n log.debug(\"Found existing workspace hub\" .. vim.inspect({\n workspace_root = workspace_info.root_dir,\n port = port,\n pid = existing_hub.pid,\n }))\n else\n if State.config.workspace.get_port and type(State.config.workspace.get_port) == \"function\" then\n -- Use custom port function if provided\n port = State.config.workspace.get_port()\n if not port or type(port) ~= \"number\" then\n vim.notify(\"Invalid port returned by workspace.get_port function\", vim.log.levels.ERROR)\n return nil\n end\n log.debug(\"Using custom port from workspace.get_port: \" .. port)\n else\n -- Generate new port\n port = workspace_utils.find_available_port(\n workspace_info.root_dir,\n State.config.workspace.port_range,\n 100 -- max attempts\n )\n end\n\n if not port then\n vim.notify(\"No available ports for workspace hub\", vim.log.levels.ERROR)\n return nil\n end\n\n log.debug(\"Generated new port for workspace\" .. vim.inspect({\n workspace_root = workspace_info.root_dir,\n port = port,\n }))\n end\n\n return {\n port = port,\n cwd = workspace_info.root_dir or cwd,\n config_files = config_files,\n is_workspace_mode = true,\n workspace_root = workspace_info.root_dir or cwd,\n existing_hub = existing_hub, -- Include hub info from cache\n }\nend\n\n--- Resolve global context (original behavior)\n--- @return MCPHub.JobContext Global context\nfunction MCPHub:_resolve_global_context()\n local cwd = vim.fn.getcwd()\n local port = self.setup_opts.port\n -- For global mode, port will always be the one provided in setup_opts, so we can get the existing hub using that\n local existing_hub = workspace_utils.get_workspace_hub_info(port)\n return {\n port = port,\n cwd = cwd,\n config_files = { self.config },\n is_workspace_mode = false,\n workspace_root = cwd,\n existing_hub = existing_hub,\n }\nend\n\n--- Resolve global environment variables\n--- @param context MCPHub.JobContext Hub context (workspace info, port, etc.)\n--- @return table Resolved global environment variables\nfunction MCPHub:_resolve_global_env(context)\n local global_env_config = config.global_env\n local resolved_global_env = {}\n\n -- Handle function type\n if type(global_env_config) == \"function\" then\n local success, result = pcall(global_env_config, context)\n if not success then\n vim.notify(\"global_env function failed: \" .. result, vim.log.levels.WARN)\n return {}\n end\n if type(result) ~= \"table\" then\n vim.notify(\"global_env function must return a table\", vim.log.levels.WARN)\n return {}\n end\n global_env_config = result\n elseif type(global_env_config) ~= \"table\" then\n if global_env_config ~= nil then\n vim.notify(\"global_env must be table or function\", vim.log.levels.WARN)\n end\n return {}\n end\n\n -- Process mixed array/hash format\n for key, value in pairs(global_env_config) do\n if type(key) == \"number\" then\n -- Array-style entry: just the env var name\n if type(value) == \"string\" then\n local env_value = os.getenv(value)\n if env_value then\n resolved_global_env[value] = env_value\n end\n end\n else\n -- Hash-style entry: key = value\n if type(value) == \"string\" then\n resolved_global_env[key] = value\n end\n end\n end\n\n return resolved_global_env\nend\n\n--- Start server with resolved context\n--- @param context MCPHub.JobContext Context information from resolve_context\nfunction MCPHub:_start_server_with_context(context)\n self.is_owner = true\n if self.server_job then\n self.server_job = nil\n end\n\n -- Resolve global environment variables\n local resolved_global_env = self:_resolve_global_env(context)\n\n -- Build command args with config files\n local args = utils.clean_args({\n self.cmdArgs,\n \"--port\",\n tostring(context.port),\n })\n\n -- Add all config files (global first, then project-specific)\n for _, config_file in ipairs(context.config_files) do\n table.insert(args, \"--config\")\n table.insert(args, config_file)\n end\n\n -- Add other flags\n vim.list_extend(args, {\n \"--auto-shutdown\",\n \"--shutdown-delay\",\n self.shutdown_delay or 0,\n \"--watch\",\n })\n\n -- Prepare job environment with global env\n local job_env = {}\n if next(resolved_global_env) then\n -- Serialize global env for mcp-hub\n local success, json_env = pcall(vim.fn.json_encode, resolved_global_env)\n if success then\n job_env.MCP_HUB_ENV = json_env\n log.debug(\"Passing global environment variables to mcp-hub: \" .. vim.inspect({\n count = vim.tbl_count(resolved_global_env),\n keys = vim.tbl_keys(resolved_global_env),\n }))\n else\n vim.notify(\"Failed to serialize global_env: \" .. json_env, vim.log.levels.WARN)\n end\n end\n job_env = vim.tbl_extend(\"force\", vim.fn.environ(), { CWD = context.cwd }, job_env or {})\n\n log.debug(\"Starting server with context\" .. vim.inspect({\n port = context.port,\n cwd = context.cwd,\n config_files = context.config_files,\n is_workspace_mode = context.is_workspace_mode,\n }))\n\n ---@diagnostic disable-next-line: missing-fields\n self.server_job = Job:new({\n command = self.cmd,\n args = args,\n cwd = context.cwd, -- Set working directory\n env = job_env, -- Pass environment variables\n hide = true,\n on_stderr = vim.schedule_wrap(function(_, data)\n if data then\n log.debug(\"Server stderr:\" .. data)\n end\n end),\n on_start = vim.schedule_wrap(function()\n self:connect_sse()\n end),\n on_stdout = vim.schedule_wrap(function(_, _)\n -- if data then\n -- log.debug(\"Server stdout:\" .. data)\n -- end\n end),\n on_exit = vim.schedule_wrap(function(j, code)\n local stderr = table.concat(j:stderr_result() or {}, \"\\n\")\n log.debug(\"Server process exited with code \" .. code .. \" and stderr: \" .. stderr)\n if stderr:match(\"EADDRINUSE\") then\n -- The on_start's self:connect_sse() will handle this case\n log.debug(\"Port taken, trying to connect...\")\n else\n -- This is causing issues when switching workspaces frequently even when we check for server_job\n -- sse_job's on_exit will anyway takes care of showing stopped status in case the mcp-hub was stopped externally\n -- local err_msg = \"Server process exited with code \" .. code\n -- self:handle_hub_stopped(err_msg .. \"\\n\" .. stderr, code, j)\n end\n end),\n })\n\n self.server_job:start()\nend\n\n--- Start the MCP Hub server\nfunction MCPHub:start()\n if self.is_starting then\n vim.notify(\"MCP Hub is starting\", vim.log.levels.WARN)\n return\n end\n log.debug(\"Starting hub\")\n State:clear_logs()\n -- Update state\n State:update_hub_state(constants.HubState.STARTING)\n self.is_restarting = false\n self.is_starting = true\n\n -- Resolve context (workspace vs global)\n local context = self:resolve_context()\n if not context then\n self:handle_hub_stopped(\"Failed to resolve hub context\")\n return\n end\n\n -- Update state with resolved context\n State.current_hub = context\n self.port = context.port -- Update our port for this session\n\n -- Load config cache into state\n local cache_loaded, refresh_err = config_manager.refresh_config()\n if not cache_loaded then\n self:handle_hub_stopped(\"Failed to load MCP servers configuration:\" .. (refresh_err or \"\"))\n return\n end\n log.debug(\"Resolved hub context: \" .. vim.inspect(context))\n\n -- Make sure to load after the config is refreshed to avoid double reading of config files\n native.setup(config.native_servers)\n\n -- Step 3: Check if server is already running on the resolved port and is of same version in cases of plugin updated\n self:check_server(function(is_running, is_our_server, is_same_version)\n if is_running then\n if not is_our_server then\n self:handle_hub_stopped(\"Port in use by non-MCP Hub server\")\n return\n end\n if not is_same_version then\n log.debug(\"Existing server is not of same version, restarting\")\n vim.notify(\"mcp-hub version mismatch. Restarting hub...\", vim.log.levels.INFO)\n self:handle_same_port_different_config(context)\n return\n end\n if not context.existing_hub then\n log.debug(\n \"Port available but no existing hub info, might be due to changed config files, starting new server\"\n )\n self:handle_same_port_different_config(context)\n return\n end\n\n -- Check config compatibility using cached hub info\n if context.existing_hub and context.existing_hub.config_files then\n local config_matches = vim.deep_equal(context.existing_hub.config_files, context.config_files)\n if config_matches then\n log.debug(\"Config files match, connecting to existing server\")\n self:connect_sse()\n else\n log.debug(\"Config files changed, restarting server\")\n vim.notify(\"Config files changed. Restarting hub...\", vim.log.levels.INFO)\n self:handle_same_port_different_config(context)\n end\n else\n -- No config info available (backwards compatibility)\n log.debug(\"No config info in cache, connecting to existing server\")\n self:connect_sse()\n end\n return\n end\n\n -- Step 4: Start new server with resolved context\n self:_start_server_with_context(context)\n end)\nend\n\n--- Handle directory changes - reconnect to appropriate workspace hub\nfunction MCPHub:handle_directory_change()\n if not State.config.workspace.enabled then\n return\n end\n\n log.debug(\"Directory changed, checking if workspace hub should change\")\n\n -- Resolve new context for current directory\n local new_context = self:resolve_context()\n if not new_context then\n log.warn(\"Failed to resolve context after directory change\")\n return\n end\n\n -- Compare with current context\n local current_context = State.current_hub\n if not current_context then\n log.debug(\"No current hub context, starting new hub\")\n self:start()\n return\n end\n\n -- Check if we need to switch hubs\n local needs_switch = false\n local reason = \"\"\n\n if tostring(new_context.port) ~= tostring(current_context.port) then\n needs_switch = true\n reason = string.format(\"port change (%s -> %s)\", current_context.port, new_context.port)\n end\n\n if needs_switch then\n log.debug(\"Switching hub due to: \" .. reason)\n -- self:restart(nil, reason)\n self:stop_sse()\n vim.schedule(function()\n self:start()\n end)\n else\n log.debug(\"No hub switch needed - context unchanged\")\n end\nend\n\nfunction MCPHub:handle_hub_ready()\n self.ready = true\n self.is_restarting = false\n self.is_starting = false\n self:_update_global_state()\n self.on_ready(self)\n self:update_servers()\n if State.marketplace_state.status == \"empty\" then\n self:get_marketplace_catalog()\n end\nend\n\nfunction MCPHub:_clean_up()\n self.is_owner = false\n self.ready = false\n self.is_starting = false\n self.is_restarting = false\n self:stop_sse()\n State:update_hub_state(constants.HubState.STOPPED)\n self:_update_global_state()\nend\n\n---@param msg string\n---@param code number|nil\nfunction MCPHub:handle_hub_stopped(msg, code, server_job)\n if server_job then\n -- While changing directories, we might have to start a new job for that directory\n -- Once in the new directory, if the old directory's job stops for any reason for e.g (shutdown_delay reached)\n -- handle_hub_stopped will be called which causes the hub UI to show as stopped.\n -- Therefore, we need to check if the server_job is the same as the one that called this function\n if self.server_job ~= server_job then\n return\n end\n end\n code = code ~= nil and code or 1\n -- if self.is_shutting_down then\n -- return -- Skip error handling during shutdown\n -- end\n if code ~= 0 then\n -- Create error object\n local err = Error(\"SERVER\", Error.Types.SERVER.SERVER_START, msg)\n State:add_error(err)\n self.on_error(tostring(err))\n end\n self:_clean_up()\nend\n\n--- Check if server is running and handle connection\n--- @param callback fun(is_running:boolean, is_our_server:boolean, is_same_version:boolean) Callback function to handle the result\nfunction MCPHub:check_server(callback)\n log.debug(\"Checking Server\")\n if self:is_ready() then\n return callback(true, true, true)\n end\n -- Quick health check\n local opts = {\n timeout = 3000,\n skip_ready_check = true,\n }\n\n opts.callback = function(response, err)\n if err then\n log.debug(\"Error while get health in check_server\")\n callback(false, false, false)\n else\n local is_hub_server = response and response.server_id == \"mcp-hub\" and response.status == \"ok\"\n local is_same_version = response and response.version == version.REQUIRED_NODE_VERSION.string\n log.debug(\n string.format(\n \"Got health response in check_server, is_hub_server (%s), is_same_version (%s) \",\n tostring(is_hub_server),\n tostring(is_same_version)\n )\n )\n callback(true, is_hub_server, is_same_version) -- Running but may not be our server\n end\n end\n return self:get_health(opts)\nend\n\n--- Get server status information\n--- @param opts? { callback?: fun(response: table?, error: string?) } Optional callback(response: table|nil, error?: string)\n--- @return table|nil, string|nil If no callback is provided, returns response and error\nfunction MCPHub:get_health(opts)\n return self:api_request(\"GET\", \"health\", opts)\nend\n\n---@param name string\n---@return NativeServer | MCPServer | nil\nfunction MCPHub:get_server(name)\n local is_native = native.is_native_server(name)\n if is_native then\n return is_native\n end\n for _, server in ipairs(State.server_state.servers) do\n if server.name == name then\n return server\n end\n end\n return nil\nend\n\n---@param url string The OAuth callback URL\nfunction MCPHub:handle_oauth_callback(url, callback)\n if not url or vim.trim(url) == \"\" then\n return vim.notify(\"No OAuth callback URL provided\", vim.log.levels.ERROR)\n end\n self:api_request(\"POST\", \"oauth/manual_callback\", {\n body = {\n url = url,\n },\n callback = callback,\n })\nend\n\n---@param name any\n---@param _ any\nfunction MCPHub:authorize_mcp_server(name, _)\n -- local authUrl = self:get_server(name)[\"authorizationUrl\"]\n self:api_request(\"POST\", \"servers/authorize\", {\n body = {\n server_name = name,\n },\n callback = function(response, _)\n --Errors will be handled automatically\n if response and response.authorizationUrl then\n vim.notify(\"Opening Authorization URL: \" .. response.authorizationUrl, vim.log.levels.INFO)\n else\n vim.notify(\"No Authorization URL found for server: \" .. name, vim.log.levels.WARN)\n end\n end,\n })\nend\n\n--- Start a disabled/disconnected MCP server\n---@param name string Server name to start\n---@param opts? { via_curl_request?:boolean,callback?: function }\n---@return table?, string? If no callback is provided, returns response and error\nfunction MCPHub:start_mcp_server(name, opts)\n opts = opts or {}\n if not self:update_server_config(name, {\n disabled = false,\n }) then\n return\n end\n local is_native = native.is_native_server(name)\n if is_native then\n local server = is_native\n server:start()\n State:emit(\"servers_updated\", {\n hub = self,\n })\n else\n for i, server in ipairs(State.server_state.servers) do\n if server.name == name then\n State.server_state.servers[i].status = \"connecting\"\n break\n end\n end\n\n --only if we want to send a curl request (otherwise file watch and sse events autoupdates)\n --This is needed in cases where users need to start the server and need to be sure if it is started or not rather than depending on just file watching\n --Note: this will update the config in the state in the backend which will not trigger file change event as this is sometimes updated before the file change event is triggered so the backend explicitly sends SubscriptionEvent with type servers_updated. which leads to \"no signigicant changes\" notification as well as \"servers updated\" notification as we send this explicitly.\n if opts.via_curl_request then\n -- Call start endpoint\n self:api_request(\"POST\", \"servers/start\", {\n body = {\n server_name = name,\n },\n callback = function(response, err)\n self:refresh()\n if opts.callback then\n opts.callback(response, err)\n end\n end,\n })\n end\n end\n State:notify_subscribers({\n server_state = true,\n }, \"server\")\nend\n\n--- Stop an MCP server\n---@param name string Server name to stop\n---@param disable boolean Whether to disable the server\n---@param opts? { via_curl_request?: boolean, callback?: function } Optional callback(response: table|nil, error?: string)\n---@return table|nil, string|nil If no callback is provided, returns response and error\nfunction MCPHub:stop_mcp_server(name, disable, opts)\n opts = opts or {}\n\n if not self:update_server_config(name, {\n disabled = disable or false,\n }) then\n return\n end\n local is_native = native.is_native_server(name)\n if is_native then\n local server = is_native\n server:stop()\n State:emit(\"servers_updated\", {\n hub = self,\n })\n else\n for i, server in ipairs(State.server_state.servers) do\n if server.name == name then\n State.server_state.servers[i].status = \"disconnecting\"\n break\n end\n end\n\n --only if we want to send a curl request (otherwise file watch and sse events autoupdates)\n if opts.via_curl_request then\n -- Call stop endpoint\n self:api_request(\"POST\", \"servers/stop\", {\n query = disable and {\n disable = \"true\",\n } or nil,\n body = {\n server_name = name,\n },\n callback = function(response, err)\n self:refresh()\n if opts.callback then\n opts.callback(response, err)\n end\n end,\n })\n end\n end\n State:notify_subscribers({\n server_state = true,\n }, \"server\")\nend\n\n--- Get a prompt from the server\n--- @param server_name string\n--- @param prompt_name string\n--- @param args table\n--- @param opts? {parse_response?: boolean, callback?: fun(res: MCPResponseOutput? ,err: string?), request_options?: MCPRequestOptions, timeout?: number } Optional callback(response: table|nil, error?: string) and timeout in ms (default 60s)\n--- @return {messages : {role:\"user\"| \"assistant\"|\"system\", output: MCPResponseOutput}[]}|nil, string|nil If no callback is provided, returns response and error\nfunction MCPHub:get_prompt(server_name, prompt_name, args, opts)\n opts = opts or {}\n if opts.callback then\n local original_callback = opts.callback\n opts.callback = function(response, err)\n -- Signal prompt completion\n utils.fire(\"MCPHubPromptEnd\", {\n server = server_name,\n prompt = prompt_name,\n success = err == nil,\n })\n if opts.parse_response == true then\n response = prompt_utils.parse_prompt_response(response)\n end\n if original_callback then\n original_callback(response, err)\n end\n end\n end\n\n local request_options =\n vim.tbl_deep_extend(\"force\", { timeout = self.mcp_request_timeout }, opts.request_options or {})\n -- Signal prompt start\n utils.fire(\"MCPHubPromptStart\", {\n server = server_name,\n prompt = prompt_name,\n })\n local arguments = args or vim.empty_dict()\n if vim.islist(arguments) or vim.isarray(arguments) then\n if #arguments == 0 then\n arguments = vim.empty_dict()\n else\n log.error(\"Arguments should be a dictionary, but got a list.\")\n return\n end\n end\n --make sure we have an object\n -- Check native servers first\n local is_native = native.is_native_server(server_name)\n if is_native then\n local server = is_native\n local result, err = server:get_prompt(prompt_name, args, opts)\n if opts.callback == nil then\n utils.fire(\"MCPHubPromptEnd\", {\n server = server_name,\n prompt = prompt_name,\n success = err == nil,\n })\n return (opts.parse_response == true and prompt_utils.parse_prompt_response(result) or result), err\n end\n return\n end\n\n local response, err = self:api_request(\n \"POST\",\n \"servers/prompts\",\n vim.tbl_extend(\"force\", {\n timeout = (request_options.timeout + 5000) or PROMPT_TIMEOUT,\n body = {\n server_name = server_name,\n prompt = prompt_name,\n arguments = arguments,\n request_options = request_options,\n },\n }, opts)\n )\n\n -- handle sync calls\n if opts.callback == nil then\n utils.fire(\"MCPHubPromptEnd\", {\n server = server_name,\n prompt = prompt_name,\n success = err == nil,\n })\n return (opts.parse_response == true and prompt_utils.parse_prompt_response(response) or response), err\n end\nend\n\n--- Call a tool on a server\n--- @param server_name string\n--- @param tool_name string\n--- @param args table\n--- @param opts? {parse_response?: boolean, callback?: fun(res: MCPResponseOutput? ,err: string?), request_options?: MCPRequestOptions, timeout?: number } Optional callback(response: table|nil, error?: string) and timeout in ms (default 60s)\n--- @return MCPResponseOutput?, string? If no callback is provided, returns response and error\nfunction MCPHub:call_tool(server_name, tool_name, args, opts)\n opts = opts or {}\n if opts.callback then\n local original_callback = opts.callback\n opts.callback = function(response, err)\n -- Signal tool completion\n utils.fire(\"MCPHubToolEnd\", {\n server = server_name,\n tool = tool_name,\n response = prompt_utils.parse_tool_response(response),\n success = err == nil,\n })\n if opts.parse_response == true then\n response = prompt_utils.parse_tool_response(response)\n end\n if original_callback then\n original_callback(response, err)\n end\n end\n end\n local request_options =\n vim.tbl_deep_extend(\"force\", { timeout = self.mcp_request_timeout }, opts.request_options or {})\n -- Signal tool start\n utils.fire(\"MCPHubToolStart\", {\n server = server_name,\n tool = tool_name,\n })\n local arguments = args or vim.empty_dict()\n if vim.islist(arguments) or vim.isarray(arguments) then\n if #arguments == 0 then\n arguments = vim.empty_dict()\n else\n log.error(\"Arguments should be a dictionary, but got a list.\")\n return\n end\n end\n -- Check native servers first\n local is_native = native.is_native_server(server_name)\n if is_native then\n local server = is_native\n local result, err = server:call_tool(tool_name, args, opts)\n if opts.callback == nil then\n utils.fire(\"MCPHubToolEnd\", {\n server = server_name,\n tool = tool_name,\n response = prompt_utils.parse_tool_response(result),\n success = err == nil,\n })\n return (opts.parse_response == true and prompt_utils.parse_tool_response(result) or result), err\n end\n return\n end\n\n local response, err = self:api_request(\n \"POST\",\n \"servers/tools\",\n vim.tbl_extend(\"force\", {\n ---Make sure that actual curl request timeout is more than the MCP request timeout\n timeout = (request_options.timeout + 5000) or TOOL_TIMEOUT,\n body = {\n server_name = server_name,\n tool = tool_name,\n arguments = arguments,\n request_options = request_options,\n },\n }, opts)\n )\n\n -- handle sync calls\n if opts.callback == nil then\n utils.fire(\"MCPHubToolEnd\", {\n server = server_name,\n tool = tool_name,\n response = prompt_utils.parse_tool_response(response),\n success = err == nil,\n })\n return (opts.parse_response == true and prompt_utils.parse_tool_response(response) or response), err\n end\nend\n\n--- Access a server resource\n--- @param server_name string\n--- @param uri string\n--- @param opts? {parse_response?: boolean, callback?: fun(res: MCPResponseOutput? ,err: string?), request_options?: MCPRequestOptions, timeout?: number } Optional callback(response: table|nil, error?: string) and timeout in ms (default 60s)\n--- @return MCPResponseOutput?, string? If no callback is provided, returns response and error\nfunction MCPHub:access_resource(server_name, uri, opts)\n opts = opts or {}\n if opts.callback then\n local original_callback = opts.callback\n opts.callback = function(response, err)\n -- Signal resource completion\n utils.fire(\"MCPHubResourceEnd\", {\n server = server_name,\n uri = uri,\n success = err == nil,\n })\n if opts.parse_response == true then\n response = prompt_utils.parse_resource_response(response)\n end\n if original_callback then\n original_callback(response, err)\n end\n end\n end\n\n local request_options =\n vim.tbl_deep_extend(\"force\", { timeout = self.mcp_request_timeout }, opts.request_options or {})\n -- Signal resource start\n utils.fire(\"MCPHubResourceStart\", {\n server = server_name,\n uri = uri,\n })\n\n -- Check native servers first\n local is_native = native.is_native_server(server_name)\n if is_native then\n local server = is_native\n local result, err = server:access_resource(uri, opts)\n if opts.callback == nil then\n utils.fire(\"MCPHubResourceEnd\", {\n server = server_name,\n uri = uri,\n success = err == nil,\n })\n return (opts.parse_response == true and prompt_utils.parse_resource_response(result) or result), err\n end\n return\n end\n\n -- Otherwise proxy to MCP server\n local response, err = self:api_request(\n \"POST\",\n \"servers/resources\",\n vim.tbl_extend(\"force\", {\n ---Make sure that actual curl request timeout is more than the MCP request timeout\n timeout = (request_options.timeout + 5000) or RESOURCE_TIMEOUT,\n body = {\n server_name = server_name,\n uri = uri,\n request_options = request_options,\n },\n }, opts)\n )\n -- handle sync calls\n if opts.callback == nil then\n utils.fire(\"MCPHubResourceEnd\", {\n server = server_name,\n uri = uri,\n success = err == nil,\n })\n return (opts.parse_response == true and prompt_utils.parse_resource_response(response) or response), err\n end\nend\n\n--- API request helper\n--- @param method string HTTP method\n--- @param path string API path\n--- @param opts? { body?: table, timeout?: number, skip_ready_check?: boolean, callback?: fun(response: table?, error: string?), query?: table }\n--- @return table|nil, string|nil If no callback is provided, returns response and error\nfunction MCPHub:api_request(method, path, opts)\n opts = opts or {}\n local callback = opts.callback\n -- the url of the mcp-hub server if it is hosted somewhere (e.g. https://mydomain.com)\n local base_url = self.server_url or string.format(\"http://localhost:%d\", self.port)\n --remove any trailing slashes\n base_url = base_url:gsub(\"/+$\", \"\")\n\n -- Build URL with query parameters if any\n local url = string.format(\"%s/api/%s\", base_url, path)\n if opts.query then\n local params = {}\n for k, v in pairs(opts.query) do\n table.insert(params, k .. \"=\" .. v)\n end\n url = url .. \"?\" .. table.concat(params, \"&\")\n end\n\n local raw = {}\n vim.list_extend(raw, {\n \"--connect-timeout\",\n tostring(vim.fn.floor(CONNECT_TIMEOUT / 1000)),\n })\n if opts.timeout then\n local timeout_seconds = tostring(vim.fn.floor((opts.timeout or TOOL_TIMEOUT) / 1000))\n vim.list_extend(raw, {\n \"--max-time\",\n timeout_seconds,\n })\n end\n\n -- Prepare request options\n local request_opts = {\n url = url,\n method = method,\n --INFO: generating custom headers file path to avoid getting .header file not found when simulataneous requests are sent\n dump = utils.gen_dump_path(),\n headers = {\n [\"Content-Type\"] = \"application/json\",\n [\"Accept\"] = \"application/json\",\n },\n raw = raw,\n on_error = vim.schedule_wrap(function(err)\n log.debug(string.format(\"Error while making request to %s: %s\", path, vim.inspect(err)))\n local error = handlers.ResponseHandlers.process_error(err)\n if not self:is_ready() and path == \"health\" then\n if callback then\n callback(nil, tostring(error))\n end\n else\n if callback then\n callback(nil, tostring(error))\n end\n State:add_error(error)\n end\n end),\n }\n if opts.body then\n request_opts.body = vim.fn.json_encode(opts.body)\n end\n\n -- Only skip ready check for health check\n if not opts.skip_ready_check and not self.ready and path ~= \"health\" then\n local err = Error(\"SERVER\", Error.Types.SERVER.INVALID_STATE, \"MCP Hub not ready\")\n State:add_error(err)\n if callback then\n callback(nil, tostring(err))\n return\n else\n return nil, tostring(err)\n end\n end\n\n -- Process response\n local function process_response(response)\n local curl_error = handlers.ResponseHandlers.handle_curl_error(response, request_opts)\n if curl_error then\n State:add_error(curl_error)\n if callback then\n callback(nil, tostring(curl_error))\n return\n else\n return nil, tostring(curl_error)\n end\n end\n\n local http_error = handlers.ResponseHandlers.handle_http_error(response, request_opts)\n if http_error then\n State:add_error(http_error)\n if callback then\n callback(nil, tostring(http_error))\n return\n else\n return nil, tostring(http_error)\n end\n end\n\n local result, parse_error = handlers.ResponseHandlers.parse_json(response.body, request_opts)\n if parse_error then\n State:add_error(parse_error)\n if callback then\n callback(nil, tostring(parse_error))\n return\n else\n return nil, tostring(parse_error)\n end\n end\n\n if callback then\n callback(result)\n else\n return result\n end\n end\n\n if callback then\n -- Async mode\n curl.request(vim.tbl_extend(\"force\", request_opts, {\n callback = vim.schedule_wrap(function(response)\n process_response(response)\n end),\n }))\n else\n -- Sync mode\n return process_response(curl.request(request_opts))\n end\nend\n\n--- Refresh cache of config files\n---@param paths string[]|nil\nfunction MCPHub:reload_config(paths)\n local success, err = config_manager.refresh_config(paths)\n if not success then\n self:handle_hub_stopped(\"Failed to reload MCP servers configuration: \" .. (err or \"\"))\n return\n end\n -- toggling a native server in one neovim will trigger insignificant changes in other neovim instances, which should be handled by refreshing the native servers\n self:refresh_native_servers()\nend\n\n-- make sure we update the native servers disabled status when the servers are updated through a sse event\nfunction MCPHub:refresh_native_servers()\n local updated = false\n for _, server in ipairs(State.server_state.native_servers) do\n local server_config = config_manager.get_server_config(server) or {}\n local is_enabled = server_config.disabled ~= true\n local was_running = server.status == \"connected\"\n if is_enabled == was_running then\n goto continue\n end\n updated = true\n if not is_enabled then\n server:stop()\n else\n server:start()\n end\n ::continue::\n end\n if updated then\n self:fire_servers_updated()\n end\nend\n\nfunction MCPHub:fire_servers_updated()\n -- Update global state\n self:_update_global_state()\n\n -- Triggers UI update\n State:notify_subscribers({\n server_state = true,\n }, \"server\")\n\n -- Useful for lualine and other extensions\n utils.fire(\"MCPHubServersUpdated\", {\n active_servers = #self:get_servers(),\n })\n State:emit(\"servers_updated\", {\n hub = self,\n })\nend\n\nfunction MCPHub:update_servers(response, callback)\n callback = callback or function() end\n local servers = response and response.servers or nil\n local workspaces = response and response.workspaces or nil\n local function update_state(_servers, workspaces)\n if _servers then\n State.server_state.servers = _servers or {}\n end\n if workspaces then\n State.server_state.workspaces = workspaces or {}\n end\n self:fire_servers_updated()\n end\n if servers or workspaces then\n update_state(servers, workspaces)\n else\n self:get_health({\n callback = function(response, err)\n if err then\n local health_err = Error(\"SERVER\", Error.Types.SERVER.HEALTH_CHECK, \"Health check failed\", {\n error = err,\n })\n State:add_error(health_err)\n callback(false)\n else\n update_state(response.servers or {}, response.workspaces or {})\n callback(true)\n end\n end,\n })\n end\nend\n\nfunction MCPHub:handle_capability_updates(data)\n local type = data.type\n local server = data.server\n local map = {\n [constants.SubscriptionTypes.TOOL_LIST_CHANGED] = { \"tools\" },\n [constants.SubscriptionTypes.RESOURCE_LIST_CHANGED] = { \"resources\", \"resourceTemplates\" },\n [constants.SubscriptionTypes.PROMPT_LIST_CHANGED] = { \"prompts\" },\n }\n local fields_to_update = map[type]\n if not fields_to_update then\n log.warn(\"Unknown capability update type: \" .. type)\n return\n end\n if not server then\n return\n end\n for _, s in ipairs(State.server_state.servers) do\n if s.name == server then\n local emit_data = {\n server = server,\n hub = self,\n }\n for _, field in ipairs(fields_to_update) do\n s.capabilities[field] = data[field] or {}\n emit_data[field] = s.capabilities[field]\n end\n State:emit(type, emit_data)\n break\n end\n end\n -- Notify subscribers of state change\n State:notify_subscribers({\n server_state = true,\n }, \"server\")\nend\n\n--- Update server configuration in the MCP config file\n---@param server_name string Name of the server to update\n---@param updates table|nil Key-value pairs to update in the server config or nil to remove\n---@param opts? { merge:boolean?, config_source: string? } Optional callback(success: boolean)\n---@return boolean, string|nil Returns success status and error message if any\nfunction MCPHub:update_server_config(server_name, updates, opts)\n return config_manager.update_server_config(server_name, updates, opts)\nend\n\n--- Remove server configuration\n---@param server_name string Server ID to remove\n---@return boolean, string|nil Returns success status and error message if any\nfunction MCPHub:remove_server_config(server_name)\n -- Use update_server_config with nil updates to remove\n return self:update_server_config(server_name, nil)\nend\n\nfunction MCPHub:stop()\n self.is_shutting_down = true\n -- Stop SSE connection\n self:stop_sse()\n self:_clean_up()\n self.is_shutting_down = false\nend\n\nfunction MCPHub:is_ready()\n return self.ready\nend\n\n--- Connect to SSE events endpoint\nfunction MCPHub:connect_sse()\n if self.sse_job then\n return\n end\n local buffer = \"\"\n local base_url = self.server_url or string.format(\"http://localhost:%d\", self.port)\n base_url = base_url:gsub(\"/+$\", \"\")\n\n -- Create SSE connection\n ---@diagnostic disable-next-line: missing-fields\n local sse_job = Job:new({\n command = \"curl\",\n args = {\n \"--no-buffer\",\n \"--tcp-nodelay\",\n \"--retry\",\n \"5\",\n \"--retry-delay\",\n \"1\",\n \"--retry-connrefused\",\n \"--keepalive-time\",\n \"60\",\n base_url .. \"/api/events\",\n },\n on_stdout = vim.schedule_wrap(function(_, data)\n if data ~= nil then\n buffer = buffer .. data .. \"\\n\"\n\n while true do\n local event_end = buffer:find(\"\\n\\n\")\n if not event_end then\n break\n end\n\n local event_str = buffer:sub(1, event_end - 1)\n buffer = buffer:sub(event_end + 2)\n\n local event = event_str:match(\"^event: (.-)\\n\")\n local data_line = event_str:match(\"\\ndata: ([^\\r\\n]+)\")\n\n if event and data_line then\n local success, decoded = utils.json_decode(data_line)\n if success then\n log.trace(string.format(\"SSE event: %s\", event))\n handlers.SSEHandlers.handle_sse_event(event, decoded, self)\n else\n log.warn(string.format(\"Failed to decode SSE data: %s\", data_line))\n end\n else\n log.warn(string.format(\"Malformed SSE event: %s\", event_str))\n end\n end\n end\n end),\n on_stderr = vim.schedule_wrap(function(_, data)\n log.debug(\"SSE STDERR: \" .. tostring(data))\n end),\n on_exit = vim.schedule_wrap(function(_, code)\n log.debug(\"SSE JOB exited with \" .. tostring(code))\n self.sse_job = nil\n self:handle_hub_stopped(\"SSE connection failed with code \" .. tostring(code), code)\n end),\n })\n\n -- Store SSE job for cleanup\n self.sse_job = sse_job\n sse_job:start()\nend\n\n--- Stop SSE connection\nfunction MCPHub:stop_sse()\n if self.sse_job then\n self.sse_job:shutdown(0)\n self.sse_job = nil\n end\nend\n\nfunction MCPHub:refresh(callback)\n callback = callback or function() end\n self:update_servers(nil, callback)\nend\n\nfunction MCPHub:hard_refresh(callback)\n callback = callback or function() end\n if not self:ensure_ready() then\n return\n end\n self:api_request(\"GET\", \"refresh\", {\n callback = function(response, err)\n if err then\n local health_err = Error(\"SERVER\", Error.Types.SERVER.HEALTH_CHECK, \"Hard Refresh failed : \" .. err, {\n error = err,\n })\n State:add_error(health_err)\n callback(false)\n else\n self:update_servers(response)\n callback(true)\n end\n end,\n })\nend\n\nfunction MCPHub:handle_hub_restarting()\n --for non owner client\n self.is_restarting = true\n State:update({\n errors = {\n items = {},\n },\n server_output = {\n entries = {},\n },\n }, \"server\")\nend\n\nfunction MCPHub:handle_hub_stopping()\n if self.is_restarting then\n vim.defer_fn(function()\n self:start()\n end, 1000)\n end\nend\n\n--- Handles already running mcp-hub on same port with different config files\n---@param context table Context containing port and config details\nfunction MCPHub:handle_same_port_different_config(context)\n self:api_request(\"POST\", \"hard-restart\", {\n callback = function(_, err)\n if err then\n local restart_err = Error(\"SERVER\", Error.Types.SERVER.RESTART, \"Hard restart failed\", {\n error = err,\n })\n State:add_error(restart_err)\n vim.notify(\n \"Failed to restart MCP Hub while trying to stop mcp-hub running on port \" .. context.port,\n vim.log.levels.ERROR\n )\n return\n end\n self:_start_server_with_context(context)\n end,\n skip_ready_check = true,\n })\nend\n\n--- Restart the MCP Hub server\n--- @param callback function|nil Optional callback to execute after restart\n--- @param reason string|nil Optional reason for the restart\nfunction MCPHub:restart(callback, reason)\n if not self:ensure_ready() then\n return self:start()\n end\n if self.is_restarting then\n vim.notify(\"MCP Hub is already restarting.\", vim.log.levels.WARN)\n return\n end\n self.is_restarting = true\n self:api_request(\"POST\", \"hard-restart\", {\n callback = function(_, err)\n if err then\n local restart_err = Error(\"SERVER\", Error.Types.SERVER.RESTART, \"Hard restart failed\", {\n error = err,\n })\n State:add_error(restart_err)\n if callback then\n callback(false)\n end\n return\n end\n if callback then\n callback(true)\n end\n end,\n })\nend\n\nfunction MCPHub:ensure_ready()\n if not self:is_ready() then\n log.warn(\"Hub is not ready.\")\n return false\n end\n return true\nend\n\n--- Get servers with their tools filtered based on server config\n--- @param server MCPServer The server object to filter\n---@return table[] Array of connected servers with disabled tools filtered out\nlocal function filter_server_capabilities(server)\n local config = config_manager.get_server_config(server) or {}\n local filtered_server = vim.deepcopy(server)\n\n if filtered_server.capabilities then\n -- Common function to filter capabilities\n local function filter_capabilities(capabilities, disabled_list, id_field)\n return vim.tbl_filter(function(item)\n return not vim.tbl_contains(disabled_list, item[id_field])\n end, capabilities)\n end\n\n -- Filter all capability types with their respective config fields\n local capability_filters = {\n tools = { list = \"disabled_tools\", id = \"name\" },\n resources = { list = \"disabled_resources\", id = \"uri\" },\n resourceTemplates = { list = \"disabled_resourceTemplates\", id = \"uriTemplate\" },\n prompts = { list = \"disabled_prompts\", id = \"name\" },\n }\n\n --- Make the properties field in inputSchema will be encoded as a object not array when empty\n if filtered_server.capabilities.tools then\n for _, tool in ipairs(filtered_server.capabilities.tools) do\n if tool.inputSchema and tool.inputSchema.properties and not next(tool.inputSchema.properties) then\n tool.inputSchema.properties = vim.empty_dict()\n end\n end\n end\n\n for cap_type, filter in pairs(capability_filters) do\n if filtered_server.capabilities[cap_type] then\n filtered_server.capabilities[cap_type] =\n filter_capabilities(filtered_server.capabilities[cap_type], config[filter.list] or {}, filter.id)\n end\n end\n end\n return filtered_server\nend\n\n---resolve any functions in the native servers\n---@param native_server NativeServer\n---@return table\nlocal function resolve_native_server(native_server)\n local server = vim.deepcopy(native_server)\n local possible_func_fields = {\n tools = { \"description\", \"inputSchema\" },\n resources = { \"description\" },\n resourceTemplates = { \"description\" },\n prompts = { \"description\" },\n }\n --first resolve the server desc itself\n server.description = prompt_utils.get_description(server)\n\n for cap_type, fields in pairs(possible_func_fields) do\n for _, capability in ipairs(server.capabilities[cap_type] or {}) do\n --remove handler as it is not in std protocol\n capability.handler = nil\n for _, field in ipairs(fields) do\n if capability[field] then\n if field == \"description\" then --resolves to string\n capability[field] = prompt_utils.get_description(capability)\n elseif field == \"inputSchema\" then --resolves to inputSchema table\n capability[field] = prompt_utils.get_inputSchema(capability)\n end\n end\n end\n end\n end\n return server\nend\n\n---@param include_disabled? boolean\n---@return MCPServer[]\nfunction MCPHub:get_servers(include_disabled)\n include_disabled = include_disabled == true\n if not self:is_ready() then\n return {}\n end\n local filtered_servers = {}\n\n -- Add regular MCP servers\n for _, server in ipairs(State.server_state.servers or {}) do\n if server.status == \"connected\" or include_disabled then\n local filtered_server = filter_server_capabilities(server)\n table.insert(filtered_servers, filtered_server)\n end\n end\n\n -- Add native servers\n for _, server in ipairs(State.server_state.native_servers or {}) do\n if server.status == \"connected\" or include_disabled then\n local filtered_server = filter_server_capabilities(server)\n --INFO: this is for cases where chat plugins expect std MCP definations to remove mcphub specific enhancements\n local resolved_server = resolve_native_server(filtered_server)\n table.insert(filtered_servers, resolved_server)\n end\n end\n\n return filtered_servers\nend\n\n---@return EnhancedMCPPrompt[]\nfunction MCPHub:get_prompts()\n local active_servers = self:get_servers()\n local prompts = {}\n for _, server in ipairs(active_servers) do\n if server.capabilities and server.capabilities.prompts then\n for _, prompt in ipairs(server.capabilities.prompts) do\n table.insert(\n prompts,\n vim.tbl_extend(\"force\", prompt, {\n server_name = server.name,\n })\n )\n end\n end\n end\n return prompts\nend\n\n---@return EnhancedMCPResource[]\nfunction MCPHub:get_resources()\n local active_servers = self:get_servers()\n local resources = {}\n for _, server in ipairs(active_servers) do\n if server.capabilities and server.capabilities.resources then\n for _, resource in ipairs(server.capabilities.resources) do\n table.insert(\n resources,\n vim.tbl_extend(\"force\", resource, {\n server_name = server.name,\n })\n )\n end\n end\n end\n return resources\nend\n\n---@return EnhancedMCPResourceTemplate[]\nfunction MCPHub:get_resource_templates()\n local active_servers = self:get_servers()\n local resource_templates = {}\n for _, server in ipairs(active_servers) do\n if server.capabilities and server.capabilities.resourceTemplates then\n for _, resource_template in ipairs(server.capabilities.resourceTemplates) do\n table.insert(\n resource_templates,\n vim.tbl_extend(\"force\", resource_template, {\n server_name = server.name,\n })\n )\n end\n end\n end\n return resource_templates\nend\n\n---@return EnhancedMCPTool[]\nfunction MCPHub:get_tools()\n local active_servers = self:get_servers()\n local tools = {}\n for _, server in ipairs(active_servers) do\n if server.capabilities and server.capabilities.tools then\n for _, tool in ipairs(server.capabilities.tools) do\n table.insert(\n tools,\n vim.tbl_extend(\"force\", tool, {\n server_name = server.name,\n })\n )\n end\n end\n end\n return tools\nend\n\n--- Convert server to text format\n--- @param server MCPServer\n--- @return string\nfunction MCPHub:convert_server_to_text(server)\n local filtered_server = filter_server_capabilities(server)\n return prompt_utils.server_to_text(filtered_server)\nend\n\n--- Get active servers prompt\n--- @param add_example? boolean Whether to add example to the prompt\n--- @param include_disabled? boolean Whether to include disabled servers\n--- @return string\nfunction MCPHub:get_active_servers_prompt(add_example, include_disabled)\n include_disabled = include_disabled ~= nil and include_disabled or self.auto_toggle_mcp_servers\n add_example = add_example ~= false\n if not self:is_ready() then\n return \"\"\n end\n return prompt_utils.get_active_servers_prompt(self:get_servers(include_disabled), add_example, include_disabled)\nend\n\n--- Get all MCP system prompts\n---@param opts? {use_mcp_tool_example?: string, add_example?: boolean, include_disabled?: boolean, access_mcp_resource_example?: string}\n---@return {active_servers: string|nil, use_mcp_tool: string|nil, access_mcp_resource: string|nil}\nfunction MCPHub:generate_prompts(opts)\n if not self:ensure_ready() then\n return {}\n end\n opts = opts or {}\n return {\n active_servers = self:get_active_servers_prompt(opts.add_example, opts.include_disabled),\n use_mcp_tool = prompt_utils.get_use_mcp_tool_prompt(opts.use_mcp_tool_example),\n access_mcp_resource = prompt_utils.get_access_mcp_resource_prompt(opts.access_mcp_resource_example),\n }\nend\n\n--- Get marketplace catalog with filters\n--- @param opts? { search?: string, category?: string, sort?: string, callback?: function, timeout?: number }\n--- @return table|nil, string|nil If no callback is provided, returns response and error\nfunction MCPHub:get_marketplace_catalog(opts)\n if State.marketplace_state.status == \"loading\" then\n return\n end\n opts = opts or {}\n local query = {}\n\n -- Add filters to query if provided\n if opts.search then\n query.search = opts.search\n end\n if opts.category then\n query.category = opts.category\n end\n if opts.sort then\n query.sort = opts.sort\n end\n\n State:update({\n marketplace_state = {\n status = \"loading\",\n },\n }, \"marketplace\")\n -- Make request with market-specific error handling\n return self:api_request(\"GET\", \"marketplace\", {\n query = query,\n callback = function(response, err)\n if err then\n local market_err = Error(\n \"MARKETPLACE\",\n Error.Types.MARKETPLACE.FETCH_ERROR,\n \"Failed to fetch marketplace catalog\",\n { error = err }\n )\n State:add_error(market_err)\n State:update({\n marketplace_state = {\n status = \"error\",\n },\n }, \"marketplace\")\n return\n end\n\n -- Update marketplace state\n State:update({\n marketplace_state = {\n status = \"loaded\",\n catalog = {\n items = response.servers or {},\n last_updated = response.timestamp,\n },\n },\n }, \"marketplace\")\n end,\n })\nend\n\n--- Update global variables for lualine integration\nfunction MCPHub:_update_global_state()\n vim.g.mcphub_status = State.server_state.state\n vim.g.mcphub_servers_count = #self:get_servers()\nend\n\n--- Setup global variable tracking for tool/resource execution\nfunction MCPHub:_setup_global_state_tracking()\n local group = vim.api.nvim_create_augroup(\"mcphub_global_state\", { clear = true })\n\n -- Track tool/resource/prompt execution\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n pattern = { \"MCPHubToolStart\", \"MCPHubResourceStart\", \"MCPHubPromptStart\" },\n callback = function()\n vim.g.mcphub_executing = true\n end,\n })\n\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n pattern = { \"MCPHubToolEnd\", \"MCPHubResourceEnd\", \"MCPHubPromptEnd\" },\n callback = function()\n vim.g.mcphub_executing = false\n end,\n })\nend\n\nreturn MCPHub\n"], ["/mcphub.nvim/lua/mcphub/utils/prompt.lua", "---@brief [[\n--- Utility functions for generating MCP system prompts.\n--- Parts of the prompts are inspired from RooCode repository:\n--- https://github.com/RooVetGit/Roo-Code\n---@brief ]]\nlocal M = {}\nlocal State = require(\"mcphub.state\")\nlocal config_manager = require(\"mcphub.utils.config_manager\")\nlocal log = require(\"mcphub.utils.log\")\nlocal native = require(\"mcphub.native\")\nlocal utils = require(\"mcphub.utils\")\nlocal validation = require(\"mcphub.utils.validation\")\n\n---@return string\nlocal function get_header()\n return [[\n# MCP SERVERS\n\nThe Model Context Protocol (MCP) enables communication between the system and locally running MCP servers that provide additional tools and resources to extend your capabilities.\n]]\nend\n\n---@param server_name string\n---@param header? string\n---@return string\nfunction M.format_custom_instructions(server_name, header)\n local server_config = config_manager.get_server_config(server_name) or {}\n local custom_instructions = server_config.custom_instructions or {}\n\n if custom_instructions.text and custom_instructions.text ~= \"\" and not custom_instructions.disabled then\n return string.format(\n ((header and header ~= \"\") and header or \"\\n\\n#### Instructions for `%s` server\\n\\n\")\n .. custom_instructions.text,\n server_name\n )\n end\n return \"\"\nend\n\n---@param def MCPServer|NativeServer|MCPTool|MCPResource|MCPResourceTemplate\n---@return string\nfunction M.get_description(def)\n local description = def.description or \"\"\n if type(description) == \"function\" then\n local ok, desc = pcall(description, def)\n if not ok then\n description = \"Failed to get description :\" .. (desc or \"\")\n else\n description = desc or \"\"\n end\n end\n return description\nend\n\n---@param def MCPTool\n---@return table\nfunction M.get_inputSchema(def)\n local base = {\n type = \"object\",\n properties = {},\n }\n local inputSchema = def.inputSchema\n if not inputSchema or (type(inputSchema) == \"table\" and not next(inputSchema)) then\n inputSchema = base\n end\n local parsedSchema = inputSchema\n if type(parsedSchema) == \"function\" then\n local ok, schema = pcall(parsedSchema, def)\n if not ok then\n local err = \"Error in inputSchema function: \" .. tostring(schema)\n log.error(err)\n parsedSchema = base\n else\n parsedSchema = schema or base\n end\n end\n local res = validation.validate_inputSchema(parsedSchema, def.name)\n if not res.ok then\n local err = \"Error in inputSchema function: \" .. tostring(res.error)\n log.error(err)\n return base\n end\n return parsedSchema\nend\n\n---@param tools MCPTool[]\n---@return string\nlocal function format_tools(tools)\n if not tools or #tools == 0 then\n return \"\"\n end\n\n local result = \"\\n\\n#### Available Tools\"\n for _, tool in ipairs(tools) do\n result = result .. string.format(\"\\n\\n- %s: %s\", tool.name, M.get_description(tool):gsub(\"\\n\", \"\\n \"))\n local inputSchema = M.get_inputSchema(tool)\n result = result\n .. \"\\n\\n Input Schema:\\n\\n ```json\\n \"\n .. utils.pretty_json(vim.json.encode(inputSchema)):gsub(\"\\n\", \"\\n \")\n .. \"\\n ```\"\n end\n return result\nend\n\n---@diagnostic disable-next-line: unused-function\nlocal function remove_functions(obj)\n if type(obj) ~= \"table\" then\n return obj\n end\n local new_obj = {}\n for k, v in pairs(obj) do\n if type(v) ~= \"function\" then\n new_obj[k] = remove_functions(v)\n end\n end\n return new_obj\nend\n\n---@param resources MCPResource[]\n---@param templates MCPResourceTemplate[]\n---@return string\nlocal function format_resources(resources, templates)\n local result = \"\"\n if resources and #resources > 0 then\n result = result .. \"\\n\\n#### Available Resources\"\n for _, resource in ipairs(resources) do\n result = result\n .. string.format(\n \"\\n\\n- %s%s\",\n resource.uri,\n resource.mimeType and \" (\" .. resource.mimeType .. \")\" or \"\"\n )\n local desc = M.get_description(resource):gsub(\"\\n\", \"\\n \")\n result = result .. \"\\n \" .. (resource.name or \"\") .. (desc == \"\" and \"\" or \"\\n \" .. desc)\n -- result = result .. \"\\n\\n\" .. vim.inspect(remove_functions(resource))\n end\n end\n if templates and #templates > 0 then\n result = result .. \"\\n\\n#### Available Resource Templates\"\n for _, template in ipairs(templates) do\n result = result .. string.format(\"\\n\\n- %s\", template.uriTemplate)\n local desc = M.get_description(template)\n result = result .. \"\\n \" .. (template.name or \"\") .. (desc == \"\" and \"\" or \"\\n \" .. desc)\n -- result = result .. \"\\n\\n\" .. vim.inspect(remove_functions(template))\n end\n end\n return result\nend\n\n--- Get the use_mcp_tool section of the prompt\n---@param example? string Optional custom XML example block\n---@return string The formatted prompt section\nfunction M.get_use_mcp_tool_prompt(example)\n local default_example = [[\nweather-server\nget_forecast\n\n{\n \"city\": \"San Francisco\",\n \"days\": 5\n}\n\n]]\n\n return string.format(\n [[\n### use_mcp_tool\n\nDescription: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.\nParameters:\n- server_name: (required) The name of the MCP server providing the tool\n- tool_name: (required) The name of the tool to execute\n- arguments: (required) A JSON object containing the tool's input parameters, following the tool's input schema\n\nExample: Requesting to use an MCP tool\n\n%s]],\n example or default_example\n )\nend\n\n--- Get the access_mcp_resource section of the prompt\n---@param example? string Optional custom XML example block\n---@return string The formatted prompt section\nfunction M.get_access_mcp_resource_prompt(example)\n local default_example = [[\nweather-server\nweather://san-francisco/current\n]]\n\n return string.format(\n [[\n### access_mcp_resource\n\nDescription: Request to access a resource provided by a connected MCP server. Resources represent data sources that can be used as context, such as files, API responses, or system information.\nParameters:\n- server_name: (required) The name of the MCP server providing the resource\n- uri: (required) The URI identifying the specific resource to access\n\nExample: Requesting to access an MCP resource\n\n%s]],\n example or default_example\n )\nend\n\n---@param server MCPServer\n---@return string\nfunction M.server_to_text(server)\n local text = \"\"\n -- Add server section\n text = text .. string.format(\"### %s\", server.name)\n local is_disabled = server.status == \"disabled\"\n if is_disabled then\n text = text .. \" (Disabled)\"\n end\n local desc = M.get_description(server)\n -- Add description\n text = text .. (desc == \"\" and \"\" or \"\\n\\n\" .. desc)\n if is_disabled then\n return text\n end\n if\n server.capabilities\n and (\n (server.capabilities.tools and #server.capabilities.tools > 0)\n or (server.capabilities.resources and #server.capabilities.resources > 0)\n or (server.capabilities.resourceTemplates and #server.capabilities.resourceTemplates > 0)\n )\n then\n -- Add custom instructions if any\n text = text .. M.format_custom_instructions(server.name)\n\n -- Add capabilities\n text = text .. format_tools(server.capabilities.tools)\n text = text .. format_resources(server.capabilities.resources, server.capabilities.resourceTemplates)\n else\n text = text .. \"\\n(No tools or resources available)\"\n end\n return text\nend\n\n---@param servers MCPServer[]\n---@param add_example boolean\n---@param enable_toggling_mcp_servers boolean\n---@return string\nfunction M.get_active_servers_prompt(servers, add_example, enable_toggling_mcp_servers)\n add_example = add_example ~= false\n enable_toggling_mcp_servers = enable_toggling_mcp_servers ~= false\n local prompt = get_header()\n\n ---@type MCPServer[]\n local connected_servers = vim.tbl_filter(function(s)\n return s.status == \"connected\"\n end, servers)\n\n ---@type MCPServer[]\n local disabled_servers = vim.tbl_filter(function(s)\n return s.status == \"disabled\"\n end, servers)\n\n prompt = prompt .. \"\\n## Connected MCP Servers\"\n\n prompt = prompt\n .. \"\\n\\nWhen a server is connected, you can use the server's tools via the `use_mcp_tool` tool, \"\n .. \"and access the server's resources via the `access_mcp_resource` tool.\\nNote: Server names are case sensitive and you should always use the exact full name like `Firecrawl MCP` or `src/user/main/time-mcp` etc\\n\\n\"\n if #connected_servers == 0 then\n prompt = prompt .. \"(No connected MCP servers)\\n\\n\"\n else\n for _, server in ipairs(connected_servers) do\n prompt = prompt .. M.server_to_text(server) .. \"\\n\\n\"\n end\n end\n\n -- instead of removing the whole disabled section, if we dont want auto toggling we set (NO disabled servers) to avoid llm hallucinating server names\n prompt = prompt .. \"## Disabled MCP Servers\\n\\n\"\n prompt = prompt\n .. \"When a server is disabled, it will not be able to provide tools or resources. You can start one of the following disabled servers by using the `toggle_mcp_server` tool on `mcphub` MCP Server if it is connected using `use_mcp_tool`\\n\\n\"\n if not enable_toggling_mcp_servers or #disabled_servers == 0 then\n prompt = prompt .. \"(No disabled MCP servers)\\n\\n\"\n else\n for _, server in ipairs(disabled_servers) do\n prompt = prompt .. M.server_to_text(server) .. \"\\n\\n\"\n end\n end\n local toggle_example = [[\n\n### Toggling a MCP Server\n\nWhen you need to start a disabled MCP Server or vice-versa, use the `toggle_mcp_server` tool on `mcphub` MCP Server using `use_mcp_tool`:\n\nCRITICAL: You need to use the `use_mcp_tool` tool to call the `toggle_mcp_server` tool on `mcphub` MCP Server when `mcphub` server is \"Connected\" else ask the user to enable `mcphub` server.\n\nPseudocode:\n\nuse_mcp_tool\n server_name: \"mcphub\"\n tool_name: \"toggle_mcp_server\"\n tool_input:\n server_name: string (One of the available server names to start or stop)\n action: string (one of `start` or `stop`)\n]]\n\n local example = [[\n## Examples\n\n### `use_mcp_tool`\n\nWhen you need to call a tool on an MCP Server, use the `use_mcp_tool` tool:\n\nPseudocode:\n\nuse_mcp_tool\n server_name: string (One of the available server names)\n tool_name: string (name of the tool in the server to call)\n tool_input: object (Arguments for the tool call)\n\n### `access_mcp_resource`\n\nWhen you need to access a resource from a MCP Server, use the `access_mcp_resource` tool:\n\nPseudocode:\n\naccess_mcp_resource\n server_name: string (One of the available server names)\n uri: string (uri for the resource)\n]]\n\n if enable_toggling_mcp_servers then\n example = example .. toggle_example\n end\n\n return prompt .. (add_example and example or \"\")\nend\n\n---@param response {result: {messages: {role:string, content: table}[]}}|nil\n---@return {messages : {role:\"user\"| \"assistant\"|\"system\", output: MCPResponseOutput}[]}\nfunction M.parse_prompt_response(response)\n if response == nil then\n return { messages = {} }\n end\n local result = response.result or {}\n local messages = {}\n for _, v in ipairs(result.messages or {}) do\n local output = { text = \"\", images = {}, blobs = {}, audios = {} }\n local content = v.content\n if content.type == \"text\" then\n output.text = content.text\n elseif content.type == \"image\" then\n table.insert(output.images, {\n data = content.data,\n mimeType = content.mimeType or \"application/octet-stream\",\n })\n elseif content.type == \"audio\" then\n table.insert(output.audios, {\n data = content.data,\n mimeType = content.mimeType or \"application/octet-stream\",\n })\n elseif content.type == \"blob\" then\n table.insert(output.blobs, {\n data = content.data,\n mimeType = content.mimeType or \"application/octet-stream\",\n })\n elseif content.type == \"resource\" then\n -- Handle resource content by treating it as a resource response\n local resource_result = M.parse_resource_response({\n result = {\n contents = { content.resource },\n },\n })\n output.text = resource_result.text\n vim.list_extend(output.images, resource_result.images)\n vim.list_extend(output.blobs, resource_result.blobs)\n vim.list_extend(output.audios, resource_result.audios)\n end\n table.insert(messages, {\n role = v.role,\n output = output,\n })\n end\n return {\n messages = messages,\n }\nend\n\n---@param response? table\n---@return MCPResponseOutput\nfunction M.parse_tool_response(response)\n if response == nil then\n return { error = nil, text = \"\", images = {}, blobs = {}, audios = {} }\n end\n\n local result = response.result or {}\n local output = { text = \"\", images = {}, blobs = {}, audios = {}, error = nil }\n local images = {}\n local blobs = {}\n local texts = {}\n local audios = {}\n\n -- parse tool response\n for _, v in ipairs(result.content or {}) do\n local type = v.type\n if type == \"text\" then\n table.insert(texts, v.text)\n elseif type == \"image\" then\n table.insert(images, {\n data = v.data,\n mimeType = v.mimeType or \"application/octet-stream\",\n })\n elseif type == \"blob\" then\n table.insert(output.blobs, {\n data = v.data,\n mimeType = v.mimeType or \"application/octet-stream\",\n })\n elseif type == \"audio\" then\n table.insert(audios, {\n data = v.data,\n mimeType = v.mimeType or \"application/octet-stream\",\n })\n elseif type == \"resource\" and v.resource then\n -- Handle resource content by treating it as a resource response\n local resource_result = M.parse_resource_response({\n result = {\n contents = { v.resource },\n },\n })\n -- Merge the results\n table.insert(texts, resource_result.text)\n vim.list_extend(images, resource_result.images)\n vim.list_extend(blobs, resource_result.blobs)\n vim.list_extend(audios, resource_result.audios)\n end\n end\n\n -- Combine all text with newlines\n output.text = table.concat(texts, \"\\n\")\n if result.isError then\n output.error = output.text\n output.text = \"The tool run failed with error.\\n\" .. output.text\n end\n output.images = images\n output.blobs = blobs\n output.audios = audios\n\n return output\nend\n\n---@param response? table\n---@return MCPResponseOutput\nfunction M.parse_resource_response(response)\n if response == nil then\n return { text = \"\", images = {}, blobs = {} }\n end\n\n local result = response.result or {}\n local output = { text = \"\", images = {}, blobs = {} }\n local images = {}\n local blobs = {}\n local texts = {}\n local audios = {}\n\n for _, content in ipairs(result.contents or {}) do\n if content.uri then\n if content.blob then\n -- Handle blob data based on mimetype\n if content.mimeType and content.mimeType:match(\"^image/\") then\n -- It's an image\n table.insert(images, {\n data = content.blob,\n mimeType = content.mimeType,\n })\n elseif content.mimeType and content.mimeType:match(\"^audio/\") then\n -- It's an audio blob\n table.insert(audios, {\n data = content.blob,\n mimeType = content.mimeType,\n })\n else\n -- It's a binary blob\n table.insert(blobs, {\n data = content.blob,\n mimeType = content.mimeType or \"application/octet-stream\",\n uri = content.uri,\n })\n -- Add blob info to text\n table.insert(\n texts,\n string.format(\n \"Resource %s: \",\n content.uri,\n content.mimeType or \"application/octet-stream\"\n )\n )\n end\n elseif content.text then\n -- Text content\n table.insert(texts, string.format(\"Resource %s:\\n%s\", content.uri, content.text))\n end\n end\n end\n\n output.text = table.concat(texts, \"\\n\\n\")\n output.images = images\n output.blobs = blobs\n output.audios = audios\n return output\nend\n\n--- Get the troubleshooting guide for MCPHub\n--- @return string|nil The troubleshooting guide content or nil if not found\nfunction M.get_troubleshooting_guide()\n local source_path = debug.getinfo(1, \"S\").source:sub(2) -- Remove '@' prefix\n local base_path = vim.fn.fnamemodify(source_path, \":h:h:h:h\") -- Go up three levels from prompt.lua\n local guide_path = base_path .. \"/doc/other/troubleshooting.md\"\n local f = io.open(guide_path)\n if not f then\n return nil\n end\n\n local content = f:read(\"*all\")\n f:close()\n\n return content\nend\n\n--- Get the native server creation prompt from the guide file\n---@return string|nil The native server guide content or nil if not found\nfunction M.get_native_server_prompt()\n -- Use source file path to find the guide\n local source_path = debug.getinfo(1, \"S\").source:sub(2) -- Remove '@' prefix\n local base_path = vim.fn.fnamemodify(source_path, \":h:h\") -- Go up three levels from prompt.lua\n local guide_path = base_path .. \"/native/NATIVE_SERVER_LLM.md\"\n local f = io.open(guide_path)\n if not f then\n return nil\n end\n\n local content = f:read(\"*all\")\n f:close()\n\n return content\nend\n\n--- Get mcphub.nvim plugin documentation intended for llms\n---@return string|nil The plugin docs content or nil if not found\nfunction M.get_plugin_docs()\n local source_path = debug.getinfo(1, \"S\").source:sub(2)\n local base_path = vim.fn.fnamemodify(source_path, \":h:h:h:h\")\n local guide_path = base_path .. \"/doc/mcphub.txt\"\n local f = io.open(guide_path)\n if not f then\n return nil\n end\n local content = f:read(\"*all\")\n f:close()\n return content\nend\n\n--- Get the changelog for the mcphub.nvim plugin\n--- @return string|nil The changelog content or nil if not found\nfunction M.get_plugin_changelog()\n local source_path = debug.getinfo(1, \"S\").source:sub(2)\n local base_path = vim.fn.fnamemodify(source_path, \":h:h:h:h\")\n local guide_path = base_path .. \"/CHANGELOG.md\"\n local f = io.open(guide_path)\n if not f then\n return nil\n end\n local content = f:read(\"*all\")\n f:close()\n return content\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/utils/validation.lua", "---@brief [[\n--- Validation utilities for MCPHub\n--- Handles configuration and input validation\n---@brief ]]\nlocal Error = require(\"mcphub.utils.errors\")\nlocal version = require(\"mcphub.utils.version\")\n\nlocal M = {}\n\n---@class MCPServersConfigFile\n---@field mcpServers table\n---@field nativeMCPServers table\n\n---@class ValidationResult\n---@field ok boolean\n---@field error? MCPError\n\n--- Validate setup options\n---@param opts MCPHub.Config\n---@return ValidationResult\nfunction M.validate_setup_opts(opts)\n if not opts.port then\n return {\n ok = false,\n error = Error(\"SETUP\", Error.Types.SETUP.INVALID_PORT, \"Port is required for MCPHub setup\"),\n }\n end\n\n if not opts.config or type(opts.config) ~= \"string\" then\n return {\n ok = false,\n error = Error(\"SETUP\", Error.Types.SETUP.INVALID_CONFIG, \"Config file path is required\"),\n }\n end\n\n -- Validate cmd and cmdArgs if provided\n if opts.cmd and type(opts.cmd) ~= \"string\" then\n return {\n ok = false,\n error = Error(\"SETUP\", Error.Types.SETUP.INVALID_CMD, \"cmd must be a string\"),\n }\n end\n\n if opts.cmdArgs and type(opts.cmdArgs) ~= \"table\" then\n return {\n ok = false,\n error = Error(\"SETUP\", Error.Types.SETUP.INVALID_CMD_ARGS, \"cmdArgs must be an array\"),\n }\n end\n -- Validate native servers if present\n if opts.native_servers then\n if type(opts.native_servers) ~= \"table\" then\n return {\n ok = false,\n error = Error(\"SETUP\", Error.Types.SETUP.INVALID_CONFIG, \"native_servers must be a table\"),\n }\n end\n end\n return { ok = true }\nend\n\n--- Validate server configuration\n---@param name string Server name to validate\n---@param config MCPServerConfig Server configuration\n---@return ValidationResult\nfunction M.validate_server_config(name, config)\n if type(config) ~= \"table\" then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' config must be a table\", name)\n ),\n }\n end\n\n local has_stdio = config.command ~= nil\n local has_sse = config.url ~= nil\n\n -- Check for mixed fields\n if has_stdio and has_sse then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' cannot mix stdio and sse fields\", name)\n ),\n }\n end\n\n -- Validate stdio config\n if has_stdio then\n if type(config.command) ~= \"string\" or config.command == \"\" then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' has invalid or missing command\", name)\n ),\n }\n end\n\n if config.args and not vim.islist(config.args) then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' args must be an array\", name)\n ),\n }\n end\n\n if config.env and type(config.env) ~= \"table\" then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' has invalid environment config\", name)\n ),\n }\n end\n\n if config.cwd and (type(config.cwd) ~= \"string\" or config.cwd == \"\") then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' has invalid cwd: must be a non-empty string\", name)\n ),\n }\n end\n elseif has_sse then\n -- Validate SSE config\n if type(config.url) ~= \"string\" or config.url == \"\" then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' has invalid or missing url\", name)\n ),\n }\n end\n\n -- Try parsing URL\n local ok, err = pcall(function()\n vim.uri_from_fname(config.url)\n end)\n if not ok then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' has invalid url format: %s\", name, err)\n ),\n }\n end\n\n if config.headers and type(config.headers) ~= \"table\" then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' has invalid headers config\", name)\n ),\n }\n end\n else\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Server '%s' must include either command (for stdio) or url (for sse)\", name)\n ),\n }\n end\n\n return { ok = true }\nend\n\n--- Validate MCP Hub version\n---@param ver_str string Version string to validate\n---@return ValidationResult\nfunction M.validate_version(ver_str)\n local major, minor, patch = ver_str:match(\"(%d+)%.(%d+)%.(%d+)\")\n if not major then\n return {\n ok = false,\n error = Error(\"SETUP\", Error.Types.SETUP.VERSION_MISMATCH, \"Invalid version format\", {\n version = ver_str,\n }),\n }\n end\n\n local current = {\n major = tonumber(major),\n minor = tonumber(minor),\n patch = tonumber(patch),\n }\n\n local required = version.REQUIRED_NODE_VERSION\n if current.major ~= required.major or current.minor < required.minor then\n return {\n ok = false,\n error = Error(\n \"SETUP\",\n Error.Types.SETUP.VERSION_MISMATCH,\n string.format(\"Incompatible mcp-hub version. Found %s, required %s\", ver_str, required.string),\n {\n found = ver_str,\n required = required.string,\n install_cmd = string.format(\"npm install -g mcp-hub@%s\", required.string),\n }\n ),\n }\n end\n\n return {\n ok = true,\n }\nend\n\n--- Validate a property according to requirements\n---@param value any The value to validate\n---@param prop_type string Type of property (string|function|table)\n---@param name string Name of property for error messages\n---@param error_type string Error type from Error.Types.NATIVE\n---@param object_id? string Optional identifier for error messages\n---@param extra_check? function Optional additional validation function\n---@return ValidationResult\nlocal function validate_property(value, prop_type, name, error_type, object_id, extra_check)\n if not value or type(value) ~= prop_type then\n return {\n ok = false,\n error = Error(\"VALIDATION\", error_type, string.format(\"%s must be a %s\", name, prop_type)),\n }\n end\n\n if prop_type == \"string\" and value == \"\" then\n return {\n ok = false,\n error = Error(\"VALIDATION\", error_type, string.format(\"%s cannot be empty\", name)),\n }\n end\n\n if extra_check then\n local ok, err = extra_check(value)\n if not ok then\n return {\n ok = false,\n error = Error(\n \"VALIDATION\",\n error_type,\n string.format(\"%s: %s\", object_id and string.format(\"%s in %s\", err, object_id) or err, name)\n ),\n }\n end\n end\n\n return { ok = true }\nend\n\n---inputSchema will be evaluated if it is a function and is obj is validated\n---@param inputSchema table\n---@param tool_name string\nfunction M.validate_inputSchema(inputSchema, tool_name)\n if not inputSchema then\n return { ok = true }\n end\n -- Check inputSchema structure\n local function validate_schema(schema)\n if schema.type ~= \"object\" then\n return false, \"type must be 'object'\"\n end\n if schema.properties and type(schema.properties) ~= \"table\" then\n return false, \"must have a properties table\"\n end\n return true\n end\n\n return validate_property(\n inputSchema,\n \"table\",\n \"Input schema\",\n Error.Types.NATIVE.INVALID_SCHEMA,\n tool_name or \"\",\n validate_schema\n )\nend\n\n--- Validate a tool definition\n---@param tool MCPTool Tool definition to validate\n---@return ValidationResult\nfunction M.validate_tool(tool)\n -- Validate name\n local name_result = validate_property(tool.name, \"string\", \"Tool name\", Error.Types.NATIVE.INVALID_NAME)\n if not name_result.ok then\n return name_result\n end\n\n -- Validate handler\n local handler_result =\n validate_property(tool.handler, \"function\", \"Handler\", Error.Types.NATIVE.INVALID_HANDLER, tool.name)\n if not handler_result.ok then\n return handler_result\n end\n return { ok = true }\nend\n\n--- Validate a resource definition\n---@param resource MCPResource Resource definition to validate\n---@return ValidationResult\nfunction M.validate_resource(resource)\n local name_result = validate_property(resource.name, \"string\", \"Resource Name\", Error.Types.NATIVE.INVALID_NAME)\n if not name_result.ok then\n return name_result\n end\n -- Validate URI\n local uri_result = validate_property(resource.uri, \"string\", \"Resource URI\", Error.Types.NATIVE.INVALID_URI)\n if not uri_result.ok then\n return uri_result\n end\n\n -- Validate handler\n local handler_result =\n validate_property(resource.handler, \"function\", \"Handler\", Error.Types.NATIVE.INVALID_HANDLER, resource.uri)\n if not handler_result.ok then\n return handler_result\n end\n\n return { ok = true }\nend\n\n--- Validate a resource template definition\n---@param template MCPResourceTemplate Resource template definition to validate\n---@return ValidationResult\nfunction M.validate_resource_template(template)\n -- Validate URI template\n local function validate_uri_template(uri)\n if not uri:match(\"{[^}]+}\") then\n return false, \"must contain at least one parameter in {param} format\"\n end\n return true\n end\n\n local name_result = validate_property(template.name, \"string\", \"Resource Name\", Error.Types.NATIVE.INVALID_NAME)\n if not name_result.ok then\n return name_result\n end\n local uri_result = validate_property(\n template.uriTemplate,\n \"string\",\n \"URI template\",\n Error.Types.NATIVE.INVALID_URI,\n nil,\n validate_uri_template\n )\n if not uri_result.ok then\n return uri_result\n end\n\n -- Validate handler\n local handler_result = validate_property(\n template.handler,\n \"function\",\n \"Handler\",\n Error.Types.NATIVE.INVALID_HANDLER,\n template.uriTemplate\n )\n if not handler_result.ok then\n return handler_result\n end\n\n return { ok = true }\nend\n\n-- Add prompts validation in native server validation\n---@param def NativeServerDef Native server definition to validate\n---@return {ok: boolean, error: MCPError}\nfunction M.validate_native_server(def)\n local server_name = def.name\n if not def.name then\n return {\n ok = false,\n error = Error(\"SETUP\", Error.Types.SETUP.INVALID_CONFIG, \"Native server must contain a name\"),\n }\n end\n if not def.capabilities then\n return {\n ok = false,\n error = Error(\n \"SETUP\",\n Error.Types.SETUP.INVALID_CONFIG,\n string.format(\"Native server '%s' must contain capabilities\", server_name)\n ),\n }\n end\n -- Validate tools if present\n if def.capabilities.tools then\n for _, tool in ipairs(def.capabilities.tools) do\n local ok, err = M.validate_tool(tool)\n if not ok then\n return {\n ok = false,\n error = err,\n }\n end\n end\n end\n\n -- Validate resources if present\n if def.capabilities.resources then\n for _, resource in ipairs(def.capabilities.resources) do\n local ok, err = M.validate_resource(resource)\n if not ok then\n return {\n ok = false,\n error = err,\n }\n end\n end\n end\n\n -- Validate resource templates if present\n if def.capabilities.resourceTemplates then\n for _, template in ipairs(def.capabilities.resourceTemplates) do\n local ok, err = M.validate_resource_template(template)\n if not ok then\n return {\n ok = false,\n error = err,\n }\n end\n end\n end\n\n -- Validate prompts if present\n if def.capabilities.prompts then\n for _, prompt in ipairs(def.capabilities.prompts) do\n local ok, err = M.validate_prompt(prompt)\n if not ok then\n return {\n ok = false,\n error = err,\n }\n end\n end\n end\n return { ok = true }\nend\n\n--- Validate a prompt definition\n---@param prompt MCPPrompt Prompt definition to validate\n---@return ValidationResult\nfunction M.validate_prompt(prompt)\n -- Validate name\n local name_result = validate_property(prompt.name, \"string\", \"Prompt name\", Error.Types.NATIVE.INVALID_NAME)\n if not name_result.ok then\n return name_result\n end\n\n -- Validate handler\n local handler_result =\n validate_property(prompt.handler, \"function\", \"Handler\", Error.Types.NATIVE.INVALID_HANDLER, prompt.name)\n if not handler_result.ok then\n return handler_result\n end\n\n return { ok = true }\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/init.lua", "local Error = require(\"mcphub.utils.errors\")\nlocal NativeServer = require(\"mcphub.native.utils.server\")\nlocal State = require(\"mcphub.state\")\nlocal validate = require(\"mcphub.utils.validation\")\n\n---@class MCPHub.Native\nlocal Native = {}\n\n--- Check if a server name belongs to a native server\n---@param server_name string Name of the server to check\n---@return NativeServer|nil server instance if found\nfunction Native.is_native_server(server_name)\n for _, server in ipairs(State.server_state.native_servers) do\n if server.name == server_name then\n return server\n end\n end\n return nil\nend\n\n---@param err MCPError Error to handle\nlocal function handle_error(err)\n State:add_error(err)\nend\n\n---@class NativeServerDef\n---@field name? string Name of the server\n---@field displayName? string Display name of the server\n---@field capabilities? MCPCapabilities\n\n---@param def NativeServerDef Server definition with name capabilities etc\n---@return NativeServer|nil server Server instance or nil on error\nfunction Native.register(def)\n if type(def) ~= \"table\" then\n handle_error(Error(\"VALIDATION\", Error.Types.NATIVE.INVALID_SCHEMA, \"Server definition is not a table\"))\n return nil\n end\n local existing = Native.is_native_server(def.name)\n if existing then\n State:add_error(\n Error(\"VALIDATION\", Error.Types.NATIVE.INVALID_SCHEMA, string.format(\"%s already exists\", def.name))\n )\n return existing\n end\n local result = validate.validate_native_server(def)\n if not result.ok then\n handle_error(result.error)\n return nil\n end\n -- Create server instance\n local server = NativeServer:new(def)\n if not server then\n handle_error(Error(\"RUNTIME\", Error.Types.NATIVE.INVALID_SCHEMA, \"Failed to create native server\"))\n return nil\n end\n\n -- Update server state with server instance state\n table.insert(State.server_state.native_servers, server)\n return server\nend\n\n--- Add a new native server\n---@param server_name string Name of the server\n---@param def? NativeServerDef Optional server definition overrides\n---@return NativeServer|nil server Server instance or nil on error\nfunction Native.add_server(server_name, def)\n -- Check if server already exists\n local existing = Native.is_native_server(server_name)\n if existing then\n State:add_error(\n Error(\"VALIDATION\", Error.Types.NATIVE.INVALID_SCHEMA, string.format(\"%s already exists\", server_name))\n )\n return existing\n end\n\n -- Create default server definition\n local server_def = vim.tbl_deep_extend(\"force\", {\n name = server_name,\n displayName = server_name,\n capabilities = {\n tools = {},\n resources = {},\n resourceTemplates = {},\n prompts = {},\n },\n }, def or {})\n --make sure the server name is same as the key\n server_def.name = server_name\n\n -- Register the server\n return Native.register(server_def)\nend\n\n--- Add a tool to a server, creating the server if it doesn't exist\n---@param server_name string Name of the server\n---@param tool_def MCPTool Tool definition including name, description, and handler\n---@return NativeServer|nil server The server instance or nil on error\nfunction Native.add_tool(server_name, tool_def)\n local result = validate.validate_tool(tool_def)\n if not result.ok then\n handle_error(result.error)\n return nil\n end\n\n local server = Native.is_native_server(server_name)\n if server then\n table.insert(server.capabilities.tools, tool_def)\n return server\n else\n return Native.add_server(server_name, {\n name = server_name,\n capabilities = { tools = { tool_def } },\n })\n end\nend\n\n--- Add a resource to a server, creating the server if it doesn't exist\n---@param server_name string Name of the server\n---@param resource_def MCPResource Resource definition including URI and handler\n---@return NativeServer|nil server The server instance or nil on error\nfunction Native.add_resource(server_name, resource_def)\n local result = validate.validate_resource(resource_def)\n if not result.ok then\n handle_error(result.error)\n return nil\n end\n\n local server = Native.is_native_server(server_name)\n if server then\n table.insert(server.capabilities.resources, resource_def)\n return server\n else\n return Native.add_server(server_name, {\n name = server_name,\n capabilities = { resources = { resource_def } },\n })\n end\nend\n\n--- Add a resource template to a server, creating the server if it doesn't exist\n---@param server_name string Name of the server\n---@param template_def MCPResourceTemplate Template definition including URI template and handler\n---@return NativeServer|nil server The server instance or nil on error\nfunction Native.add_resource_template(server_name, template_def)\n local result = validate.validate_resource_template(template_def)\n if not result.ok then\n handle_error(result.error)\n return nil\n end\n\n local server = Native.is_native_server(server_name)\n if server then\n table.insert(server.capabilities.resourceTemplates, template_def)\n return server\n else\n return Native.add_server(server_name, {\n name = server_name,\n capabilities = { resourceTemplates = { template_def } },\n })\n end\nend\n--- Add a prompt to a server, creating the server if it doesn't exist\n---@param server_name string Name of the server\n---@param prompt_def MCPPrompt Prompt definition including name and handler\n---@return NativeServer|nil server The server instance or nil on error\nfunction Native.add_prompt(server_name, prompt_def)\n local result = validate.validate_prompt(prompt_def)\n if not result.ok then\n handle_error(result.error)\n return nil\n end\n\n local server = Native.is_native_server(server_name)\n if server then\n table.insert(server.capabilities.prompts, prompt_def)\n return server\n else\n return Native.add_server(server_name, {\n name = server_name,\n capabilities = { prompts = { prompt_def } },\n })\n end\nend\n\nNative.done_setup = false\nfunction Native.setup(user_native_servers)\n if Native.done_setup then\n return\n end\n require(\"mcphub.native.neovim\")\n require(\"mcphub.native.mcphub\")\n -- Initialize native servers if any provided in setup config\n if user_native_servers and type(user_native_servers) == \"table\" then\n for name, def in pairs(user_native_servers) do\n local server = Native.register(def)\n if server then\n -- make sure the server name is set to key\n server.name = name\n end\n end\n end\n Native.done_setup = true\nend\n\nreturn Native\n"], ["/mcphub.nvim/lua/mcphub/ui/views/main.lua", "---@brief [[\n--- Main dashboard view for MCPHub\n--- Shows server status and connected servers\n---@brief ]]\nlocal Capabilities = require(\"mcphub.ui.capabilities\")\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal View = require(\"mcphub.ui.views.base\")\nlocal config_manager = require(\"mcphub.utils.config_manager\")\nlocal constants = require(\"mcphub.utils.constants\")\nlocal native = require(\"mcphub.native\")\nlocal renderer = require(\"mcphub.utils.renderer\")\nlocal ui_utils = require(\"mcphub.utils.ui\")\nlocal utils = require(\"mcphub.utils\")\n\n---@class MainView: View\n---@field super View\n---@field expanded_server string|nil Currently expanded server name\n---@field expanded_workspace string|nil Currently expanded workspace port\n---@field active_capability CapabilityHandler|nil Currently active capability\n---@field cursor_positions {browse_mode: number[]|nil, capability_line: number[]|nil} Cursor positions for different modes\nlocal MainView = setmetatable({}, {\n __index = View,\n})\nMainView.__index = MainView\n\nfunction MainView:new(ui)\n local instance = View:new(ui, \"main\") -- Create base view with name\n instance = setmetatable(instance, MainView)\n -- Initialize state\n instance.expanded_server = nil\n instance.expanded_workspace = nil\n instance.active_capability = nil\n instance.cursor_positions = {\n browse_mode = nil, -- Will store [line, col]\n capability_line = nil, -- Will store [line, col]\n }\n\n return instance\nend\n\nfunction MainView:show_prompts_view()\n -- Store current cursor position before switching\n self.cursor_positions.browse_mode = vim.api.nvim_win_get_cursor(0)\n\n -- Switch to prompts capability\n self.active_capability = Capabilities.create_handler(\"preview\", \"MCP Servers\", { name = \"System Prompts\" }, self)\n self:setup_active_mode()\n self:draw()\n -- Move to capability's preferred position\n local cap_pos = self.active_capability:get_cursor_position()\n if cap_pos then\n vim.api.nvim_win_set_cursor(0, cap_pos)\n end\nend\n\nfunction MainView:handle_collapse()\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = cursor[1]\n\n -- Get line info\n local type, context = self:get_line_info(line)\n\n -- If we're on a server line, handle directly\n if type == \"server\" and context then\n if context.status == \"connected\" and self.expanded_server == context.name then\n local server_line = line\n self.expanded_server = nil -- collapse\n self:draw()\n vim.api.nvim_win_set_cursor(0, { server_line, 3 })\n return\n end\n end\n\n -- If we're on a workspace line, handle directly\n if type == \"workspace\" and context then\n if self.expanded_workspace == context.port then\n local workspace_line = line\n self.expanded_workspace = nil -- collapse\n self:draw()\n vim.api.nvim_win_set_cursor(0, { workspace_line, 3 })\n return\n end\n end\n\n -- If we have an expanded server, determine if we're in its scope\n if self.expanded_server then\n local expanded_server_line\n local next_server_line\n\n -- Find the expanded server's line and next server's line\n for _, tracked in ipairs(self.interactive_lines) do\n if tracked.type == \"server\" then\n if tracked.context.name == self.expanded_server then\n expanded_server_line = tracked.line\n elseif expanded_server_line and not next_server_line then\n -- This is the next server after our expanded one\n next_server_line = tracked.line\n break\n end\n end\n end\n\n -- Check if current line is within expanded server's section:\n -- After expanded server line and before next server (or end if no next server)\n if\n expanded_server_line\n and line > expanded_server_line\n and (not next_server_line or line < next_server_line)\n then\n self.expanded_server = nil\n self:draw()\n vim.api.nvim_win_set_cursor(0, { expanded_server_line, 3 })\n return\n end\n end\n\n -- If we have an expanded workspace, determine if we're in its scope\n if self.expanded_workspace then\n local expanded_workspace_line\n local next_workspace_line\n\n -- Find the expanded workspace's line and next workspace's line\n for _, tracked in ipairs(self.interactive_lines) do\n if tracked.type == \"workspace\" then\n if tracked.context.port == self.expanded_workspace then\n expanded_workspace_line = tracked.line\n elseif expanded_workspace_line and not next_workspace_line then\n -- This is the next workspace after our expanded one\n next_workspace_line = tracked.line\n break\n end\n end\n end\n\n -- Check if current line is within expanded workspace's section:\n -- After expanded workspace line and before next workspace (or end if no next workspace)\n if\n expanded_workspace_line\n and line > expanded_workspace_line\n and (not next_workspace_line or line < next_workspace_line)\n then\n self.expanded_workspace = nil\n self:draw()\n vim.api.nvim_win_set_cursor(0, { expanded_workspace_line, 3 })\n end\n end\nend\n\nfunction MainView:handle_custom_instructions(context)\n -- Get current instructions\n local server_config = config_manager.get_server_config(context.server_name) or {}\n local custom_instructions = server_config.custom_instructions or {}\n local text = custom_instructions.text or \"\"\n\n -- Open text box using base class method\n ui_utils.multiline_input(\"Custom Instructions\", text, function(content)\n if content ~= text then\n State.hub_instance:update_server_config(context.server_name, {\n custom_instructions = vim.tbl_extend(\"force\", custom_instructions, { text = content }),\n })\n vim.notify(\"Updated custom instructions for \" .. context.server_name, vim.log.levels.INFO)\n end\n end, {\n filetype = \"markdown\",\n start_insert = false,\n show_footer = false,\n })\nend\n\nfunction MainView:add_server()\n utils.open_server_editor({\n title = \"Paste Server Config\",\n start_insert = true,\n ask_for_source = true,\n })\nend\n\nfunction MainView:handle_edit()\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = cursor[1]\n\n local line_type, context = self:get_line_info(line)\n if not line_type or not context then\n return\n end\n local server_name = context.name\n if line_type == \"server\" then\n local is_native = native.is_native_server(server_name)\n local server_config = config_manager.get_server_config(server_name) or {}\n local config_source = config_manager.get_config_source(server_name)\n local text = utils.pretty_json(vim.json.encode({\n [server_name] = server_config,\n }) or \"\")\n utils.open_server_editor({\n title = \"Edit '\" .. server_name .. \"' Config\",\n is_native = is_native ~= nil,\n old_server_name = server_name,\n config_source = config_source,\n placeholder = text,\n start_insert = false,\n virtual_lines = {\n {\n Text.icons.hint\n .. \" ${VARIABLES} will be resolved from config.global_env or environment if not replaced\",\n Text.highlights.muted,\n },\n { Text.icons.hint .. \" ${cmd: echo 'secret'} will run command and replace ${}\", Text.highlights.muted },\n },\n })\n elseif (line_type == \"customInstructions\") and context then\n self:handle_custom_instructions(context)\n end\nend\n\n--- Handle killing a workspace process\n---@param context table Workspace context containing workspace details\nfunction MainView:handle_workspace_kill(context)\n if not context or not context.workspace_details then\n return\n end\n\n local workspace_details = context.workspace_details\n local workspace_name = vim.fn.fnamemodify(workspace_details.cwd, \":t\")\n local is_current = context.is_current\n\n -- -- Prevent killing current workspace\n -- if is_current then\n -- vim.notify(\"Cannot kill the current workspace. Switch to a different workspace first.\", vim.log.levels.WARN)\n -- return\n -- end\n\n -- Prepare confirmation message with proper highlights\n local ui_utils = require(\"mcphub.utils.ui\")\n local confirm_lines = {}\n\n -- Header line with highlights\n local header_line = NuiLine()\n header_line:append(\"Kill MCP Hub process for workspace \", Text.highlights.text)\n header_line:append(\"'\" .. workspace_name .. \"'\", Text.highlights.warn)\n header_line:append(\"?\", Text.highlights.text)\n table.insert(confirm_lines, header_line)\n table.insert(confirm_lines, \"\")\n\n -- Workspace details with highlights\n local port_line = NuiLine()\n port_line:append(\"Port: \", Text.highlights.muted)\n port_line:append(tostring(workspace_details.port), Text.highlights.info)\n table.insert(confirm_lines, port_line)\n\n local pid_line = NuiLine()\n pid_line:append(\"PID: \", Text.highlights.muted)\n pid_line:append(tostring(workspace_details.pid), Text.highlights.info)\n table.insert(confirm_lines, pid_line)\n\n local path_line = NuiLine()\n path_line:append(\"Path: \", Text.highlights.muted)\n path_line:append(workspace_details.cwd, Text.highlights.info)\n table.insert(confirm_lines, path_line)\n\n table.insert(confirm_lines, \"\")\n\n -- Warning with highlights\n local warning_line = NuiLine()\n warning_line:append(\"This will terminate the hub process.\", Text.highlights.error)\n table.insert(confirm_lines, warning_line)\n local async = require(\"plenary.async\")\n\n async.run(function()\n local confirmed, cancelled = ui_utils.confirm(confirm_lines, {\n min_width = 60,\n max_width = 80,\n })\n\n if confirmed and not cancelled then\n -- Kill the process\n local success = pcall(function()\n local uv = vim.loop or vim.uv\n uv.kill(workspace_details.pid, \"sigterm\")\n end)\n\n if success then\n vim.notify(\n string.format(\"Sent SIGTERM to workspace '%s' (PID: %d)\", workspace_name, workspace_details.pid),\n vim.log.levels.INFO\n )\n else\n vim.notify(\n string.format(\"Failed to kill workspace '%s' (PID: %d)\", workspace_name, workspace_details.pid),\n vim.log.levels.ERROR\n )\n end\n end\n end, function() end)\nend\n\n--- Handle changing directory to a workspace\nfunction MainView:handle_workspace_change_directory()\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = cursor[1]\n\n local type, context = self:get_line_info(line)\n if not type or not context or type ~= \"workspace\" then\n return\n end\n\n local workspace_details = context.workspace_details\n local target_dir = workspace_details.cwd\n local workspace_name = vim.fn.fnamemodify(target_dir, \":t\")\n\n -- Change directory\n local success, err = pcall(vim.cmd.cd, target_dir)\n if success then\n if State.config.workspace.enabled then\n vim.notify(string.format(\"Changed directory to '%s' (%s)\", workspace_name, target_dir), vim.log.levels.INFO)\n -- Trigger directory change handler to potentially switch hubs\n if State.hub_instance and State.hub_instance.handle_directory_change then\n State.hub_instance:handle_directory_change()\n end\n else\n vim.notify(\"Workspace feature is disabled, directory change won't trigger hub switch\", vim.log.levels.WARN)\n end\n else\n vim.notify(string.format(\"Failed to change directory: %s\", err), vim.log.levels.ERROR)\n end\nend\n\nfunction MainView:handle_delete()\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = cursor[1]\n\n local type, context = self:get_line_info(line)\n if not type or not context then\n return\n end\n if type == \"server\" then\n local server_name = context.name\n local is_native = native.is_native_server(server_name)\n if is_native then\n return vim.notify(\"Native servers cannot be deleted, only their configuration can be edited\")\n end\n utils.confirm_and_delete_server(server_name)\n elseif type == \"workspace\" and context then\n self:handle_workspace_kill(context)\n end\nend\n\nfunction MainView:handle_action(line_override, context_override)\n local go_to_cap_line = false\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = line_override or cursor[1]\n\n -- Get line info from either override or current line\n local type, context\n if context_override then\n type = context_override.type\n context = context_override.context\n else\n type, context = self:get_line_info(line)\n end\n if not type or not context then\n return\n end\n if type == \"breadcrumb\" then\n self:show_prompts_view()\n elseif type == \"server\" then\n -- Toggle expand/collapse for server\n if context.status == \"connected\" then\n if self.expanded_server == context.name then\n self.expanded_server = nil -- collapse\n self:draw()\n else\n self.expanded_server = context.name -- expand\n self:draw()\n\n -- Find server and capabilities in new view\n local server_line = nil\n local first_cap_line = nil\n\n for _, tracked in ipairs(self.interactive_lines) do\n if tracked.type == \"server\" and tracked.context.name == context.name then\n server_line = tracked.line\n elseif\n tracked.type == \"tool\"\n or tracked.type == \"resource\"\n or tracked.type == \"resourceTemplate\"\n or tracked.type == \"customInstructions\"\n then\n if tracked.context.server_name == context.name and not first_cap_line then\n first_cap_line = tracked.line\n break\n end\n end\n end\n\n -- Position cursor:\n -- 1. On first capability if exists\n -- 2. Otherwise on server line\n -- 3. Fallback to current line\n if first_cap_line and go_to_cap_line then\n vim.api.nvim_win_set_cursor(0, { first_cap_line, 3 })\n elseif server_line then\n vim.api.nvim_win_set_cursor(0, { server_line, 3 })\n else\n vim.api.nvim_win_set_cursor(0, { line, 3 })\n end\n end\n elseif context.status == \"unauthorized\" then\n local authUrl = State.hub_instance:get_server(context.name)[\"authorizationUrl\"]\n if not authUrl then\n return vim.notify(\"No authorization URL found for server \" .. context.name, vim.log.levels.ERROR)\n end\n ---Auto opens the browser with authorization URL\n State.hub_instance:authorize_mcp_server(context.name)\n -- Show popup for the user\n ui_utils.open_auth_popup(context.name, authUrl)\n end\n elseif type == \"create_server\" then\n -- Store browse mode position before switching\n self.cursor_positions.browse_mode = vim.api.nvim_win_get_cursor(0)\n\n -- Switch to createServer or addServer capability\n if type == \"create_server\" then\n self.active_capability =\n Capabilities.create_handler(\"createServer\", \"Native Servers\", { name = \"Create Server\" }, self)\n end\n self:setup_active_mode()\n self:draw()\n -- Move to capability's preferred position\n local cap_pos = self.active_capability:get_cursor_position()\n if cap_pos then\n vim.api.nvim_win_set_cursor(0, cap_pos)\n end\n elseif (type == \"tool\" or type == \"resource\" or type == \"resourceTemplate\" or type == \"prompt\") and context then\n if context.disabled then\n return\n end\n -- Store browse mode position before entering capability\n self.cursor_positions.browse_mode = vim.api.nvim_win_get_cursor(0)\n\n -- Create capability handler and switch to capability mode\n self.active_capability = Capabilities.create_handler(type, context.server_name, context, self)\n self:setup_active_mode()\n self:draw()\n\n -- Move to capability's preferred position\n local cap_pos = self.active_capability:get_cursor_position()\n if cap_pos then\n vim.api.nvim_win_set_cursor(0, cap_pos)\n end\n elseif (type == \"customInstructions\") and context then\n self:handle_custom_instructions(context)\n elseif type == \"add_server\" then\n self:add_server()\n elseif type == \"workspace\" and context then\n -- Toggle expand/collapse for workspace\n if self.expanded_workspace == context.port then\n self.expanded_workspace = nil -- collapse\n self:draw()\n else\n self.expanded_workspace = context.port -- expand\n self:draw()\n\n -- Find workspace line in new view and position cursor\n for _, tracked in ipairs(self.interactive_lines) do\n if tracked.type == \"workspace\" and tracked.context.port == context.port then\n vim.api.nvim_win_set_cursor(0, { tracked.line, 3 })\n break\n end\n end\n end\n end\nend\n\nfunction MainView:handle_cursor_move()\n -- Clear previous highlight\n if self.cursor_highlight then\n vim.api.nvim_buf_del_extmark(self.ui.buffer, self.hover_ns, self.cursor_highlight)\n self.cursor_highlight = nil\n end\n\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = cursor[1]\n if self.active_capability then\n self.active_capability:handle_cursor_move(self, line)\n else\n -- Get line info\n local type, context = self:get_line_info(line)\n if type then\n -- Add virtual text without line highlight\n self.cursor_highlight = vim.api.nvim_buf_set_extmark(self.ui.buffer, self.hover_ns, line - 1, 0, {\n virt_text = { { context and context.hint or \"[ Interact]\", Text.highlights.muted } },\n virt_text_pos = \"eol\",\n })\n end\n end\nend\n\nfunction MainView:setup_active_mode()\n if self.active_capability then\n self.keymaps = {\n [\"l\"] = {\n action = function()\n if self.active_capability.handle_action then\n self.active_capability:handle_action(vim.api.nvim_win_get_cursor(0)[1])\n end\n end,\n desc = \"Execute/Submit\",\n },\n [\"o\"] = {\n action = function()\n ---@diagnostic disable-next-line: undefined-field\n if self.active_capability.handle_text_box then\n ---@diagnostic disable-next-line: undefined-field\n self.active_capability:handle_text_box(vim.api.nvim_win_get_cursor(0)[1])\n end\n end,\n desc = \"Open text box\",\n },\n [\"\"] = {\n action = function()\n ---@diagnostic disable-next-line: undefined-field\n if self.active_capability.handle_tab then\n ---@diagnostic disable-next-line: undefined-field\n self.active_capability:handle_tab()\n end\n end,\n desc = \"Switch tab\",\n },\n [\"h\"] = {\n action = function()\n -- -- Store capability line before exiting\n -- self.cursor_positions.capability_line = vim.api.nvim_win_get_cursor(0)\n\n -- Clear active capability\n self.active_capability = nil\n\n -- Setup browse mode and redraw\n self:setup_active_mode()\n self:draw()\n\n -- Restore to last browse mode position\n if self.cursor_positions.browse_mode then\n vim.api.nvim_win_set_cursor(0, self.cursor_positions.browse_mode)\n end\n end,\n desc = \"Back\",\n },\n }\n else\n -- Normal mode keymaps\n self.keymaps = {\n [\"e\"] = {\n action = function()\n self:handle_edit()\n end,\n desc = \"Edit\",\n },\n [\"d\"] = {\n action = function()\n self:handle_delete()\n end,\n desc = \"Delete\",\n },\n\n [\"A\"] = {\n action = function()\n -- Handle like an add_server action\n self:add_server()\n end,\n desc = \"Add Server\",\n },\n [\"t\"] = {\n action = function()\n self:handle_server_toggle()\n end,\n desc = \"Toggle\",\n },\n [\"a\"] = {\n action = function()\n self:handle_auto_approve_toggle()\n end,\n desc = \"Auto-approve\",\n },\n [\"h\"] = {\n action = function()\n self:handle_collapse()\n end,\n desc = \"Collapse\",\n },\n [\"l\"] = {\n action = function()\n self:handle_action()\n end,\n desc = \"Expand\",\n },\n [\"gd\"] = {\n action = function()\n self:show_prompts_view()\n end,\n desc = \"Preview\",\n },\n [\"gc\"] = {\n action = function()\n self:handle_workspace_change_directory()\n end,\n desc = \"Change Directory\",\n },\n }\n end\n self.keymaps[\"ga\"] = {\n action = function()\n vim.g.mcphub_auto_approve = not vim.g.mcphub_auto_approve\n self:draw()\n end,\n desc = \"Toggle AutoApprove\",\n }\n\n -- Add silent keymap aliases for common expand/action keys\n if self.active_capability then\n self:add_keymap_alias(\"\", \"l\")\n self:add_keymap_alias(\"\", \"h\")\n else\n -- In browse mode, add silent aliases for expand action\n self:add_keymap_alias(\"\", \"l\") -- Enter key as alias for expand\n self:add_keymap_alias(\"o\", \"l\") -- 'o' key as alias for expand\n end\n\n self:apply_keymaps()\nend\n\n-- Helper function to get all tool names for a server\nlocal function get_server_tool_names(server_name)\n local tools = {}\n\n -- Check if it's a native server\n local is_native = native.is_native_server(server_name)\n if is_native then\n local native_server = is_native\n for _, tool in ipairs(native_server.capabilities.tools or {}) do\n table.insert(tools, tool.name)\n end\n else\n -- Regular MCP server\n for _, server in ipairs(State.server_state.servers) do\n if server.name == server_name and server.capabilities then\n for _, tool in ipairs(server.capabilities.tools or {}) do\n table.insert(tools, tool.name)\n end\n break\n end\n end\n end\n\n return tools\nend\n\n-- Helper function to determine actual auto-approval status\nlocal function get_auto_approval_status(server_config, all_tools)\n local auto_approve = server_config.autoApprove\n\n if auto_approve == true then\n return \"all\", #all_tools -- All tools auto-approved\n elseif type(auto_approve) == \"table\" and vim.islist(auto_approve) then\n if #auto_approve == 0 then\n return \"none\", 0\n elseif #auto_approve == #all_tools then\n return \"all\", #all_tools -- All tools are in the list\n else\n return \"partial\", #auto_approve -- Some tools auto-approved\n end\n else\n return \"none\", 0 -- No auto-approval\n end\nend\n\nfunction MainView:handle_auto_approve_toggle()\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = cursor[1]\n\n -- Get line info\n local type, context = self:get_line_info(line)\n if not type or not context or not State.hub_instance then\n return\n end\n\n if type == \"server\" then\n -- Check if server is enabled\n if context.status == \"disabled\" or context.status == \"disconnected\" then\n return\n end\n\n -- Toggle auto-approval for entire server\n local server_name = context.name\n local server_config = config_manager.get_server_config(server_name) or {}\n\n local all_tools = get_server_tool_names(server_name)\n local status, _ = get_auto_approval_status(server_config, all_tools)\n local new_auto_approve\n\n if status == \"all\" then\n -- Currently auto-approving all tools, turn off\n new_auto_approve = {}\n else\n -- Currently partial or no auto-approval, enable for all\n new_auto_approve = vim.deepcopy(all_tools)\n end\n\n State.hub_instance:update_server_config(server_name, {\n autoApprove = new_auto_approve,\n })\n elseif type == \"tool\" and context then\n -- Check if tool is enabled\n if context.disabled then\n return\n end\n\n -- Toggle auto-approval for specific tool\n local server_name = context.server_name\n local tool_name = context.def.name\n local server_config = config_manager.get_server_config(server_name) or {}\n\n local current_auto_approve = server_config.autoApprove or {}\n local new_auto_approve\n\n -- Handle boolean case (convert to array first)\n if current_auto_approve == true then\n local all_tools = get_server_tool_names(server_name)\n current_auto_approve = vim.deepcopy(all_tools)\n end\n\n -- Ensure it's an array\n if not vim.islist(current_auto_approve) then\n current_auto_approve = {}\n end\n\n -- Toggle the tool in the list using filter instead of table.remove\n local tool_approved = vim.tbl_contains(current_auto_approve, tool_name)\n\n if tool_approved then\n -- Remove tool from auto-approve list\n new_auto_approve = vim.tbl_filter(function(tool)\n return tool ~= tool_name\n end, current_auto_approve)\n else\n -- Add tool to auto-approve list\n new_auto_approve = vim.deepcopy(current_auto_approve)\n table.insert(new_auto_approve, tool_name)\n end\n\n State.hub_instance:update_server_config(server_name, {\n autoApprove = new_auto_approve,\n })\n end\nend\nfunction MainView:handle_server_toggle()\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = cursor[1]\n\n -- Get line info\n local type, context = self:get_line_info(line)\n if type == \"server\" and context and State.hub_instance then\n -- Handle regular MCP server\n -- Gets updated via sse endpoint after file changed rather than explicitly send curl request\n if context.status == \"disabled\" then\n State.hub_instance:start_mcp_server(context.name, {\n -- via_curl_request = true,\n -- callback = function(response, err)\n -- if err then\n -- vim.notify(\"Failed to enable server: \" .. err, vim.log.levels.ERROR)\n -- end\n -- end,\n })\n else\n State.hub_instance:stop_mcp_server(context.name, true, {\n -- via_curl_request = true,\n -- callback = function(response, err)\n -- if err then\n -- vim.notify(\"Failed to disable server: \" .. err, vim.log.levels.ERROR)\n -- end\n -- end,\n })\n end\n elseif\n (type == \"tool\" or type == \"resource\" or type == \"resourceTemplate\" or type == \"prompt\")\n and context\n and State.hub_instance\n then\n local server_name = context.server_name\n local server_config = config_manager.get_server_config(server_name) or {}\n\n local type_config = {\n tool = { id_field = \"name\", config_field = \"disabled_tools\" },\n resource = { id_field = \"uri\", config_field = \"disabled_resources\" },\n resourceTemplate = { id_field = \"uriTemplate\", config_field = \"disabled_resourceTemplates\" },\n prompt = { id_field = \"name\", config_field = \"disabled_prompts\" },\n }\n\n local config = type_config[type]\n local capability_id = context.def[config.id_field]\n local disabled_list = vim.deepcopy(server_config[config.config_field] or {})\n local is_disabled = vim.tbl_contains(disabled_list, capability_id)\n\n -- Update disabled list based on desired state\n if is_disabled then\n for i, item_id in ipairs(disabled_list) do\n if item_id == capability_id then\n table.remove(disabled_list, i)\n break\n end\n end\n else\n table.insert(disabled_list, capability_id)\n end\n\n -- Update server config with new disabled list\n local updates = {}\n updates[config.config_field] = disabled_list\n State.hub_instance:update_server_config(server_name, updates)\n State:emit(type .. \"_list_changed\", {\n server_name = server_name,\n config_field = config.config_field,\n disabled_list = disabled_list,\n })\n elseif type == \"customInstructions\" and context then\n -- Toggle custom instructions state\n local server_name = context.server_name\n local server_config = config_manager.get_server_config(server_name) or {}\n local custom_instructions = server_config.custom_instructions or {}\n local is_disabled = custom_instructions.disabled\n\n State.hub_instance:update_server_config(server_name, {\n custom_instructions = {\n disabled = not is_disabled,\n },\n })\n end\nend\n\nfunction MainView:get_initial_cursor_position()\n -- Position after server status section\n local lines = self:render_header(false)\n -- vim.list_extend(lines, self:render_hub_status(self:get_width()))\n -- In browse mode, restore last browse position\n if not self.active_capability and self.cursor_positions.browse_mode then\n return self.cursor_positions.browse_mode[1]\n end\n return #lines + 1\nend\n\n--- Sort servers by status (connected first, then disconnected, disabled last) and alphabetically within each group\n---@param servers table[] List of servers to sort\nlocal function sort_servers(servers)\n table.sort(servers, function(a, b)\n -- First compare status priority\n local status_priority = {\n connected = 1,\n disconnected = 2,\n disabled = 3,\n }\n local a_priority = status_priority[a.status] or 2 -- default to disconnected priority\n local b_priority = status_priority[b.status] or 2\n\n if a_priority ~= b_priority then\n return a_priority < b_priority\n end\n\n -- If same status, sort alphabetically\n return a.name < b.name\n end)\n return servers\nend\n\n--- Render a server section\n---@param title? string Section title\n---@param servers table[] List of servers\n---@param current_line number Current line number\n---@return NuiLine[], number Lines and new current line\nfunction MainView:render_servers_section(title, servers, current_line)\n local lines = {}\n\n if title then\n -- Section header\n table.insert(lines, Text.pad_line(NuiLine():append(title, Text.highlights.title)))\n current_line = current_line + 1\n end\n\n -- If no servers in section\n if not servers or #servers == 0 then\n table.insert(\n lines,\n Text.pad_line(\n NuiLine():append(\" No servers connected \" .. \"(Install from Marketplace)\", Text.highlights.muted)\n )\n )\n table.insert(lines, Text.empty_line())\n return lines, current_line + 2\n end\n\n -- Sort and render servers\n local sorted = sort_servers(vim.deepcopy(servers))\n for _, server in ipairs(sorted) do\n local server_config = config_manager.get_server_config(server) or {}\n current_line =\n renderer.render_server_capabilities(server, lines, current_line, server_config, self, server.is_native)\n end\n\n return lines, current_line\nend\n\n--- Render all server sections\n---@return NuiLine[]\nfunction MainView:render_servers(line_offset)\n local lines = {}\n local current_line = line_offset\n\n local width = self:get_width() - (Text.HORIZONTAL_PADDING * 2)\n -- Start with top-level MCP Servers header\n local left_section = NuiLine():append(\"MCP Servers\", Text.highlights.title)\n\n -- Add token count on MCP Servers section if connected\n if State:is_connected() and State.hub_instance and State.hub_instance:is_ready() then\n local prompts = State.hub_instance:generate_prompts()\n if prompts then\n -- Calculate total tokens from all prompts\n local active_servers_tokens = utils.calculate_tokens(prompts.active_servers or \"\")\n local use_mcp_tool_tokens = utils.calculate_tokens(prompts.use_mcp_tool or \"\")\n local access_mcp_resource_tokens = utils.calculate_tokens(prompts.access_mcp_resource or \"\")\n local total_tokens = active_servers_tokens + use_mcp_tool_tokens + access_mcp_resource_tokens\n\n if total_tokens > 0 then\n left_section:append(\n \" (~ \" .. utils.format_token_count(total_tokens) .. \" tokens)\",\n Text.highlights.muted\n )\n end\n end\n end\n local is_auto_approve_enabled = vim.g.mcphub_auto_approve == true\n local right_section = NuiLine()\n :append(Text.icons.auto, is_auto_approve_enabled and Text.highlights.success or Text.highlights.muted)\n :append(\" AutoApprove: \", Text.highlights.muted)\n :append(\n is_auto_approve_enabled and \"ON\" or \"OFF\",\n is_auto_approve_enabled and Text.highlights.success or Text.highlights.muted\n )\n right_section\n :append(\" | \", Text.highlights.muted)\n :append(Text.icons.tower, Text.highlights.success)\n :append(\" Port: \", Text.highlights.success)\n :append(tostring(State.current_hub.port or \"N/A\"), Text.highlights.success)\n\n -- Calculate padding needed between sections\n local total_content_width = left_section:width() + right_section:width()\n local padding = width - total_content_width\n\n -- Combine sections with padding\n local header_line = NuiLine():append(left_section):append(string.rep(\" \", padding)):append(right_section)\n\n table.insert(lines, Text.pad_line(header_line))\n current_line = current_line + 1\n -- Track breadcrumb line for interaction\n -- self:track_line(current_line, \"breadcrumb\", {\n -- hint = \" to preview servers prompt\",\n -- })\n table.insert(lines, self:divider())\n current_line = current_line + 1\n\n current_line = renderer.render_servers_grouped(State.server_state.servers, lines, current_line, self)\n\n -- -- Add server creation options\n -- table.insert(\n -- lines,\n -- Text.pad_line(\n -- NuiLine()\n -- :append(\" \" .. Text.icons.plus .. \" \", Text.highlights.muted)\n -- :append(\"Add Server (A)\", Text.highlights.muted)\n -- )\n -- )\n -- -- Track line for interaction\n -- self:track_line(current_line + 1, \"add_server\", {\n -- name = \"Add Server\",\n -- hint = \"[ Open Editor]\",\n -- })\n -- current_line = current_line + 1\n\n -- Add spacing between sections\n table.insert(lines, Text.empty_line())\n current_line = current_line + 1\n\n -- Native servers section header\n table.insert(lines, Text.pad_line(NuiLine():append(\"\" .. \" Native Servers\", Text.highlights.title)))\n current_line = current_line + 1\n\n -- Render Native servers first\n local native_lines, native_line = self:render_servers_section(\n nil, -- No title since we added it above\n State.server_state.native_servers,\n current_line\n )\n vim.list_extend(lines, native_lines)\n current_line = native_line\n\n -- Add create server option\n -- table.insert(lines, Text.empty_line())\n table.insert(\n lines,\n Text.pad_line(\n NuiLine()\n :append(\" \" .. Text.icons.edit .. \" \", Text.highlights.muted)\n :append(\"Auto-create Server\", Text.highlights.muted)\n )\n )\n -- Track line for interaction\n self:track_line(current_line + 1, \"create_server\", {\n hint = \"[ Create Server]\",\n })\n\n return lines\nend\n\nfunction MainView:before_enter()\n View.before_enter(self)\n self:setup_active_mode()\nend\n\nfunction MainView:after_enter()\n View.after_enter(self)\n\n local line_count = vim.api.nvim_buf_line_count(self.ui.buffer)\n -- Restore appropriate cursor position\n if self.active_capability then\n local cap_pos = self.cursor_positions.capability_line or self.active_capability:get_cursor_position()\n if cap_pos then\n local new_pos = { math.min(cap_pos[1], line_count), cap_pos[2] }\n vim.api.nvim_win_set_cursor(0, new_pos)\n end\n else\n -- In browse mode, restore last browse position with column\n if self.cursor_positions.browse_mode then\n local new_pos = {\n math.min(self.cursor_positions.browse_mode[1], line_count),\n self.cursor_positions.browse_mode[2] or 2,\n }\n vim.api.nvim_win_set_cursor(0, new_pos)\n end\n end\nend\n\nfunction MainView:before_leave()\n -- Store appropriate position based on current mode\n if self.active_capability then\n -- In capability mode, store full position\n self.cursor_positions.capability_line = vim.api.nvim_win_get_cursor(0)\n else\n -- In browse mode, store full position\n self.cursor_positions.browse_mode = vim.api.nvim_win_get_cursor(0)\n end\n\n View.before_leave(self)\nend\n\nfunction MainView:should_show_logs()\n return not vim.tbl_contains({ constants.HubState.READY, constants.HubState.RESTARTED }, State.server_state.state)\nend\n\nfunction MainView:render()\n -- Handle special states from base view\n if State.setup_state == \"failed\" or State.setup_state == \"in_progress\" or State.setup_state == \"not_started\" then\n return View.render(self)\n end\n -- Get base header\n local lines = self:render_header(false)\n if self:should_show_logs() then\n local state_info = renderer.get_hub_info(State.server_state.state)\n local breadcrumb_line = NuiLine():append(state_info.icon, state_info.hl):append(state_info.desc, state_info.hl)\n table.insert(lines, Text.pad_line(breadcrumb_line))\n table.insert(lines, self:divider())\n vim.list_extend(lines, renderer.render_server_entries(State.server_output.entries))\n local errors = renderer.render_hub_errors(nil, false)\n if #errors > 0 then\n vim.list_extend(lines, errors)\n end\n return lines\n end\n -- Handle capability mode\n if self.active_capability then\n -- Get base header\n local capability_view_lines = self:render_header(false)\n -- Add breadcrumb\n local breadcrumb = NuiLine()\n breadcrumb\n :append(self.active_capability.server_name, Text.highlights.muted)\n :append(\" > \", Text.highlights.muted)\n :append(self.active_capability.name, Text.highlights.info)\n table.insert(capability_view_lines, Text.pad_line(breadcrumb))\n table.insert(capability_view_lines, self:divider())\n -- Let capability render its content\n vim.list_extend(capability_view_lines, self.active_capability:render(#capability_view_lines))\n return capability_view_lines\n end\n\n -- Servers section\n vim.list_extend(lines, self:render_servers(#lines))\n\n -- Add spacing before workspaces section\n table.insert(lines, Text.empty_line())\n table.insert(lines, Text.empty_line())\n\n -- Workspaces section\n vim.list_extend(lines, self:render_workspaces(#lines))\n\n return lines\nend\n\n--- Render workspaces section using renderer\n---@param line_offset number Current line number\n---@return NuiLine[] Lines for workspaces section\nfunction MainView:render_workspaces(line_offset)\n return renderer.render_workspaces_section(line_offset, self)\nend\nreturn MainView\n"], ["/mcphub.nvim/lua/mcphub/native/mcphub/guide.lua", "local mcphub = require(\"mcphub\")\nlocal prompt_utils = require(\"mcphub.utils.prompt\")\n\nmcphub.add_tool(\"mcphub\", {\n name = \"get_current_servers\",\n description = \"Get the current state of all MCP servers (connected and disabled). This is useful when you need to know what servers are currently available, especially when restoring chat from history or when server state may have changed.\",\n inputSchema = {\n type = \"object\",\n properties = {\n include_disabled = {\n type = \"boolean\",\n description = \"Whether to include disabled servers in the response (default: true)\",\n default = true,\n },\n format = {\n type = \"string\",\n description = \"Response format: 'detailed' for full server info or 'summary' for compact list (default: detailed)\",\n enum = { \"detailed\", \"summary\" },\n default = \"detailed\",\n },\n },\n },\n handler = function(req, res)\n local hub = mcphub.get_hub_instance()\n if not hub or not hub:is_ready() then\n return res:error(\"Hub is not ready\")\n end\n\n local include_disabled = req.params.include_disabled ~= false -- default to true\n local format = req.params.format or \"detailed\"\n\n if format == \"summary\" then\n local connected_count = 0\n local disabled_count = 0\n local server_names = { connected = {}, disabled = {} }\n\n local servers = hub:get_servers(include_disabled)\n for _, server in ipairs(servers) do\n if server.status == \"connected\" then\n connected_count = connected_count + 1\n table.insert(server_names.connected, server.name)\n elseif server.status == \"disabled\" then\n disabled_count = disabled_count + 1\n table.insert(server_names.disabled, server.name)\n end\n end\n\n local summary = string.format(\n \"# Current MCP Server Status\\n\\n\" .. \"Connected servers (%d): %s\\n\" .. \"Disabled servers (%d): %s\",\n connected_count,\n #server_names.connected > 0 and table.concat(server_names.connected, \", \") or \"None\",\n disabled_count,\n #server_names.disabled > 0 and table.concat(server_names.disabled, \", \") or \"None\"\n )\n\n return res:text(summary):send()\n else\n -- Detailed format using the existing active servers prompt\n local detailed_info = hub:get_active_servers_prompt(true, include_disabled)\n return res:text(detailed_info):send()\n end\n end,\n})\n\nmcphub.add_tool(\"mcphub\", {\n name = \"toggle_mcp_server\",\n description = \"Start or stop an MCP server. You can only start a server from one of the disabled servers.\",\n inputSchema = {\n type = \"object\",\n properties = {\n server_name = {\n type = \"string\",\n description = \"Name of the MCP server to toggle\",\n },\n action = {\n type = \"string\",\n description = \"Action to perform. One of 'start' or 'stop'\",\n enum = { \"start\", \"stop\" },\n },\n },\n required = { \"server_name\", \"action\" },\n },\n handler = function(req, res)\n local hub = mcphub.get_hub_instance()\n if not hub or not hub:is_ready() then\n return res:error(\"Hub is not ready\")\n end\n\n local server_name = req.params.server_name\n local action = req.params.action\n if not server_name or not action then\n return res:error(\"Missing required parameters: server_name and action\")\n end\n\n -- Check if server exists in current state\n local found = false\n for _, server in ipairs(hub:get_servers(true)) do\n if server.name == server_name then\n found = true\n break\n end\n end\n\n if not found then\n return res:error(string.format(\"Server '%s' not found in active servers\", server_name))\n end\n\n --INFO: via_curl_request: because we can wait for the server to start or stop and send the correct status to llm rather than sse event based on file wathing which is more appropriate for UI\n if action == \"start\" then\n hub:start_mcp_server(server_name, {\n via_curl_request = true,\n callback = function(response, err)\n if err then\n return res:error(string.format(\"Failed to start MCP server: %s\", err))\n end\n local server = response and response.server\n return res\n :text(\n string.format(\"Started MCP server: %s\\n%s\", server_name, hub:convert_server_to_text(server))\n )\n :send()\n end,\n })\n elseif action == \"stop\" then\n hub:stop_mcp_server(server_name, true, {\n via_curl_request = true,\n callback = function(_, err)\n if err then\n return res:error(string.format(\"Failed to stop MCP server: %s\", err))\n end\n return res:text(string.format(\"Stopped MCP server: %s.\", server_name)):send()\n end,\n })\n else\n return res:error(string.format(\"Invalid action '%s'. Use 'start' or 'stop'\", action))\n end\n end,\n})\n\nmcphub.add_resource(\"mcphub\", {\n name = \"MCPHub Plugin Docs\",\n mimeType = \"text/plain\",\n uri = \"mcphub://docs\",\n description = [[Documentation for the mcphub.nvim plugin for Neovim.]],\n handler = function(_, res)\n local guide = prompt_utils.get_plugin_docs()\n if not guide then\n return res:error(\"Plugin docs not available\")\n end\n return res:text(guide):send()\n end,\n})\n\nmcphub.add_resource(\"mcphub\", {\n name = \"MCPHub Native Server Guide\",\n mimeType = \"text/plain\",\n uri = \"mcphub://native_server_guide\",\n description = [[Documentation on how to create Lua Native MCP servers for mcphub.nvim plugin.\nThis guide is intended for Large language models to help users create their own native servers for mcphub.nvim plugin.\nAccess this guide whenever you need information on how to create a native server for mcphub.nvim plugin.]],\n handler = function(_, res)\n local guide = prompt_utils.get_native_server_prompt()\n if not guide then\n return res:error(\"Native server guide not available\")\n end\n return res:text(guide):send()\n end,\n})\n\nmcphub.add_resource(\"mcphub\", {\n name = \"MCPHub Changelog\",\n mimeType = \"text/plain\",\n uri = \"mcphub://changelog\",\n description = [[Changelog for the mcphub.nvim plugin for Neovim.]],\n handler = function(_, res)\n local guide = prompt_utils.get_plugin_changelog()\n if not guide then\n return res:error(\"Plugin changelog not available\")\n end\n return res:text(guide):send()\n end,\n})\n"], ["/mcphub.nvim/lua/mcphub/utils/renderer.lua", "local NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal config_manager = require(\"mcphub.utils.config_manager\")\nlocal constants = require(\"mcphub.utils.constants\")\nlocal utils = require(\"mcphub.utils\")\n\nlocal M = {}\n\n--- Get display name for a config source\n---@param config_source string Path to config file\n---@return string Display name for the source\nfunction M.get_source_display_name(config_source)\n if not config_source then\n return \"Unknown\"\n end\n\n -- Get filename\n local filename = vim.fn.fnamemodify(config_source, \":t\")\n return filename\nend\n\n--- Render servers grouped by config source\n---@param servers table[] List of servers\n---@param lines table[] Existing lines to append to\n---@param current_line number Current line number\n---@param view MainView View instance for tracking\n---@return number New current line\nfunction M.render_servers_grouped(servers, lines, current_line, view)\n local config_files = config_manager.get_active_config_files(true)\n -- Render each group\n for i, config_source in ipairs(config_files) do\n local group_servers = vim.tbl_filter(function(s)\n return s.config_source == config_source\n end, servers)\n current_line = M.render_server_group(config_source, group_servers, lines, current_line, view)\n if i < #config_files then\n table.insert(lines, Text.empty_line())\n current_line = current_line + 1\n end\n end\n -- Show empty project group if no marker files are found\n if #config_files == 1 and State.config.workspace.enabled then\n table.insert(lines, Text.empty_line())\n current_line = current_line + 1\n local is_global = false\n local icon = is_global and Text.icons.globe or Text.icons.folder\n local prefix = icon .. \" \" .. (is_global and \"Global\" or \"Project\") .. \" \"\n local header_line = NuiLine():append(prefix, Text.highlights.title)\n table.insert(lines, Text.pad_line(header_line))\n current_line = current_line + 1\n local line = NuiLine()\n local look_for = table.concat(State.config.workspace.look_for or {}, \", \")\n line:append(string.format(\"%s not in path\", look_for), Text.highlights.muted)\n table.insert(lines, Text.pad_line(line, nil, 4))\n current_line = current_line + 1\n end\n\n return current_line\nend\n\n--- Render a single server group with header\n---@param config_source string Config file path\n---@param servers table[] Servers in this group\n---@param lines table[] Lines to append to\n---@param current_line number Current line number\n---@param view MainView View instance\n---@return number New current line\nfunction M.render_server_group(config_source, servers, lines, current_line, view)\n -- Sort servers within group (connected > disconnected > disabled)\n local sorted = vim.deepcopy(servers)\n table.sort(sorted, function(a, b)\n -- First compare status priority\n local status_priority = {\n connected = 1,\n disconnected = 2,\n disabled = 3,\n }\n local a_priority = status_priority[a.status] or 2\n local b_priority = status_priority[b.status] or 2\n\n if a_priority ~= b_priority then\n return a_priority < b_priority\n end\n\n -- If same status, sort alphabetically\n return a.name < b.name\n end)\n\n local is_global = config_source == State.config.config\n local icon = is_global and Text.icons.globe or Text.icons.folder\n local prefix = icon .. \" \" .. (is_global and \"Global\" or \"Project\") .. \" \"\n\n -- Render group header\n -- local display_name = M.get_source_display_name(config_source)\n local header_line = NuiLine():append(prefix, Text.highlights.title)\n table.insert(lines, Text.pad_line(header_line))\n current_line = current_line + 1\n if #sorted == 0 then\n -- No servers in this group\n table.insert(\n lines,\n Text.pad_line(\n NuiLine():append(\n string.format(\"No servers found in `%s` (Install from Marketplace)\", config_source),\n Text.highlights.muted\n ),\n nil,\n 4\n )\n )\n return current_line + 1\n end\n\n for _, server in ipairs(sorted) do\n local server_config = config_manager.get_server_config(server) or {}\n current_line = M.render_server_capabilities(server, lines, current_line, server_config, view, server.is_native)\n end\n\n return current_line\nend\n\nfunction M.get_hub_info(state)\n local icon = ({\n [constants.HubState.STARTING] = \"◉ \",\n [constants.HubState.READY] = Text.icons.loaded .. \" \",\n [constants.HubState.RESTARTING] = \"◉ \",\n [constants.HubState.RESTARTED] = Text.icons.loaded .. \" \",\n [constants.HubState.STOPPING] = \"◉ \",\n [constants.HubState.STOPPED] = \"○ \",\n [constants.HubState.ERROR] = Text.icons.error .. \" \",\n })[state] or \"⚠ \"\n\n local desc = ({\n [constants.HubState.STARTING] = \"Starting...\",\n [constants.HubState.READY] = \"Connected\",\n [constants.HubState.RESTARTING] = \"Restarting...\",\n [constants.HubState.RESTARTED] = \"Restarted\",\n [constants.HubState.STOPPING] = \"Stopping...\",\n [constants.HubState.STOPPED] = \"Stopped\",\n [constants.HubState.ERROR] = \"Error\",\n })[state] or \"Unknown\"\n\n local hl = ({\n [constants.HubState.STARTING] = Text.highlights.success,\n [constants.HubState.READY] = Text.highlights.success,\n [constants.HubState.RESTARTING] = Text.highlights.success,\n [constants.HubState.RESTARTED] = Text.highlights.success,\n [constants.HubState.STOPPING] = Text.highlights.warn,\n [constants.HubState.STOPPED] = Text.highlights.warn,\n [constants.HubState.ERROR] = Text.highlights.error,\n })[state] or Text.highlights.error\n return {\n icon = icon,\n desc = desc,\n hl = hl,\n }\nend\n\n--- Get server status information\n---@param status string Server status\n---@return { icon: string, desc: string, hl: string } Status info\nfunction M.get_server_status_info(status, expanded)\n return {\n icon = ({\n connected = (expanded and Text.icons.triangleDown or Text.icons.triangleRight) .. \" \",\n connecting = \"◉ \",\n restarting = \"◉ \",\n unauthorized = Text.icons.unauthorized .. \" \",\n disconnecting = \"○ \",\n disconnected = \"○ \",\n disabled = \"○ \",\n })[status] or \"⚠ \",\n\n desc = ({\n connecting = \" (connecting...)\",\n disconnecting = \" (disconnecting...)\",\n unauthorized = \" (unauthorized)\",\n })[status] or \"\",\n\n hl = ({\n connected = Text.highlights.success,\n connecting = Text.highlights.success,\n restarting = Text.highlights.success,\n disconnecting = Text.highlights.warn,\n disconnected = Text.highlights.warn,\n unauthorized = Text.highlights.warn,\n disabled = Text.highlights.muted,\n })[status] or Text.highlights.error,\n }\nend\n\n--- Render server capabilities section\n---@param items table[] List of items\n---@param title string Section title\n---@param server_name string Server name\n---@param line_type string Item type\n---@param current_line number Current line number\n---@param server_config table Server configuration\n---@return NuiLine[],number,table\nfunction M.render_cap_section(items, title, server_name, line_type, current_line, server_config)\n local lines = {}\n local mappings = {}\n\n local icons = {\n tool = Text.icons.tool,\n resource = Text.icons.resource,\n resourceTemplate = Text.icons.resourceTemplate,\n prompt = Text.icons.prompt,\n }\n table.insert(\n lines,\n Text.pad_line(NuiLine():append(\" \" .. icons[line_type] .. \" \" .. title .. \": \", Text.highlights.muted), nil, 4)\n )\n\n local disabled_tools = server_config.disabled_tools or {}\n if line_type == \"tool\" then\n -- For tools, sort by name and move disabled ones to end\n local sorted_items = vim.deepcopy(items)\n table.sort(sorted_items, function(a, b)\n local a_disabled = vim.tbl_contains(disabled_tools, a.name)\n local b_disabled = vim.tbl_contains(disabled_tools, b.name)\n if a_disabled ~= b_disabled then\n return not a_disabled\n end\n return a.name < b.name\n end)\n items = sorted_items\n end\n\n for _, item in ipairs(items) do\n local name = item.name or item.uri or item.uriTemplate or \"NO NAME\"\n local is_disabled = false\n if line_type == \"tool\" then\n is_disabled = vim.tbl_contains(disabled_tools, item.name)\n elseif line_type == \"resource\" then\n is_disabled = vim.tbl_contains(server_config.disabled_resources or {}, item.uri)\n elseif line_type == \"resourceTemplate\" then\n is_disabled = vim.tbl_contains(server_config.disabled_resourceTemplates or {}, item.uriTemplate)\n elseif line_type == \"prompt\" then\n is_disabled = vim.tbl_contains(server_config.disabled_prompts or {}, item.name)\n end\n\n local line = NuiLine()\n if is_disabled then\n line:append(Text.icons.circle .. \" \", Text.highlights.muted):append(name, Text.highlights.muted)\n else\n line:append(Text.icons.arrowRight .. \" \", Text.highlights.muted):append(name, Text.highlights.info)\n end\n\n if item.mimeType then\n line:append(\" (\" .. item.mimeType .. \")\", Text.highlights.muted)\n end\n\n -- Show auto-approve status for tools\n if line_type == \"tool\" and not is_disabled then\n local auto_approve = server_config.autoApprove\n local tool_auto_approved = false\n\n if auto_approve == true then\n tool_auto_approved = true\n elseif type(auto_approve) == \"table\" and vim.islist(auto_approve) then\n tool_auto_approved = vim.tbl_contains(auto_approve, name)\n end\n\n if tool_auto_approved then\n line:append(\" \" .. Text.icons.auto, Text.highlights.success)\n end\n end\n\n table.insert(lines, Text.pad_line(line, nil, 6))\n\n local hint\n if is_disabled then\n hint = \"[ Toggle]\"\n elseif line_type == \"tool\" then\n hint = string.format(\"[ open %s, Toggle, Auto-approve]\", line_type)\n else\n hint = string.format(\"[ open %s, Toggle]\", line_type)\n end\n table.insert(mappings, {\n line = current_line + #lines,\n type = line_type,\n context = {\n def = item,\n server_name = server_name,\n disabled = is_disabled,\n hint = hint,\n },\n })\n end\n\n return lines, current_line + #lines, mappings\nend\n\n--- Function to render a single server's capabilities\n---@param server table Server to render\n---@param lines table[] Lines array to append to\n---@param current_line number Current line number\n---@param server_config table Config source for the server\n---@param view MainView View instance for tracking\n---@return number New current line\nfunction M.render_server_capabilities(server, lines, current_line, server_config, view, is_native)\n local server_name_line = M.render_server_line(server, view.expanded_server == server.name)\n table.insert(lines, Text.pad_line(server_name_line, nil, 3))\n current_line = current_line + 1\n\n -- Prepare hover hint based on server status\n local base_hint_disabled = is_native and \"[ Toggle, Edit]\" or \"[ Toggle, Edit, Delete]\"\n local base_hint_enabled = is_native and \"[ Toggle, Auto-approve, Edit]\"\n or \"[ Toggle, Auto-approve, Edit, Delete]\"\n\n local needs_authorization = server.status == \"unauthorized\"\n local enabled_hint = is_native and \"[ Expand, Toggle, Auto-approve, Edit]\"\n or needs_authorization and \"[ Authorize, Toggle, Auto-approve, Edit, Delete]\"\n or \"[ Expand, Toggle, Auto-approve, Edit, Delete]\"\n local expanded_hint = is_native and \"[ Collapse, Toggle, Auto-approve, Edit]\"\n or \"[ Collapse, Toggle, Auto-approve, Edit, Delete]\"\n\n local hint\n if server.status == \"disabled\" or server.status == \"disconnected\" then\n hint = base_hint_disabled -- No auto-approve for disabled/disconnected servers\n else\n hint = view.expanded_server == server.name and expanded_hint or enabled_hint\n end\n\n view:track_line(current_line, \"server\", {\n name = server.name,\n status = server.status,\n hint = hint,\n })\n\n -- Show expanded server capabilities\n if server.status == \"connected\" and server.capabilities and view.expanded_server == server.name then\n -- local desc = server.description or \"\"\n -- if desc ~= \"\" then\n -- table.insert(lines, Text.pad_line(NuiLine():append(tostring(desc), Text.highlights.muted), nil, 5))\n -- current_line = current_line + 1\n -- end\n\n if\n #server.capabilities.tools + #server.capabilities.resources + #server.capabilities.resourceTemplates\n == 0\n then\n table.insert(\n lines,\n Text.pad_line(NuiLine():append(\"No capabilities available\", Text.highlights.muted), nil, 6)\n )\n table.insert(lines, Text.empty_line())\n current_line = current_line + 2\n return current_line\n end\n\n local custom_instructions = server_config.custom_instructions or {}\n local is_disabled = custom_instructions.disabled == true\n local has_instructions = custom_instructions.text and #custom_instructions.text > 0\n local ci_line = NuiLine()\n :append(is_disabled and Text.icons.circle or Text.icons.instructions, Text.highlights.muted)\n :append(\n \" Custom Instructions\" .. (not is_disabled and not has_instructions and \" (empty)\" or \"\"),\n (is_disabled or not has_instructions) and Text.highlights.muted or Text.highlights.info\n )\n table.insert(lines, Text.pad_line(ci_line, nil, 5))\n current_line = current_line + 1\n view:track_line(current_line, \"customInstructions\", {\n server_name = server.name,\n disabled = is_disabled,\n name = Text.icons.instructions .. \" Custom Instructions\",\n hint = is_disabled and \"[ Toggle]\" or \"[ Edit, Toggle]\",\n })\n table.insert(lines, Text.empty_line())\n current_line = current_line + 1\n\n if #server.capabilities.prompts > 0 then\n local section_lines, new_line, mappings = M.render_cap_section(\n server.capabilities.prompts,\n \"Prompts\",\n server.name,\n \"prompt\",\n current_line,\n server_config\n )\n vim.list_extend(lines, section_lines)\n for _, m in ipairs(mappings) do\n view:track_line(m.line, m.type, m.context)\n end\n table.insert(lines, Text.empty_line())\n current_line = new_line + 1\n end\n -- Tools section if any\n if #server.capabilities.tools > 0 then\n local section_lines, new_line, mappings = M.render_cap_section(\n server.capabilities.tools,\n \"Tools\",\n server.name,\n \"tool\",\n current_line,\n server_config\n )\n vim.list_extend(lines, section_lines)\n for _, m in ipairs(mappings) do\n view:track_line(m.line, m.type, m.context)\n end\n table.insert(lines, Text.empty_line())\n current_line = new_line + 1\n end\n\n -- Resources section if any\n if #server.capabilities.resources > 0 then\n local section_lines, new_line, mappings = M.render_cap_section(\n server.capabilities.resources,\n \"Resources\",\n server.name,\n \"resource\",\n current_line,\n server_config\n )\n vim.list_extend(lines, section_lines)\n for _, m in ipairs(mappings) do\n view:track_line(m.line, m.type, m.context)\n end\n table.insert(lines, Text.empty_line())\n current_line = new_line + 1\n end\n\n -- Resource Templates section if any\n if #server.capabilities.resourceTemplates > 0 then\n local section_lines, new_line, mappings = M.render_cap_section(\n server.capabilities.resourceTemplates,\n \"Resource Templates\",\n server.name,\n \"resourceTemplate\",\n current_line,\n server_config\n )\n vim.list_extend(lines, section_lines)\n for _, m in ipairs(mappings) do\n view:track_line(m.line, m.type, m.context)\n end\n table.insert(lines, Text.empty_line())\n current_line = new_line + 1\n end\n end\n\n return current_line\nend\n\n--- Render a server line\n---@param server table Server data\n---@return { line: NuiLine, mapping: table? }\nfunction M.render_server_line(server, active)\n local server_config = config_manager.get_server_config(server.name) or {}\n local is_enabled = server_config.disabled ~= true\n if server.is_native and not is_enabled then\n server.status = \"disabled\"\n end\n local status = M.get_server_status_info(server.status, active)\n local line = NuiLine()\n local hl = server.status == \"connected\" and Text.highlights.success or status.hl\n line:append(status.icon, status.hl)\n line:append(server.displayName or server.name, hl)\n if server.transportType == \"sse\" then\n line:append(\" \" .. (server.status == \"connected\" and Text.icons.sse or Text.icons.sse), hl)\n else\n end\n\n --INFO: when decoded from regualr mcp servers vim.NIL; for nativeservers we set nil, so check both\n -- Add error message for disconnected servers\n if server.error ~= vim.NIL and server.error ~= nil and server.status == \"disconnected\" and server.error ~= \"\" then\n -- Get first line of error message\n local error_lines = Text.multiline(server.error, Text.highlights.error)\n line:append(\" - \", Text.highlights.muted):append(error_lines[1], Text.highlights.error)\n end\n\n -- Add capabilities counts inline for connected servers\n if server.status == \"connected\" and server.capabilities then\n local custom_instructions = server_config.custom_instructions\n if custom_instructions and custom_instructions.text and custom_instructions.text ~= \"\" then\n local is_disabled = server_config.custom_instructions.disabled\n line:append(\n \" \" .. Text.icons.instructions .. \" \",\n is_disabled and Text.highlights.muted or Text.highlights.success\n )\n end\n -- Show auto-approve status for server using smart detection\n local all_tools = {}\n for _, tool in ipairs(server.capabilities.tools or {}) do\n table.insert(all_tools, tool.name)\n end\n\n local auto_approve = server_config.autoApprove\n local status = \"none\"\n local count = 0\n\n if auto_approve == true then\n status = \"all\"\n count = #all_tools\n elseif type(auto_approve) == \"table\" and vim.islist(auto_approve) then\n if #auto_approve == 0 then\n status = \"none\"\n count = 0\n elseif #auto_approve == #all_tools and #all_tools > 0 then\n status = \"all\"\n count = #all_tools\n else\n status = \"partial\"\n count = #auto_approve\n end\n end\n\n if status == \"all\" then\n -- All tools auto-approved\n line:append(\" \" .. Text.icons.auto .. \" \", Text.highlights.success)\n elseif status == \"partial\" then\n -- Partial auto-approval (show count)\n line:append(\" \" .. Text.icons.auto .. \" \" .. tostring(count) .. \" \", Text.highlights.warn)\n end\n\n -- Helper to render capability count with active/total\n local function render_capability_count(capabilities, disabled_list, id_field, icon, highlight)\n if capabilities and #capabilities > 0 then\n local current_ids = vim.tbl_map(function(cap)\n return cap[id_field]\n end, capabilities)\n local disabled = vim.tbl_filter(function(item)\n return vim.tbl_contains(current_ids, item)\n end, disabled_list or {})\n local enabled = #capabilities - #disabled\n\n line:append(icon, highlight):append(\n (\" \" .. tostring(enabled) .. (#disabled > 0 and \"/\" .. tostring(#capabilities) or \"\")),\n Text.highlights.muted\n )\n return true\n end\n end\n -- line:append(\" [\", Text.highlights.muted)\n\n -- if\n -- render_capability_count(\n -- server.capabilities.prompts,\n -- server_config.disabled_prompts,\n -- \"name\",\n -- Text.icons.prompt,\n -- Text.highlights.muted\n -- )\n -- then\n -- line:append(\" \")\n -- end\n -- render_capability_count(\n -- server.capabilities.tools,\n -- server_config.disabled_tools,\n -- \"name\",\n -- Text.icons.tool,\n -- Text.highlights.success\n -- )\n -- line:append(\" \")\n -- render_capability_count(\n -- server.capabilities.resources,\n -- server_config.disabled_resources,\n -- \"uri\",\n -- Text.icons.resource,\n -- Text.highlights.warning\n -- )\n -- line:append(\" \")\n -- render_capability_count(\n -- server.capabilities.resourceTemplates,\n -- server_config.disabled_resourceTemplates,\n -- \"uriTemplate\",\n -- Text.icons.resourceTemplate,\n -- Text.highlights.error\n -- )\n -- line:append(\"]\", Text.highlights.muted)\n end\n\n -- Add status description if any\n if status.desc ~= \"\" then\n line:append(status.desc, Text.highlights.muted)\n end\n\n return line\nend\n\n-- Format timestamp (could be Unix timestamp or ISO string)\nlocal function format_time(timestamp)\n -- For Unix timestamps\n return os.date(\"%H:%M:%S\", math.floor(timestamp / 1000))\nend\n\n--- Render error lines without header\n---@param error_type? string Optional error type to filter (setup/server/runtime)\n---@param detailed? boolean Whether to show full error details\n---@return NuiLine[] Lines\nfunction M.render_hub_errors(error_type, detailed)\n local lines = {}\n local errors = State:get_errors(error_type)\n if #errors > 0 then\n for _, err in ipairs(errors) do\n vim.list_extend(lines, M.render_error(err, detailed))\n end\n end\n return lines\nend\n\n--- Render server entry logs without header\n---@param entries table[] Array of log entries\n---@return NuiLine[] Lines\nfunction M.render_server_entries(entries)\n local lines = {}\n\n if #entries > 0 then\n for _, entry in ipairs(entries) do\n if entry.timestamp and entry.message then\n local line = NuiLine()\n -- Add timestamp\n line:append(string.format(\"[%s] \", format_time(entry.timestamp)), Text.highlights.muted)\n\n -- Add type icon and message\n line:append(\n (Text.icons[entry.type] or \"•\") .. \" \",\n Text.highlights[entry.type] or Text.highlights.muted\n )\n\n -- Add error code if present\n if entry.code then\n line:append(string.format(\"[Code: %s] \", entry.code), Text.highlights.muted)\n end\n\n -- Add main message\n line:append(entry.message, Text.highlights[entry.type] or Text.highlights.muted)\n\n table.insert(lines, Text.pad_line(line))\n end\n end\n end\n\n return lines\nend\n\nfunction M.render_error(err, detailed)\n local lines = {}\n -- Get appropriate icon based on error type\n local error_icon = ({\n SETUP = Text.icons.setup_error,\n SERVER = Text.icons.server_error,\n RUNTIME = Text.icons.runtime_error,\n })[err.type] or Text.icons.error\n\n -- Handle multiline error messages\n local message_lines = Text.multiline(err.message, Text.highlights.error)\n\n -- First line with icon and timestamp\n local first_line = NuiLine()\n first_line:append(error_icon .. \" \", Text.highlights.error)\n first_line:append(message_lines[1], Text.highlights.error)\n if err.timestamp then\n first_line:append(\" (\" .. utils.format_relative_time(err.timestamp) .. \")\", Text.highlights.muted)\n end\n table.insert(lines, Text.pad_line(first_line))\n\n -- Add remaining lines with proper indentation\n for i = 2, #message_lines do\n local line = NuiLine()\n line:append(message_lines[i], Text.highlights.error)\n table.insert(lines, Text.pad_line(line, nil, 4))\n end\n\n -- Add error details if detailed mode and details exist\n if detailed and err.details and next(err.details) then\n -- Convert details to string\n local detail_text = type(err.details) == \"string\" and err.details or vim.inspect(err.details)\n\n -- Add indented details\n local detail_lines = vim.tbl_map(function(l)\n return Text.pad_line(l, nil, 4)\n end, Text.multiline(detail_text, Text.highlights.muted))\n vim.list_extend(lines, detail_lines)\n table.insert(lines, Text.empty_line())\n end\n return lines\nend\n\n--- Get workspace state highlight based on current state\n---@param workspace_details table Workspace details from cache\n---@return string Highlight group name\nlocal function get_workspace_highlight(workspace_details)\n if workspace_details.state == \"shutting_down\" then\n return Text.highlights.warn\n elseif workspace_details.state == \"active\" then\n return Text.highlights.success\n else\n return Text.highlights.error\n end\nend\n\n--- Get workspace time display (uptime or countdown)\n---@param workspace_details table Workspace details\n---@return string, string Time text and icon\nlocal function get_workspace_time_info(workspace_details)\n if not workspace_details then\n return \"unknown\", Text.icons.clock\n end\n if\n workspace_details.state == \"shutting_down\"\n and workspace_details.shutdownStartedAt\n and workspace_details.shutdownDelay\n then\n -- Calculate remaining time\n local start_time = workspace_details.shutdownStartedAt\n local delay_ms = workspace_details.shutdownDelay\n local current_time = os.time() * 1000 -- Convert to milliseconds\n\n -- Parse ISO time to milliseconds\n local start_ms = 0\n if start_time then\n local year, month, day, hour, min, sec = start_time:match(\"(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)\")\n if year then\n local ok, secs = pcall(os.time, {\n ---@diagnostic disable-next-line: assign-type-mismatch\n year = tonumber(year),\n ---@diagnostic disable-next-line: assign-type-mismatch\n month = tonumber(month),\n ---@diagnostic disable-next-line: assign-type-mismatch\n day = tonumber(day),\n hour = tonumber(hour),\n min = tonumber(min),\n sec = tonumber(sec),\n })\n if ok then\n start_ms = secs * 1000 -- Convert to milliseconds\n else\n -- Fallback to current time if parsing fails\n start_ms = current_time\n end\n end\n end\n\n local elapsed = current_time - start_ms\n local remaining = math.max(0, delay_ms - elapsed)\n\n if remaining > 0 then\n local remaining_seconds = math.floor(remaining / 1000)\n local minutes = math.floor(remaining_seconds / 60)\n local seconds = remaining_seconds % 60\n return string.format(\"shutdown in %dm %ds\", minutes, seconds), Text.icons.hourglass\n else\n return \"closing...\", Text.icons.hourglass\n end\n else\n -- Show uptime\n if workspace_details.startTime then\n local uptime = utils.iso_to_relative_time(workspace_details.startTime) .. \" ago\"\n return uptime, Text.icons.clock\n end\n return \"unknown\", Text.icons.clock\n end\nend\n\n--- Render workspace line (collapsed view)\n---@param workspace_details MCPHub.WorkspaceDetails Workspace details from cache\n---@param port_str string Port as string (cache key)\n---@param is_current boolean Whether this is the current workspace\n---@param is_expanded boolean Whether this workspace is expanded\n---@return NuiLine\nfunction M.render_workspace_line(workspace_details, port_str, is_current, is_expanded)\n local line = NuiLine()\n local hl = get_workspace_highlight(workspace_details)\n\n -- Expansion indicator\n local expand_icon = is_expanded and Text.icons.triangleDown or Text.icons.triangleRight\n line:append(expand_icon .. \" \", hl)\n\n -- Folder icon and name\n local workspace_name = vim.fn.fnamemodify(workspace_details.cwd, \":t\") -- Get directory name\n if tostring(workspace_details.port) == tostring(State.config.port) then\n workspace_name = \"Global\"\n end\n line:append(Text.icons.folder .. \" \" .. workspace_name, hl)\n\n -- Current indicator\n if is_current then\n line:append(\" (current)\", Text.highlights.success)\n end\n\n -- Port\n line:append(\" | \" .. Text.icons.tower .. \" \" .. port_str, Text.highlights.muted)\n\n -- Client count\n local client_count = workspace_details.activeConnections or 0\n if client_count > 0 then\n line:append(\" | \" .. Text.icons.person .. \" \" .. tostring(client_count), Text.highlights.muted)\n end\n\n -- Time info\n local time_text, time_icon = get_workspace_time_info(workspace_details)\n line:append(\" | \" .. time_icon .. \" \" .. time_text, Text.highlights.muted)\n\n return line\nend\n\n--- Render workspace details (expanded view)\n---@param workspace_details MCPHub.WorkspaceDetails Workspace details from cache\n---@param current_line number Current line number\n---@return NuiLine[], number, table[] Lines new current line and line mappings\nfunction M.render_workspace_details(workspace_details, current_line)\n local lines = {}\n local mappings = {}\n\n -- Config files section\n if workspace_details.config_files and #workspace_details.config_files > 0 then\n table.insert(lines, Text.empty_line())\n current_line = current_line + 1\n\n table.insert(lines, Text.pad_line(NuiLine():append(\"Config Files Used:\", Text.highlights.muted), nil, 5))\n current_line = current_line + 1\n\n for _, config_file in ipairs(workspace_details.config_files) do\n local config_line = NuiLine()\n config_line:append(Text.icons.file .. \" \", Text.highlights.muted)\n\n config_line:append(config_file .. \" \", Text.highlights.info)\n\n table.insert(lines, Text.pad_line(config_line, nil, 6))\n current_line = current_line + 1\n end\n end\n\n -- Empty line for spacing\n table.insert(lines, Text.empty_line())\n current_line = current_line + 1\n\n -- Details section\n table.insert(lines, Text.pad_line(NuiLine():append(\"Details:\", Text.highlights.muted), nil, 5))\n current_line = current_line + 1\n\n -- Time info\n local time_text = get_workspace_time_info(workspace_details)\n -- State information\n local state_line = NuiLine()\n state_line:append(\"State: \", Text.highlights.muted)\n local state_text = workspace_details.state == \"shutting_down\" and (\"Hub will \" .. time_text) or \"Active\"\n local state_hl = workspace_details.state == \"shutting_down\" and Text.highlights.warn or Text.highlights.success\n state_line:append(state_text, state_hl)\n table.insert(lines, Text.pad_line(state_line, nil, 6))\n current_line = current_line + 1\n\n -- Clients connected\n if workspace_details.activeConnections then\n local clients_line = NuiLine()\n clients_line:append(\"Connected Clients: \", Text.highlights.muted)\n clients_line:append(tostring(workspace_details.activeConnections), Text.highlights.info)\n table.insert(lines, Text.pad_line(clients_line, nil, 6))\n current_line = current_line + 1\n end\n -- Path\n local path_line = NuiLine()\n path_line:append(\"CWD: \", Text.highlights.muted)\n path_line:append(workspace_details.cwd, Text.highlights.info)\n table.insert(lines, Text.pad_line(path_line, nil, 6))\n current_line = current_line + 1\n\n -- Process ID\n local pid_line = NuiLine()\n pid_line:append(\"Process ID: \", Text.highlights.muted)\n pid_line:append(tostring(workspace_details.pid), Text.highlights.info)\n table.insert(lines, Text.pad_line(pid_line, nil, 6))\n current_line = current_line + 1\n\n -- Started time\n if workspace_details.startTime then\n local started_line = NuiLine()\n started_line:append(\"Started: \", Text.highlights.muted)\n -- Format the ISO time nicely\n local start_time = workspace_details.startTime\n local formatted_time = utils.iso_to_relative_time(start_time) .. \" ago\"\n started_line:append(formatted_time, Text.highlights.info)\n table.insert(lines, Text.pad_line(started_line, nil, 6))\n current_line = current_line + 1\n end\n\n if workspace_details.shutdownDelay then\n local shutdown_line = NuiLine()\n shutdown_line:append(\"shutdown-delay: \", Text.highlights.muted)\n local formatted_time = utils.ms_to_relative_time(workspace_details.shutdownDelay)\n shutdown_line:append(formatted_time, Text.highlights.info)\n shutdown_line:append(\n string.format(\n \" (When 0 clients connected, will wait for %s for any new connections before shutting down)\",\n formatted_time\n ),\n Text.highlights.muted\n )\n table.insert(lines, Text.pad_line(shutdown_line, nil, 6))\n current_line = current_line + 1\n end\n table.insert(lines, Text.empty_line())\n current_line = current_line + 1\n\n return lines, current_line, mappings\nend\n\n--- Render all workspaces section\n---@param line_offset number Current line number\n---@param view MainView View instance for tracking interactions\n---@return NuiLine[] Lines for workspaces section\nfunction M.render_workspaces_section(line_offset, view)\n local lines = {}\n local current_line = line_offset\n\n -- Section header\n table.insert(lines, Text.pad_line(NuiLine():append(Text.icons.server .. \" Active Hubs\", Text.highlights.title)))\n current_line = current_line + 1\n\n local workspaces = State.server_state.workspaces\n if not workspaces or not workspaces.allActive or vim.tbl_isempty(workspaces.allActive) then\n table.insert(lines, Text.pad_line(NuiLine():append(\"No active workspaces\", Text.highlights.muted)))\n current_line = current_line + 1\n return lines\n end\n\n local current_port = workspaces.current\n\n -- Sort workspaces: current first, then by port number\n local ports = vim.tbl_keys(workspaces.allActive)\n table.sort(ports, function(a, b)\n if a == current_port then\n return true\n elseif b == current_port then\n return false\n else\n return (tonumber(a) or 0) < (tonumber(b) or 0)\n end\n end)\n\n for _, port_str in ipairs(ports) do\n local workspace_details = workspaces.allActive[port_str]\n local is_current = port_str == current_port\n local is_expanded = view.expanded_workspace == port_str\n\n -- Render workspace line\n local workspace_line = M.render_workspace_line(workspace_details, port_str, is_current, is_expanded)\n table.insert(lines, Text.pad_line(workspace_line, nil, 3))\n current_line = current_line + 1\n\n -- Track line for interaction\n local base_hint = is_expanded and \"[ Collapse\" or \"[ Expand\"\n local action_hint = \", Kill\"\n local change_dir_hint = is_current and \"\" or \", Change Dir\"\n local full_hint = base_hint .. action_hint .. change_dir_hint .. \"]\"\n\n view:track_line(current_line, \"workspace\", {\n port = port_str,\n workspace_details = workspace_details,\n is_current = is_current,\n hint = full_hint,\n })\n\n -- Render expanded details if this workspace is expanded\n if is_expanded then\n local detail_lines, new_line, mappings = M.render_workspace_details(workspace_details, current_line)\n vim.list_extend(lines, detail_lines)\n current_line = new_line\n\n -- Track any interactive lines from details (for future actions)\n for _, mapping in ipairs(mappings) do\n view:track_line(mapping.line, mapping.type, mapping.context)\n end\n end\n end\n\n return lines\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/extensions/codecompanion/tools.lua", "local M = {}\nlocal core = require(\"mcphub.extensions.codecompanion.core\")\n\nlocal mcphub = require(\"mcphub\")\n\n--- Utility functions for naming\n---@param name string\n---@return string\nlocal function make_safe_name(name)\n name = name:gsub(\"[^%w_]\", \"_\")\n return name\nend\n\n---@param server_name string Name of the MCP server\n---@param tool_name string Tool name\n---@return string\nlocal function create_namespaced_tool_name(server_name, tool_name)\n local safe_server_name = make_safe_name(server_name)\n local safe_tool_name = make_safe_name(tool_name)\n return safe_server_name .. \"__\" .. safe_tool_name\nend\n\n--- Create handler for static tools (use_mcp_tool, access_mcp_resource)\n---@param action_name MCPHub.ActionType\n---@param has_function_calling boolean\n---@param opts MCPHub.Extensions.CodeCompanionConfig\nlocal function create_static_handler(action_name, has_function_calling, opts)\n ---@param agent CodeCompanion.Agent The Editor tool\n ---@param args MCPHub.ToolCallArgs | MCPHub.ResourceAccessArgs The arguments from the LLM's tool call\n ---@param output_handler function Callback for asynchronous calls\n ---@return nil|{ status: \"success\"|\"error\", data: string }\n return function(agent, args, _, output_handler)\n local context = {\n tool_display_name = action_name,\n is_individual_tool = false,\n action = action_name,\n }\n core.execute_mcp_tool(args, agent, output_handler, context)\n end\nend\n\n---@class MCPHub.ToolCallContext\n---@field tool_display_name string\n---@field is_individual_tool boolean\n---@field action MCPHub.ActionType\n\n--- Create handler for individual tools\n---@param server_name string MCP Server name\n---@param tool_name string Tool name on the server\n---@param namespaced_name string Namespaced tool name (safe_server_name__safe_tool_name)\n---@return function\nlocal function create_individual_tool_handler(server_name, tool_name, namespaced_name)\n ---@param agent CodeCompanion.Agent The Editor tool\n ---@param args MCPHub.ToolCallArgs\n ---@param output_handler function Callback for asynchronous calls\n return function(agent, args, _, output_handler)\n local params = {\n server_name = server_name,\n tool_name = tool_name,\n tool_input = args,\n }\n ---@type MCPHub.ToolCallContext\n local context = {\n tool_display_name = namespaced_name,\n is_individual_tool = true,\n action = \"use_mcp_tool\",\n }\n core.execute_mcp_tool(params, agent, output_handler, context)\n end\nend\n\n-- Static tool schemas\nlocal tool_schemas = {\n access_mcp_resource = {\n type = \"function\",\n [\"function\"] = {\n name = \"access_mcp_resource\",\n description = \"get resources on MCP servers.\",\n parameters = {\n type = \"object\",\n properties = {\n server_name = {\n description = \"Name of the server to call the resource on. Must be from one of the available servers.\",\n type = \"string\",\n },\n uri = {\n description = \"URI of the resource to access.\",\n type = \"string\",\n },\n },\n required = { \"server_name\", \"uri\" },\n additionalProperties = false,\n },\n strict = true,\n },\n },\n use_mcp_tool = {\n type = \"function\",\n [\"function\"] = {\n name = \"use_mcp_tool\",\n description = \"calls tools on MCP servers.\",\n parameters = {\n type = \"object\",\n properties = {\n server_name = {\n description = \"Name of the server to call the tool on. Must be from one of the available servers.\",\n type = \"string\",\n },\n tool_name = {\n description = \"Name of the tool to call.\",\n type = \"string\",\n },\n tool_input = {\n description = \"Input object for the tool call\",\n type = \"object\",\n },\n },\n required = { \"server_name\", \"tool_name\", \"tool_input\" },\n additionalProperties = false,\n },\n strict = false,\n },\n },\n}\n\n--- Create static MCP tools\n---@param opts MCPHub.Extensions.CodeCompanionConfig\n---@return {groups: table, [MCPHub.ActionType]: table}\nfunction M.create_static_tools(opts)\n local codecompanion = require(\"codecompanion\")\n local has_function_calling = codecompanion.has(\"function-calling\") --[[@as boolean]]\n\n local tools = {\n groups = {\n mcp = {\n id = \"mcp_static:mcp\",\n description = \" Call tools and resources from MCP servers with:\\n\\n - `use_mcp_tool`\\n - `access_mcp_resource`\\n\",\n hide_in_help_window = false,\n system_prompt = function(_)\n local hub = require(\"mcphub\").get_hub_instance()\n if not hub then\n vim.notify(\"MCP Hub is not initialized\", vim.log.levels.WARN)\n return \"\"\n end\n if not hub:is_ready() then\n vim.notify(\"MCP Hub is not ready yet\", vim.log.levels.WARN)\n return \"\"\n end\n local prompt = \"\"\n if not has_function_calling then\n local xml_tool = require(\"mcphub.extensions.codecompanion.xml_tool\")\n prompt = xml_tool.system_prompt(hub)\n end\n prompt = prompt .. hub:get_active_servers_prompt()\n return prompt\n end,\n tools = {},\n opts = {\n collapse_tools = true,\n },\n },\n },\n }\n\n for action_name, schema in pairs(tool_schemas) do\n tools[action_name] = {\n id = \"mcp_static:\" .. action_name,\n description = schema[\"function\"].description,\n hide_in_help_window = true,\n visible = false,\n ---@class MCPHub.Extensions.CodeCompanionTool: CodeCompanion.Agent.Tool\n callback = {\n name = action_name,\n cmds = { create_static_handler(action_name, has_function_calling, opts) },\n system_prompt = function()\n return string.format(\"You can use the %s tool to %s\\n\", action_name, schema[\"function\"].description)\n end,\n output = core.create_output_handlers(action_name, has_function_calling, opts),\n schema = schema,\n },\n }\n table.insert(tools.groups.mcp.tools, action_name)\n end\n\n return tools\nend\n\n-- Cleanup dynamic tools and groups\nlocal function cleanup_dynamic_items(config)\n local tools = config.strategies.chat.tools\n local groups = tools.groups or {}\n\n -- Clean up existing MCP dynamic tools\n for key, value in pairs(tools) do\n local id = value.id or \"\"\n if id:sub(1, 11) == \"mcp_dynamic\" then\n tools[key] = nil\n end\n end\n\n -- Clean up existing MCP dynamic tool groups\n for key, value in pairs(groups) do\n local id = value.id or \"\"\n if id:sub(1, 11) == \"mcp_dynamic\" then\n groups[key] = nil\n end\n end\nend\n\n---@param opts MCPHub.Extensions.CodeCompanionConfig\nfunction M.register(opts)\n local hub = mcphub.get_hub_instance()\n if not hub then\n return\n end\n\n local ok, config = pcall(require, \"codecompanion.config\")\n if not ok then\n return\n end\n\n -- Cleanup existing dynamic items\n cleanup_dynamic_items(config)\n\n local tools = config.strategies.chat.tools\n local groups = tools.groups or {}\n\n -- Get servers and process in one go\n local servers = hub:get_servers()\n local server_tools = {} -- Map safe_server_name -> {tool_names, server_name}\n local used_safe_names = {}\n local skipped_tools = {}\n local skipped_groups = {}\n\n -- Process servers: create unique safe names and individual tools\n for _, server in ipairs(servers) do\n local safe_name = make_safe_name(server.name)\n local counter = 1\n local original_safe_name = safe_name\n\n -- Ensure unique safe name\n while used_safe_names[safe_name] do\n safe_name = original_safe_name .. \"_\" .. counter\n counter = counter + 1\n end\n\n used_safe_names[safe_name] = true\n\n if opts.add_mcp_prefix_to_tool_names then\n safe_name = \"mcp__\" .. safe_name\n end\n -- Check if this safe_name conflicts with existing group\n if groups[safe_name] then\n table.insert(skipped_groups, safe_name)\n -- Skip this entire server to avoid confusing individual tools\n goto continue\n end\n\n server_tools[safe_name] = { tool_names = {}, server_name = server.name }\n\n -- Create individual tools for this server\n if server.capabilities and server.capabilities.tools then\n for _, tool in ipairs(server.capabilities.tools) do\n local tool_name = tool.name\n local namespaced_tool_name = create_namespaced_tool_name(safe_name, tool_name)\n -- Check for tool name conflicts (after cleanup, no mcp_dynamic should exist)\n if tools[namespaced_tool_name] then\n table.insert(skipped_tools, namespaced_tool_name)\n else\n -- Track for server group\n table.insert(server_tools[safe_name].tool_names, namespaced_tool_name)\n\n -- Add individual tool\n tools[namespaced_tool_name] = {\n id = \"mcp_dynamic:\" .. safe_name .. \":\" .. tool_name,\n description = tool.description,\n hide_in_help_window = true,\n visible = opts.show_server_tools_in_chat == true,\n callback = {\n name = namespaced_tool_name,\n cmds = { create_individual_tool_handler(server.name, tool_name, namespaced_tool_name) },\n output = core.create_output_handlers(namespaced_tool_name, true, opts),\n schema = {\n type = \"function\",\n [\"function\"] = {\n name = namespaced_tool_name,\n description = tool.description,\n parameters = tool.inputSchema,\n },\n },\n },\n }\n end\n end\n end\n\n ::continue::\n end\n\n -- Create server groups\n local prompt_utils = require(\"mcphub.utils.prompt\")\n for safe_server_name, server_data in pairs(server_tools) do\n local tool_names = server_data.tool_names\n local server_name = server_data.server_name\n\n -- Only create group if it has tools and no conflict\n if #tool_names > 0 then\n if groups[safe_server_name] then\n table.insert(skipped_groups, safe_server_name)\n else\n local custom_instructions = prompt_utils.format_custom_instructions(\n server_name,\n \"\\n\\n### Instructions for \" .. safe_server_name .. \" tools\\n\\n\"\n )\n\n groups[safe_server_name] = {\n id = \"mcp_dynamic:\" .. safe_server_name,\n hide_in_help_window = true,\n description = string.format(\n \" All tools from `%s` MCP server: \\n\\n%s\",\n server_name,\n table.concat(\n vim.tbl_map(function(t)\n return \" - `\" .. t .. \"` \"\n end, tool_names),\n \"\\n\"\n )\n ),\n tools = tool_names,\n system_prompt = function(self)\n if custom_instructions and custom_instructions ~= \"\" then\n return custom_instructions\n end\n end,\n opts = {\n collapse_tools = true,\n },\n }\n end\n end\n end\n\n -- Silent warnings for conflicts\n if #skipped_tools > 0 then\n vim.notify(\n string.format(\n \"Skipped adding %d tool(s) to codecompanion due to name conflicts: %s\",\n #skipped_tools,\n table.concat(skipped_tools, \", \")\n ),\n vim.log.levels.WARN,\n { title = \"MCPHub\" }\n )\n end\n\n if #skipped_groups > 0 then\n vim.notify(\n string.format(\n \"Skipped adding %d server group(s) to codecompanion due to name conflicts: %s\",\n #skipped_groups,\n table.concat(skipped_groups, \", \")\n ),\n vim.log.levels.WARN,\n { title = \"MCPHub\" }\n )\n end\n\n -- Update syntax highlighting\n M.update_syntax_highlighting(server_tools)\nend\n\n--- Setup dynamic tools (individual tools + server groups)\n---@param opts MCPHub.Extensions.CodeCompanionConfig\nfunction M.setup_dynamic_tools(opts)\n if not opts.make_tools then\n return\n end\n vim.schedule(function()\n M.register(opts)\n end)\n mcphub.on(\n { \"servers_updated\", \"tool_list_changed\" },\n vim.schedule_wrap(function()\n M.register(opts)\n end)\n )\nend\n\n-- Update syntax highlighting for new tools\nfunction M.update_syntax_highlighting(server_tools)\n vim.schedule(function()\n for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do\n if vim.api.nvim_buf_is_valid(bufnr) and vim.bo[bufnr].filetype == \"codecompanion\" then\n vim.api.nvim_buf_call(bufnr, function()\n for safe_server_name, server_data in pairs(server_tools) do\n local tool_names = server_data.tool_names\n vim.cmd.syntax('match CodeCompanionChatToolGroup \"@{' .. safe_server_name .. '}\"')\n vim.iter(tool_names):each(function(name)\n vim.cmd.syntax('match CodeCompanionChatTool \"@{' .. name .. '}\"')\n end)\n end\n end)\n end\n end\n end)\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/extensions/shared.lua", "local M = {}\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal native = require(\"mcphub.native\")\nlocal ui_utils = require(\"mcphub.utils.ui\")\nlocal utils = require(\"mcphub.utils\")\n\n---@class MCPHub.ParsedParams\n---@field errors string[] List of errors encountered during parsing\n---@field action MCPHub.ActionType Action type, either \"use_mcp_tool\" or \"access_mcp_resource\"\n---@field server_name string Name of the server to call the tool/resource on\n---@field tool_name string Name of the tool to call (nil for resources)\n---@field arguments table Input arguments for the tool call (empty table for resources)\n---@field uri string URI of the resource to access (nil for tools)\n---@field is_auto_approved_in_server boolean Whether the tool autoApproved in the servers.json\n---@field needs_confirmation_window boolean Whether the tool call needs a confirmation window\n\n---@class MCPHub.ToolCallArgs\n---@field server_name string Name of the server to call the tool on.\n---@field tool_name string Name of the tool to call.\n---@field tool_input table | string Input for the tool call. Must be an object for `use_mcp_tool` action.\n\n---@class MCPHub.ResourceAccessArgs\n---@field server_name string Name of the server to call the resource on.\n---@field uri string URI of the resource to access.\n\n---@param server_name string Name of the server to check\n---@param tool_name string Name of the tool to check\n---@return boolean Whether the tool is auto-approved in the server\nfunction M.is_auto_approved_in_server(server_name, tool_name)\n local config_manager = require(\"mcphub.utils.config_manager\")\n local server_config = config_manager.get_server_config(server_name) or {}\n local auto_approve = server_config.autoApprove\n if not auto_approve then\n return false\n end\n -- If autoApprove is true, approve everything for this server\n if auto_approve == true then\n return true\n end\n -- If autoApprove is an array, check if tool is in the list\n if type(auto_approve) == \"table\" and vim.islist(auto_approve) then\n return vim.tbl_contains(auto_approve, tool_name)\n end\n return false\nend\n\n---@param params MCPHub.ToolCallArgs | MCPHub.ResourceAccessArgs\n---@param action_name MCPHub.ActionType\n---@return MCPHub.ParsedParams\nfunction M.parse_params(params, action_name)\n params = params or {}\n\n local server_name = params.server_name\n local tool_name = params.tool_name\n local uri = params.uri\n local arguments = params.tool_input or {}\n if type(arguments) == \"string\" then\n local json_ok, decode_result = utils.json_decode(arguments or \"{}\")\n if json_ok then\n arguments = decode_result or {}\n else\n arguments = {}\n end\n end\n local errors = {}\n if not vim.tbl_contains({ \"use_mcp_tool\", \"access_mcp_resource\" }, action_name) then\n table.insert(errors, \"Action must be one of `use_mcp_tool` or `access_mcp_resource`\")\n end\n if not server_name then\n table.insert(errors, \"server_name is required\")\n end\n if action_name == \"use_mcp_tool\" and not tool_name then\n table.insert(errors, \"tool_name is required\")\n end\n if action_name == \"use_mcp_tool\" and type(arguments) ~= \"table\" then\n table.insert(errors, \"tool_input must be an object\")\n end\n\n if action_name == \"access_mcp_resource\" and not uri then\n table.insert(errors, \"uri is required\")\n end\n\n return {\n errors = errors,\n action = action_name or \"nil\",\n server_name = server_name or \"nil\",\n tool_name = tool_name or \"nil\",\n arguments = arguments or {},\n uri = uri or \"nil\",\n needs_confirmation_window = M.needs_confirmation_window(server_name, tool_name),\n is_auto_approved_in_server = M.is_auto_approved_in_server(server_name, tool_name),\n }\nend\n\n--- For some built-in tools, we already show interactive diffs, before confirmation.\n---@param server_name string Name of the server\n---@param tool_name string Name of the tool to check\nfunction M.needs_confirmation_window(server_name, tool_name)\n local server = native.is_native_server(server_name)\n if not server then\n return true\n end\n for _, tool in ipairs(server.capabilities.tools) do\n if tool.name == tool_name and tool.needs_confirmation_window == false then\n return false\n end\n end\n return true\nend\n---@param arguments MCPPromptArgument[]\n---@param callback fun(values: string[])\nfunction M.collect_arguments(arguments, callback)\n local values = {}\n local should_proceed = true\n\n local function collect_input(index)\n if index > #arguments and should_proceed then\n callback(values)\n return\n end\n\n local arg = arguments[index]\n local title = string.format(\"%s %s\", arg.name, arg.required and \"(required)\" or \"\")\n local default = arg.default or \"\"\n\n local function submit_input(input)\n if arg.required and (input == nil or input == \"\") then\n vim.notify(\"Value for \" .. arg.name .. \" is required\", vim.log.levels.ERROR)\n should_proceed = false\n return\n end\n\n values[arg.name] = input\n collect_input(index + 1)\n end\n\n local function cancel_input()\n if arg.required then\n vim.notify(\"Value for \" .. arg.name .. \" is required\", vim.log.levels.ERROR)\n should_proceed = false\n return\n end\n values[arg.name] = nil\n collect_input(index + 1)\n end\n ui_utils.multiline_input(title, default, submit_input, { on_cancel = cancel_input })\n end\n\n if #arguments > 0 then\n vim.defer_fn(function()\n collect_input(1)\n end, 0)\n else\n callback(values)\n end\nend\n\n---Create the confirmation prompt for mcp tool\n---@param params MCPHub.ParsedParams\n---@return string\nfunction M.get_mcp_tool_prompt(params)\n local action_name = params.action\n local server_name = params.server_name\n local tool_name = params.tool_name\n local uri = params.uri\n local arguments = params.arguments or {}\n\n local args = \"\"\n for k, v in pairs(arguments) do\n args = args .. k .. \":\\n \"\n if type(v) == \"string\" then\n local lines = vim.split(v, \"\\n\")\n for _, line in ipairs(lines) do\n args = args .. line .. \"\\n\"\n end\n else\n args = args .. vim.inspect(v) .. \"\\n\"\n end\n end\n local msg = \"\"\n if action_name == \"use_mcp_tool\" then\n msg = string.format(\n [[Do you want to run the `%s` tool on the `%s` mcp server with arguments:\n%s]],\n tool_name,\n server_name,\n args\n )\n elseif action_name == \"access_mcp_resource\" then\n msg = string.format(\"Do you want to access the resource `%s` on the `%s` server?\", uri, server_name)\n end\n return msg\nend\n\n---@param params MCPHub.ParsedParams\n---@return boolean confirmed\n---@return boolean cancelled\nfunction M.show_mcp_tool_prompt(params)\n local action_name = params.action\n local server_name = params.server_name\n local tool_name = params.tool_name\n local uri = params.uri\n local arguments = params.arguments or {}\n\n local lines = {}\n local is_tool = action_name == \"use_mcp_tool\"\n\n -- Header as a question\n local header_line = NuiLine()\n header_line:append(Text.icons.event, Text.highlights.warn)\n header_line:append(\" Do you want to \", Text.highlights.text)\n if is_tool then\n header_line:append(\"call \", Text.highlights.text)\n header_line:append(tool_name, Text.highlights.warn_italic)\n else\n header_line:append(\"access \", Text.highlights.text)\n header_line:append(uri, Text.highlights.link)\n end\n header_line:append(\" on \", Text.highlights.text)\n header_line:append(server_name, Text.highlights.success_italic)\n header_line:append(\"?\", Text.highlights.text)\n table.insert(lines, header_line)\n\n -- Parameters section\n if is_tool and next(arguments) then\n table.insert(lines, NuiLine():append(\"\"))\n\n for key, value in pairs(arguments) do\n -- Parameter name\n local param_name_line = NuiLine()\n param_name_line:append(Text.icons.param, Text.highlights.info)\n param_name_line:append(\" \" .. key .. \":\", Text.highlights.json_property)\n table.insert(lines, param_name_line)\n\n -- Parameter value\n local function add_value_lines(val)\n if type(val) == \"string\" then\n local value_lines = val:find(\"\\n\") and vim.split(val, \"\\n\", { plain = true })\n or { '\"' .. val .. '\"' }\n for _, line in ipairs(value_lines) do\n local value_line = NuiLine()\n value_line:append(\" \" .. line, Text.highlights.json_string)\n table.insert(lines, value_line)\n end\n elseif type(val) == \"boolean\" then\n local value_line = NuiLine()\n value_line:append(\" \" .. tostring(val), Text.highlights.json_boolean)\n table.insert(lines, value_line)\n elseif type(val) == \"number\" then\n local value_line = NuiLine()\n value_line:append(\" \" .. tostring(val), Text.highlights.json_number)\n table.insert(lines, value_line)\n else\n for _, line in ipairs(vim.split(vim.inspect(val), \"\\n\", { plain = true })) do\n local value_line = NuiLine()\n value_line:append(\" \" .. line, Text.highlights.muted)\n table.insert(lines, value_line)\n end\n end\n end\n\n add_value_lines(value)\n table.insert(lines, NuiLine():append(\"\"))\n end\n end\n\n return require(\"mcphub.utils.ui\").confirm(lines, {\n min_width = 70,\n max_width = 100,\n })\nend\n\n---@param parsed_params MCPHub.ParsedParams\n---@return {error?:string, approve:boolean}\nfunction M.handle_auto_approval_decision(parsed_params)\n local auto_approve = State.config.auto_approve or false\n local status = { approve = false, error = nil }\n --- If user has a custom function that decides whether to auto-approve\n --- call that with params + saved autoApprove state as is_auto_approved_in_server field\n if type(auto_approve) == \"function\" then\n local ok, res = pcall(auto_approve, parsed_params)\n if not ok or type(res) == \"string\" then\n --- If auto_approve function throws an error, or returns a string, treat it as an error\n status = { approve = false, error = res }\n elseif type(res) == \"boolean\" then\n --- If auto_approve function returns a boolean, use that as the decision\n status = { approve = res, error = nil }\n end\n elseif type(auto_approve) == \"boolean\" then\n status = { approve = auto_approve, error = nil }\n end\n\n -- Check if auto-approval is enabled in servers.json\n if parsed_params.is_auto_approved_in_server then\n status = { approve = true, error = nil }\n end\n\n if status.error then\n return { error = status.error or \"Something went wrong with auto-approval\", approve = false }\n end\n\n if status.approve == false and parsed_params.needs_confirmation_window then\n local confirmed, _ = M.show_mcp_tool_prompt(parsed_params)\n return { error = not confirmed and \"User cancelled the operation\", approve = confirmed }\n end\n return status\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/utils/init.lua", "local NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal config = require(\"mcphub.config\")\nlocal ui_utils = require(\"mcphub.utils.ui\")\nlocal validation = require(\"mcphub.utils.validation\")\n\nlocal M = {}\n\n--- Clean command arguments by filtering out empty strings and nil values.\n--- This is particularly useful when handling command arguments that may contain optional values.\n--- @param args table Array of command arguments\n--- @return table Cleaned array with only valid arguments\nfunction M.clean_args(args)\n return vim.iter(args or {})\n :flatten()\n :filter(function(arg)\n return arg ~= \"\" and arg ~= nil\n end)\n :totable()\nend\n\nlocal uid = 0\nfunction M.gen_dump_path()\n uid = uid + 1\n local P = require(\"plenary.path\")\n local path\n local id = string.gsub(\"xxxx4xxx\", \"[xy]\", function(l)\n local v = (l == \"x\") and math.random(0, 0xf) or math.random(0, 0xb)\n return string.format(\"%x\", v)\n end)\n if P.path.sep == \"\\\\\" then\n path = string.format(\"%s\\\\AppData\\\\Local\\\\Temp\\\\plenary_curl_%s.headers\", os.getenv(\"USERPROFILE\"), id)\n else\n local temp_dir = os.getenv(\"XDG_RUNTIME_DIR\") or \"/tmp\"\n path = temp_dir .. \"/plenary_curl_\" .. id .. \".headers\"\n end\n local nvim_pid = vim.uv.os_getpid()\n local dump_file = path .. nvim_pid .. uid\n return { \"-D\", dump_file .. \".headers\" }\nend\n\n--- Format timestamp relative to now\n---@param timestamp number Unix timestamp\n---@return string\nfunction M.format_relative_time(timestamp)\n local now = vim.loop.now()\n local diff = math.floor(now - timestamp)\n\n if diff < 1000 then -- Less than a second\n return \"just now\"\n elseif diff < 60000 then -- Less than a minute\n local seconds = math.floor(diff / 1000)\n return string.format(\"%ds\", seconds)\n elseif diff < 3600000 then -- Less than an hour\n local minutes = math.floor(diff / 60000)\n local seconds = math.floor((diff % 60000) / 1000)\n return string.format(\"%dm %ds\", minutes, seconds)\n elseif diff < 86400000 then -- Less than a day\n local hours = math.floor(diff / 3600000)\n local minutes = math.floor((diff % 3600000) / 60000)\n return string.format(\"%dh %dm\", hours, minutes)\n else -- Days\n local days = math.floor(diff / 86400000)\n local hours = math.floor((diff % 86400000) / 3600000)\n return string.format(\"%dd %dh\", days, hours)\n end\nend\n\n--- Format duration in seconds to human readable string\n---@param seconds number Duration in seconds\n---@return string Formatted duration\nfunction M.format_uptime(seconds)\n if seconds < 60 then\n return string.format(\"%ds\", seconds)\n elseif seconds < 3600 then\n return string.format(\"%dm %ds\", math.floor(seconds / 60), seconds % 60)\n else\n local hours = math.floor(seconds / 3600)\n local mins = math.floor((seconds % 3600) / 60)\n return string.format(\"%dh %dm\", hours, mins)\n end\nend\n\n--- Calculate the approximate number of tokens in a text string\n--- This is a simple approximation using word count, which works reasonably well for most cases\n---@param text string The text to count tokens from\n---@return number approx_tokens The approximate number of tokens\nfunction M.calculate_tokens(text)\n if not text or text == \"\" then\n return 0\n end\n\n -- Simple tokenization approximation (4 chars ≈ 1 token)\n local char_count = #text\n local approx_tokens = math.ceil(char_count / 4)\n\n -- Alternative method using word count\n -- local words = {}\n -- for word in text:gmatch(\"%S+\") do\n -- table.insert(words, word)\n -- end\n -- local word_count = #words\n -- local approx_tokens = math.ceil(word_count * 1.3) -- Words + punctuation overhead\n\n return approx_tokens\nend\n\n--- Format token count for display\n---@param count number The token count\n---@return string formatted The formatted token count\nfunction M.format_token_count(count)\n if count < 1000 then\n return tostring(count)\n elseif count < 1000000 then\n return string.format(\"%.1fk\", count / 1000)\n else\n return string.format(\"%.1fM\", count / 1000000)\n end\nend\n\n--- Fire an autocommand event with data\n---@param name string The event name (without \"User\" prefix)\n---@param data? table Optional data to pass to the event\nfunction M.fire(name, data)\n vim.api.nvim_exec_autocmds(\"User\", {\n pattern = name,\n data = data,\n })\nend\n\n--- Sort table keys recursively while preserving arrays\n---@param tbl table The table to sort\n---@return table sorted_tbl The sorted table\nlocal function sort_keys_recursive(tbl)\n if type(tbl) ~= \"table\" then\n return tbl\n end\n\n -- Check if table is an array\n local is_array = true\n local max_index = 0\n for k, _ in pairs(tbl) do\n if type(k) ~= \"number\" then\n is_array = false\n break\n end\n max_index = math.max(max_index, k)\n end\n if is_array and max_index == #tbl then\n -- Process array values but preserve order\n local result = {}\n for i, v in ipairs(tbl) do\n result[i] = sort_keys_recursive(v)\n end\n return result\n end\n\n -- Sort object keys alphabetically (case-insensitive)\n local sorted = {}\n local keys = {}\n\n for k in pairs(tbl) do\n table.insert(keys, k)\n end\n table.sort(keys)\n for _, k in ipairs(keys) do\n sorted[k] = sort_keys_recursive(tbl[k])\n end\n return sorted\nend\n\nlocal _is_jq_available\nlocal function is_jq_available()\n if _is_jq_available ~= nil then\n return _is_jq_available\n end\n _is_jq_available = vim.fn.executable(\"jq\") == 1\n return _is_jq_available\nend\n\n--- Pretty print JSON string with optional unescaping of forward slashes\n---@param str string JSON string to format\n---@param opts? { unescape_slashes?: boolean, use_jq?: boolean, sort_keys?: boolean } Optional options\n---@return string Formatted JSON string\nfunction M.pretty_json(str, opts)\n opts = opts or {}\n\n if opts.use_jq and is_jq_available() then\n local jq_cmd = { \"jq\" }\n if opts.sort_keys ~= false then\n vim.list_extend(jq_cmd, { \"--sort-keys\", \".\" })\n end\n local formatted = vim.fn.system(jq_cmd, str)\n if vim.v.shell_error ~= 0 or not formatted or formatted == \"\" then\n return M.format_json_string(str, opts.unescape_slashes)\n end\n if opts.unescape_slashes == nil or opts.unescape_slashes then\n formatted = formatted:gsub(\"\\\\/\", \"/\")\n end\n return formatted\n else\n -- Fallback to custom implementation\n local ok, parsed = M.json_decode(str)\n if not ok then\n vim.notify(\"Failed to parse JSON string\", vim.log.levels.INFO)\n return M.format_json_string(str, opts.unescape_slashes)\n end\n local sorted = opts.sort_keys ~= false and sort_keys_recursive(parsed) or parsed\n local encoded = vim.json.encode(sorted)\n return M.format_json_string(encoded, opts.unescape_slashes)\n end\nend\n\n--- Format a JSON string with proper indentation\n---@param str string JSON string to format\n---@return string Formatted JSON string\nfunction M.format_json_string(str, unescape_slashes)\n local level = 0\n local result = \"\"\n local in_quotes = false\n local escape_next = false\n local indent = \" \"\n -- Default to true if not specified\n if unescape_slashes == nil then\n unescape_slashes = true\n end\n\n -- Pre-process to unescape forward slashes if requested\n if unescape_slashes then\n str = str:gsub(\"\\\\/\", \"/\")\n end\n\n for i = 1, #str do\n local char = str:sub(i, i)\n\n -- Handle escape sequences properly\n if escape_next then\n escape_next = false\n result = result .. char\n elseif char == \"\\\\\" then\n escape_next = true\n result = result .. char\n elseif char == '\"' then\n in_quotes = not in_quotes\n result = result .. char\n elseif not in_quotes then\n if char == \"{\" or char == \"[\" then\n level = level + 1\n result = result .. char .. \"\\n\" .. string.rep(indent, level)\n elseif char == \"}\" or char == \"]\" then\n level = level - 1\n result = result .. \"\\n\" .. string.rep(indent, level) .. char\n elseif char == \",\" then\n result = result .. char .. \"\\n\" .. string.rep(indent, level)\n elseif char == \":\" then\n -- Add space after colons for readability\n result = result .. \": \"\n elseif char == \" \" or char == \"\\n\" or char == \"\\t\" then\n -- Skip whitespace in non-quoted sections\n -- (vim.json.encode already adds its own whitespace)\n else\n result = result .. char\n end\n else\n -- In quotes, preserve all characters\n result = result .. char\n end\n end\n return result\nend\n\nfunction M.is_windows()\n return vim.fn.has(\"win32\") == 1 or vim.fn.has(\"win64\") == 1\nend\n\n---@param config MCPHub.Config\n---@return { cmd: string, cmdArgs: string[] }\nfunction M.get_default_cmds(config)\n local cmd, cmdArgs\n local bin_name = nil\n if config.use_bundled_binary then\n bin_name = M.get_bundled_mcp_path()\n else\n if M.is_windows() then\n bin_name = \"mcp-hub.cmd\"\n else\n bin_name = \"mcp-hub\"\n end\n end\n -- set default cmds\n if config.cmd == nil and config.cmdArgs == nil then\n if M.is_windows() then\n cmd = \"cmd.exe\"\n cmdArgs = {\n \"/C\",\n bin_name,\n }\n else\n cmd = bin_name\n cmdArgs = {}\n end\n else\n cmd = config.cmd or bin_name\n cmdArgs = config.cmdArgs or {}\n end\n return {\n cmd = cmd,\n cmdArgs = cmdArgs,\n }\nend\n\n--- Get path to bundled mcp-hub executable when build = \"bundled_build.lua\"\n---@return string Path to mcp-hub executable in bundled directory\nfunction M.get_bundled_mcp_path()\n local plugin_root = vim.fn.fnamemodify(debug.getinfo(1, \"S\").source:sub(2), \":h:h:h:h\")\n local base_path = plugin_root .. \"/bundled/mcp-hub/node_modules/.bin/mcp-hub\"\n if M.is_windows() then\n return base_path .. \".cmd\"\n end\n return base_path\nend\n\nfunction M.safe_get(tbl, path)\n -- Handle nil input\n if tbl == nil then\n return nil\n end\n\n -- Split path by dots\n local parts = {}\n for part in path:gmatch(\"[^.]+\") do\n parts[#parts + 1] = part\n end\n\n local current = tbl\n for _, key in ipairs(parts) do\n -- Convert string numbers to numeric indices\n if tonumber(key) then\n key = tonumber(key)\n end\n\n if type(current) ~= \"table\" then\n return nil\n end\n current = current[key]\n if current == nil then\n return nil\n end\n end\n\n return current\nend\n\nfunction M.parse_context(caller)\n local bufnr = nil\n local context = {}\n local type = caller.type\n local meta = caller.meta or {}\n if type == \"codecompanion\" then\n local is_within_variable = meta.is_within_variable == true\n local chat\n if is_within_variable then\n chat = M.safe_get(caller, \"codecompanion.Chat\") or M.safe_get(caller, \"codecompanion.inline\")\n else\n chat = M.safe_get(caller, \"codecompanion.chat\")\n end\n bufnr = M.safe_get(chat, \"context.bufnr\") or 0\n elseif type == \"avante\" then\n bufnr = M.safe_get(caller, \"avante.code.bufnr\") or 0\n elseif type == \"hubui\" then\n context = M.safe_get(caller, \"hubui.context\") or {}\n end\n return vim.tbl_extend(\"force\", {\n bufnr = bufnr,\n }, context)\nend\n\n---@param mode string\n---@return boolean\nlocal function is_visual_mode(mode)\n return mode == \"v\" or mode == \"V\" or mode == \"^V\"\nend\n\n---Get the context of the current buffer.\n---@param bufnr? integer\n---@param args? table\n---@return table\nfunction M.get_buf_info(bufnr, args)\n bufnr = bufnr or vim.api.nvim_get_current_buf()\n\n -- Validate buffer\n if not vim.api.nvim_buf_is_valid(bufnr) then\n error(\"Invalid buffer number: \" .. tostring(bufnr))\n end\n\n -- Find the window displaying this buffer\n local winnr\n for _, win in ipairs(vim.api.nvim_list_wins()) do\n if vim.api.nvim_win_get_buf(win) == bufnr then\n winnr = win\n break\n end\n end\n\n -- Fallback to current window if buffer isn't displayed\n if not winnr then\n winnr = vim.api.nvim_get_current_win()\n end\n local mode = vim.fn.mode()\n local cursor_pos = { 1, 0 } -- Default to start of buffer\n\n -- Only get cursor position if we have a valid window\n if winnr and vim.api.nvim_win_is_valid(winnr) then\n local ok, pos = pcall(vim.api.nvim_win_get_cursor, winnr)\n if ok then\n cursor_pos = pos\n end\n end\n\n -- Get all buffer lines for context\n local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)\n local start_line = cursor_pos[1]\n local start_col = cursor_pos[2]\n local end_line = cursor_pos[1]\n local end_col = cursor_pos[2]\n\n local is_visual = false\n local is_normal = true\n\n local function try_get_visual_selection()\n local ok, result = pcall(function()\n if args and args.range and args.range > 0 then\n is_visual = true\n is_normal = false\n mode = \"v\"\n return M.get_visual_selection(bufnr)\n elseif is_visual_mode(mode) then\n is_visual = true\n is_normal = false\n return M.get_visual_selection(bufnr)\n end\n return lines, start_line, start_col, end_line, end_col\n end)\n\n if not ok then\n -- Fallback to current cursor position on error\n vim.notify(\"Failed to get visual selection: \" .. tostring(result), vim.log.levels.WARN)\n is_visual = false\n is_normal = true\n return lines, start_line, start_col, end_line, end_col\n end\n return result\n end\n\n lines, start_line, start_col, end_line, end_col = try_get_visual_selection()\n\n return {\n winnr = winnr,\n bufnr = bufnr,\n mode = mode,\n is_visual = is_visual,\n is_normal = is_normal,\n buftype = vim.api.nvim_buf_get_option(bufnr, \"buftype\") or \"\",\n filetype = vim.api.nvim_buf_get_option(bufnr, \"filetype\") or \"\",\n filename = vim.api.nvim_buf_get_name(bufnr),\n cursor_pos = cursor_pos,\n lines = lines,\n line_count = vim.api.nvim_buf_line_count(bufnr),\n start_line = start_line,\n start_col = start_col,\n end_line = end_line,\n end_col = end_col,\n }\nend\n\n---@class ConfigParseResult\n---@field ok boolean\n---@field error string|nil\n---@field name string|nil\n---@field config table|nil\n\n---@param text string\n---@return ConfigParseResult\nfunction M.parse_config_from_json(text)\n local result = {\n ok = false,\n error = nil,\n name = nil,\n config = nil,\n }\n\n local ok, parsed = M.json_decode(text)\n if not ok then\n result.error = \"Invalid JSON format\"\n return result\n end\n\n -- Case 1: Full mcpServers object\n if parsed.mcpServers then\n local name, config = next(parsed.mcpServers)\n if not name then\n result.error = \"No server config found in mcpServers\"\n return result\n end\n result.ok = true\n result.name = name\n result.config = config\n return result\n end\n\n -- Case 2: Server config object\n if parsed.command or parsed.url then\n local is_string = parsed.command and type(parsed.command) == \"string\" or type(parsed.url) == \"string\"\n if is_string then\n result.ok = true\n result.name = \"unnamed\"\n result.config = parsed\n return result\n end\n end\n\n -- Case 3: Single server name:config pair\n if vim.tbl_count(parsed) == 1 then\n local name, config = next(parsed)\n result.ok = true\n result.name = name\n result.config = config\n return result\n end\n\n result.error = \"JSON should have a mcpServers key or name:config pair\"\n return result\nend\n\n---@param opts { title: string?, placeholder: string?, old_server_name: string?, start_insert: boolean?, is_native: boolean?, on_success: function?, on_error: function?, go_to_placeholder: boolean?, virtual_lines: Array[]?, config_source: string?, ask_for_source: boolean? }\nfunction M.open_server_editor(opts)\n opts = opts or {}\n ui_utils.multiline_input(opts.title or \"Paste server's JSON config\", opts.placeholder or \"\", function(content)\n if not content or vim.trim(content) == \"\" then\n if opts.on_error then\n opts.on_error(\"No content provided\")\n end\n return\n end\n local result = M.parse_config_from_json(content)\n if result.ok then\n if opts.old_server_name and opts.old_server_name ~= \"\" then\n if result.name ~= opts.old_server_name then\n if opts.is_native then\n if opts.on_error then\n opts.on_error(\"Server name cannot be changed for native servers\")\n else\n vim.notify(\"Server name cannot be changed for native servers\", vim.log.levels.ERROR)\n end\n return\n end\n -- If an old server name is provided, remove the old config\n State.hub_instance:remove_server_config(opts.old_server_name)\n vim.notify(\"Server \" .. opts.old_server_name .. \" removed\", vim.log.levels.INFO)\n end\n end\n\n local function save(config_source)\n local success = State.hub_instance:update_server_config(\n result.name,\n result.config,\n { merge = false, config_source = config_source }\n )\n if success then\n vim.notify(\"Server \" .. result.name .. \" added successfully\", vim.log.levels.INFO)\n if opts.on_success then\n opts.on_success(result.name, result.config)\n end\n else\n local error_msg = \"Failed to update server configuration\"\n if opts.on_error then\n opts.on_error(error_msg)\n else\n vim.notify(error_msg, vim.log.levels.ERROR)\n end\n end\n end\n local config_files = State.current_hub.config_files or {}\n if opts.ask_for_source and #config_files > 1 then\n vim.ui.select(config_files, {\n prompt = \"Select config path to save the server configuration\",\n }, function(choice)\n if choice then\n save(choice)\n else\n if opts.on_error then\n opts.on_error(\"No config source selected\")\n end\n return\n end\n end)\n else\n save(opts.config_source)\n end\n else\n if opts.on_error then\n opts.on_error(result.error)\n else\n vim.notify(result.error, vim.log.levels.ERROR)\n end\n end\n end, {\n filetype = \"json\",\n start_insert = opts.start_insert or false,\n show_footer = false,\n position = \"center\", -- Always use center positioning for server editor\n go_to_placeholder = opts.go_to_placeholder,\n virtual_lines = opts.virtual_lines,\n validate = function(content)\n local result = M.parse_config_from_json(content)\n if not result.ok then\n vim.notify(result.error, vim.log.levels.ERROR)\n return false\n end\n\n if opts.is_native then\n if type(result.config) ~= \"table\" then\n vim.notify(\"Config must be a table\", vim.log.levels.ERROR)\n return false\n end\n -- Native servers only need basic config validation\n return true\n else\n local valid = validation.validate_server_config(result.name, result.config)\n if not valid.ok then\n vim.notify(valid.error.message, vim.log.levels.ERROR)\n return false\n end\n end\n return true\n end,\n on_cancel = function()\n if opts.on_error then\n opts.on_error(\"User cancelled\")\n end\n end,\n })\nend\n\n--- Confirm and delete a server configuration with a detailed preview\n--- @param server_name string The name of the server to delete\n--- @param on_delete function? Callback function to call after deletion\nfunction M.confirm_and_delete_server(server_name, on_delete)\n if not server_name or server_name == \"\" then\n vim.notify(\"Server name is required for deletion\", vim.log.levels.ERROR)\n return\n end\n local async = require(\"plenary.async\")\n async.run(function()\n local config_manager = require(\"mcphub.utils.config_manager\")\n local server_config = config_manager.get_server_config(server_name, true) or {}\n -- Create confirmation message with highlights\n local message = {}\n\n -- Header line with highlights\n local header_line = NuiLine()\n header_line:append(\"Do you want to delete \", Text.highlights.muted)\n header_line:append(\"'\" .. server_name .. \"'\", Text.highlights.error)\n header_line:append(\" server?\", Text.highlights.muted)\n table.insert(message, header_line)\n table.insert(message, \"\")\n\n -- Current configuration preview\n if server_config then\n vim.list_extend(message, Text.render_json(vim.json.encode(server_config)))\n else\n local no_config_line = NuiLine()\n no_config_line:append(\"No current configuration found.\", Text.highlights.muted)\n table.insert(message, no_config_line)\n end\n\n -- Show confirmation dialog\n local confirmed, cancelled = ui_utils.confirm(message, {\n min_width = 70,\n max_width = 90,\n })\n\n if confirmed and not cancelled then\n -- Delete the server\n if State.hub_instance then\n local success = State.hub_instance:remove_server_config(server_name)\n if success then\n vim.notify(\"Server '\" .. server_name .. \"' deleted successfully!\", vim.log.levels.INFO)\n if on_delete then\n on_delete(server_name)\n end\n else\n vim.notify(\"Failed to delete server '\" .. server_name .. \"'\", vim.log.levels.ERROR)\n end\n else\n vim.notify(\"MCP Hub not available\", vim.log.levels.ERROR)\n end\n end\n end, function() end)\nend\n\n--- Convert ISO 8601 timestamp to relative time format (e.g., \"23s\", \"1d\", \"1hr\", \"2m\")\n---@param iso_string string ISO 8601 timestamp string\n---@return string Relative time string\nfunction M.iso_to_relative_time(iso_string)\n if not iso_string or iso_string == \"\" then\n return \"unknown\"\n end\n\n -- Parse ISO string to Unix timestamp\n local pattern = \"(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)\"\n local year, month, day, hour, min, sec = iso_string:match(pattern)\n\n if not year then\n return \"invalid\"\n end\n\n -- Convert to Unix timestamp\n local timestamp = os.time({\n year = tonumber(year),\n month = tonumber(month),\n day = tonumber(day),\n hour = tonumber(hour),\n min = tonumber(min),\n sec = tonumber(sec),\n })\n\n -- Get current time\n local now = os.time()\n local diff = now - timestamp\n\n -- Handle future dates\n if diff < 0 then\n diff = math.abs(diff)\n local future_result = M._format_time_diff(diff)\n return \"in \" .. future_result\n end\n\n return M._format_time_diff(diff)\nend\n\n--- Convert ms to relative time format (e.g., \"23s\", \"1d\", \"1hr\", \"2m\")\n--- @param ms number Time in milliseconds\n--- @return string Relative time string\nfunction M.ms_to_relative_time(ms)\n if type(ms) ~= \"number\" then\n ms = tonumber(ms)\n end\n if not ms or ms < 0 then\n return \"unknown\"\n end\n\n local seconds = math.floor(ms / 1000)\n return M._format_time_diff(seconds)\nend\n\n--- Internal helper to format time difference\n---@param diff number Time difference in seconds\n---@return string Formatted time string\nfunction M._format_time_diff(diff)\n if diff < 60 then\n return string.format(\"%ds\", diff)\n elseif diff < 3600 then -- Less than 1 hour\n return string.format(\"%dm\", math.floor(diff / 60))\n elseif diff < 86400 then -- Less than 1 day\n return string.format(\"%dh\", math.floor(diff / 3600))\n elseif diff < 2592000 then -- Less than 30 days\n return string.format(\"%dd\", math.floor(diff / 86400))\n elseif diff < 31536000 then -- Less than 1 year\n return string.format(\"%dmo\", math.floor(diff / 2592000))\n else\n return string.format(\"%dy\", math.floor(diff / 31536000))\n end\nend\n\n--- Decode a JSON string into a Lua table\n--- @param str string The JSON string to decode\n--- @param opts? {use_custom_parser: boolean} Optional options\n--- @return boolean The decoded Lua table, or nil if decoding fails\n--- @return table|nil\nfunction M.json_decode(str, opts)\n opts = opts or {}\n local ok, result\n\n -- Try decoding using vim.json.decode for all\n ok, result = pcall(vim.json.decode, str, { luanil = { object = true, array = true } })\n if ok then\n return ok, result\n end\n -- If decoding fails, check if we should use a custom parser\n if not ok and opts.use_custom_parser then\n -- Try custom parser first (lua-json5) e.g `require\n if type(config.json_decode) == \"function\" then\n ok, result = pcall(config.json_decode, str)\n if ok then\n return ok, result\n end\n end\n\n -- INFO: We can bundle a lightweight JSON5 parser using Node.js or rust but it needs a breaking change wrt the build step. Without build step, including the bundled script which is bundled in development might not go well with the users security concerns. So we will not include it for now and let the user provide a custom parser if needed.\n -- -- Fallback to bundled JSON5 parser\n -- local plugin_root = vim.fn.fnamemodify(debug.getinfo(1, \"S\").source:sub(2), \":h:h:h:h\")\n -- local json5_script = plugin_root .. \"/scripts/bundled_json5.js\"\n --\n -- local json5_result = vim.fn.system({ \"node\", json5_script }, str)\n --\n -- if vim.v.shell_error == 0 and json5_result and vim.trim(json5_result) ~= \"\" then\n -- -- Parse the clean JSON output from bundled JSON5 parser\n -- ok, result = pcall(vim.json.decode, json5_result, { luanil = { object = true, array = true } })\n -- if ok then\n -- return ok, result\n -- end\n -- end\n end\n return false, result\nend\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/utils/request.lua", "---@class ToolRequest\n---@field params table Tool arguments (validated against inputSchema)\n---@field tool MCPTool Complete tool definition including dynamic fields\n---@field server NativeServer Server instance\n---@field caller table Additional context from caller\n---@field editor_info EditorInfo Current editor state\nlocal ToolRequest = {}\nToolRequest.__index = ToolRequest\n\nfunction ToolRequest:new(opts)\n local instance = {\n server = opts.server,\n params = opts.arguments, -- Tool arguments become params\n tool = opts.tool, -- Store tool definition\n caller = opts.caller or {},\n editor_info = opts.editor_info,\n }\n return setmetatable(instance, self)\nend\n\n---@class PromptRequest\n---@field params table Template parameters from URI\n---@field prompt MCPPrompt Complete prompt definition including dynamic fields\n---@field server NativeServer Server instance\n---@field caller table Additional context from caller\n---@field editor_info EditorInfo Current editor state\n\nlocal PromptRequest = {}\nPromptRequest.__index = PromptRequest\nfunction PromptRequest:new(opts)\n local instance = {\n server = opts.server,\n params = opts.arguments, -- Template params\n prompt = opts.prompt, -- Store resource definition\n caller = opts.caller or {},\n editor_info = opts.editor_info,\n }\n return setmetatable(instance, self)\nend\n\n---@class ResourceRequest\n---@field params table Template parameters from URI\n---@field uri string Complete requested URI\n---@field uriTemplate string|nil Original template pattern if from template\n---@field resource MCPResource|MCPResourceTemplate Complete resource definition including dynamic fields\n---@field server NativeServer Server instance\n---@field caller table Additional context from caller\n---@field editor_info EditorInfo Current editor state\nlocal ResourceRequest = {}\nResourceRequest.__index = ResourceRequest\n\nfunction ResourceRequest:new(opts)\n local instance = {\n server = opts.server,\n params = opts.params, -- Template params\n resource = opts.resource, -- Store resource definition\n caller = opts.caller or {},\n uri = opts.uri,\n uriTemplate = opts.template,\n editor_info = opts.editor_info,\n }\n return setmetatable(instance, self)\nend\n\nreturn {\n ToolRequest = ToolRequest,\n ResourceRequest = ResourceRequest,\n PromptRequest = PromptRequest,\n}\n"], ["/mcphub.nvim/lua/mcphub/extensions/codecompanion/core.lua", "local M = {}\nlocal async = require(\"plenary.async\")\nlocal shared = require(\"mcphub.extensions.shared\")\n\n--- Core MCP tool execution logic\n---@param params MCPHub.ToolCallArgs | MCPHub.ResourceAccessArgs\n---@param agent CodeCompanion.Agent The Editor tool\n---@param output_handler function Callback for asynchronous calls\n---@param context MCPHub.ToolCallContext\n---@return nil|{ status: \"success\"|\"error\", data: string }\nfunction M.execute_mcp_tool(params, agent, output_handler, context)\n context = context or {}\n ---@diagnostic disable-next-line: missing-parameter\n async.run(function()\n -- Reuse existing validation logic\n local parsed_params = shared.parse_params(params, context.action)\n if #parsed_params.errors > 0 then\n return output_handler({\n status = \"error\",\n data = table.concat(parsed_params.errors, \"\\n\"),\n })\n end\n\n local result = shared.handle_auto_approval_decision(parsed_params)\n\n if result.error then\n return output_handler({\n status = \"error\",\n data = result.error,\n })\n end\n\n local hub = require(\"mcphub\").get_hub_instance()\n if not hub then\n return output_handler({\n status = \"error\",\n data = \"MCP Hub is not ready yet\",\n })\n end\n\n -- Call appropriate hub method\n if parsed_params.action == \"access_mcp_resource\" then\n hub:access_resource(parsed_params.server_name, parsed_params.uri, {\n caller = {\n type = \"codecompanion\",\n codecompanion = agent,\n auto_approve = result.approve,\n },\n parse_response = true,\n callback = function(res, err)\n if err or not res then\n output_handler({\n status = \"error\",\n data = err and tostring(err)\n or \"No response from accessing the resource \" .. parsed_params.uri,\n })\n elseif res then\n output_handler({ status = \"success\", data = res })\n end\n end,\n })\n elseif parsed_params.action == \"use_mcp_tool\" then\n hub:call_tool(parsed_params.server_name, parsed_params.tool_name, parsed_params.arguments, {\n caller = {\n type = \"codecompanion\",\n codecompanion = agent,\n auto_approve = result.approve,\n },\n parse_response = true,\n callback = function(res, err)\n if err or not res then\n output_handler({ status = \"error\", data = tostring(err) or \"No response from tool call\" })\n elseif res.error then\n output_handler({ status = \"error\", data = res.error })\n else\n output_handler({ status = \"success\", data = res })\n end\n end,\n })\n else\n return output_handler({\n status = \"error\",\n data = \"Invalid action type: \" .. parsed_params.action,\n })\n end\n end)\nend\n\n---@param display_name string\n---@param tool CodeCompanion.Agent.Tool\n---@param chat any\n---@param llm_msg string\n---@param is_error boolean\n---@param has_function_calling boolean\n---@param opts MCPHub.Extensions.CodeCompanionConfig\n---@param user_msg string?\n---@param images table\n-- Helper function for tool output formatting\nlocal function add_tool_output(\n display_name,\n tool,\n chat,\n llm_msg,\n is_error,\n has_function_calling,\n opts,\n user_msg,\n images\n)\n local config = require(\"codecompanion.config\")\n local helpers = require(\"codecompanion.strategies.chat.helpers\")\n local show_result_in_chat = opts.show_result_in_chat == true\n local text = llm_msg\n local formatted_name = opts.format_tool and opts.format_tool(display_name, tool) or display_name\n\n if has_function_calling then\n chat:add_tool_output(\n tool,\n text,\n (user_msg or show_result_in_chat or is_error) and (user_msg or text)\n or string.format(\"**`%s` Tool**: Successfully finished\", formatted_name)\n )\n for _, image in ipairs(images) do\n helpers.add_image(chat, image)\n end\n else\n if show_result_in_chat or is_error then\n chat:add_buf_message({\n role = config.constants.USER_ROLE,\n content = text,\n })\n else\n chat:add_message({\n role = config.constants.USER_ROLE,\n content = text,\n })\n chat:add_buf_message({\n role = config.constants.USER_ROLE,\n content = string.format(\"I've shared the result of the `%s` tool with you.\\n\", formatted_name),\n })\n end\n end\nend\n\n---@param display_name string\n---@param has_function_calling boolean\n---@param opts MCPHub.Extensions.CodeCompanionConfig\n---@return {error: function, success: function}\nfunction M.create_output_handlers(display_name, has_function_calling, opts)\n return {\n ---@param self CodeCompanion.Agent.Tool\n ---@param agent CodeCompanion.Agent\n ---@param stderr table The error output from the command\n error = function(self, agent, cmd, stderr)\n ---@diagnostic disable-next-line: cast-local-type\n stderr = has_function_calling and (stderr[#stderr] or \"\") or cmd[#cmd]\n ---@diagnostic disable-next-line: cast-local-type\n agent = has_function_calling and agent or self\n if type(stderr) == \"table\" then\n ---@diagnostic disable-next-line: cast-local-type\n stderr = vim.inspect(stderr)\n end\n local formatted_name = opts.format_tool and opts.format_tool(display_name, self) or display_name\n local err_msg = string.format(\n [[**`%s` Tool**: Failed with the following error:\n\n````\n%s\n````\n]],\n formatted_name,\n stderr\n )\n add_tool_output(display_name, self, agent.chat, err_msg, true, has_function_calling, opts, nil, {})\n end,\n\n ---@param self CodeCompanion.Agent.Tool\n ---@param agent CodeCompanion.Agent\n ---@param cmd table The command that was executed\n ---@param stdout table The output from the command\n success = function(self, agent, cmd, stdout)\n local image_cache = require(\"mcphub.utils.image_cache\")\n ---@type MCPResponseOutput\n local result = has_function_calling and stdout[#stdout] or cmd[#cmd]\n ---@diagnostic disable-next-line: cast-local-type\n agent = has_function_calling and agent or self\n local formatted_name = opts.format_tool and opts.format_tool(display_name, self) or display_name\n local to_llm = nil\n local to_user = nil\n local images = {}\n\n if result.text and result.text ~= \"\" then\n to_llm = string.format(\n [[**`%s` Tool**: Returned the following:\n\n````\n%s\n````]],\n formatted_name,\n result.text\n )\n end\n\n if result.images and #result.images > 0 then\n for _, image in ipairs(result.images) do\n local cached_file_path = image_cache.save_image(image.data, image.mimeType)\n local id = cached_file_path\n table.insert(images, {\n id = id,\n base64 = image.data,\n mimetype = image.mimeType,\n cached_file_path = cached_file_path,\n })\n end\n\n if not to_llm then\n to_llm = string.format(\n [[**`%s` Tool**: Returned the following:\n````\n%s\n````]],\n formatted_name,\n string.format(\"%d image%s returned\", #result.images, #result.images > 1 and \"s\" or \"\")\n )\n end\n\n to_user = to_llm .. (#images > 0 and string.format(\"\\n\\n#### Preview Images\\n\") or \"\")\n for _, image in ipairs(images) do\n local file = image.cached_file_path\n if file then\n local file_name = vim.fn.fnamemodify(file, \":t\")\n to_user = to_user .. string.format(\"\\n\\n\", file_name, vim.fn.fnameescape(file))\n else\n to_user = to_user .. string.format(\"\\n\\n\", file)\n end\n end\n end\n\n local fallback_to_llm = string.format(\"**`%s` Tool**: Completed with no output\", formatted_name)\n if opts.show_result_in_chat == false and not to_user then\n to_user = string.format(\"**`%s` Tool**: Successfully finished\", formatted_name)\n end\n add_tool_output(\n display_name,\n self,\n agent.chat,\n to_llm or fallback_to_llm,\n false,\n has_function_calling,\n opts,\n to_user,\n images\n )\n end,\n }\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/utils/response.lua", "---@class BaseResponse\n---@field output_handler function|nil Async callback handler\n---@field error fun(self: BaseResponse, message: string, details?: table): table Send error response\n---@field result table Response data\nlocal BaseResponse = {}\nBaseResponse.__index = BaseResponse\n\nfunction BaseResponse:new(output_handler)\n local instance = {\n output_handler = output_handler,\n result = {},\n }\n return setmetatable(instance, self)\nend\n\nfunction BaseResponse:send(result)\n local final_result = result or self.result\n if self.output_handler then\n -- Async with callback\n self.output_handler({\n result = final_result,\n })\n else\n -- Sync return\n return {\n result = final_result,\n }\n end\nend\n\n---@alias MCPResourceContent { uri: string, text?: string, blob?: string, mimeType: string }\n---@alias MCPContent { type: \"text\"|\"image\"|\"audio\"|\"resource\", text?: string, data?: string, resource?: MCPResourceContent, mimeType?: string }\n\n---@class ToolResponse : BaseResponse\n---@field result { content: MCPContent[] }\n---@field text fun(self: ToolResponse, text: string): ToolResponse Add text content\n---@field image fun(self: ToolResponse, data: string, mime: string): ToolResponse Add image content\n---@field audio fun(self: ToolResponse, data: string, mime: string): ToolResponse Add audio content\n---@field resource fun(self: ToolResponse, resource: MCPResourceContent): ToolResponse Add resource content\n---@field error fun(self: ToolResponse|BaseResponse, message: string, details?: table): table Send error response\n---@field send fun(self: ToolResponse, result?: table): table Send response\nlocal ToolResponse = setmetatable({}, { __index = BaseResponse })\nToolResponse.__index = ToolResponse\n\nfunction ToolResponse:new(output_handler)\n local instance = BaseResponse:new(output_handler)\n instance.result = { content = {} }\n setmetatable(instance, self)\n return instance\nend\n\nfunction ToolResponse:text(text)\n if type(text) ~= \"string\" then\n text = vim.inspect(text)\n end\n table.insert(self.result.content, {\n type = \"text\",\n text = text,\n })\n return self\nend\n\nfunction ToolResponse:image(data, mime)\n table.insert(self.result.content, {\n type = \"image\",\n data = data,\n mimeType = mime,\n })\n return self\nend\n\nfunction ToolResponse:audio(data, mime)\n table.insert(self.result.content, {\n type = \"audio\",\n data = data,\n mimeType = mime or \"audio/mp3\",\n })\n return self\nend\n\nfunction ToolResponse:resource(resource)\n table.insert(self.result.content, {\n type = \"resource\",\n resource = resource,\n })\n return self\nend\n\nfunction ToolResponse:error(message, details)\n if type(message) ~= \"string\" then\n message = vim.inspect(message)\n end\n local result = {\n isError = true,\n content = {\n {\n type = \"text\",\n text = message,\n },\n },\n }\n\n -- Add details if provided\n if details then\n table.insert(result.content, {\n type = \"text\",\n text = \"Details: \" .. vim.inspect(details),\n })\n end\n\n -- Auto-send error response\n return self:send(result)\nend\n\n---@class ResourceResponse : BaseResponse\nlocal ResourceResponse = setmetatable({}, { __index = BaseResponse })\nResourceResponse.__index = ResourceResponse\n\n---@return ResourceResponse\nfunction ResourceResponse:new(output_handler, uri, template)\n ---@class BaseResponse\n local instance = BaseResponse:new(output_handler)\n instance.uri = uri\n instance.template = template\n instance.result = { contents = {} }\n setmetatable(instance, self)\n return instance --[[@as ResourceResponse]]\nend\n\nfunction ResourceResponse:text(text, mime)\n if type(text) ~= \"string\" then\n text = vim.inspect(text)\n end\n table.insert(self.result.contents, {\n uri = self.uri,\n text = text,\n mimeType = mime or \"text/plain\",\n })\n return self\nend\n\nfunction ResourceResponse:blob(data, mime)\n table.insert(self.result.contents, {\n uri = self.uri,\n blob = data,\n mimeType = mime or \"application/octet-stream\",\n })\n return self\nend\n\nfunction ResourceResponse:image(data, mime)\n table.insert(self.result.contents, {\n uri = self.uri,\n blob = data,\n mimeType = mime or \"image/png\",\n })\n return self\nend\n\nfunction ResourceResponse:audio(data, mime)\n table.insert(self.result.contents, {\n uri = self.uri,\n blob = data,\n mimeType = mime or \"audio/mp3\",\n })\n return self\nend\n\nfunction ResourceResponse:error(message, details)\n if type(message) ~= \"string\" then\n message = vim.inspect(message)\n end\n -- For resources, we return error as a text resource\n self.result = {\n contents = {\n {\n uri = self.uri,\n text = message .. (details and (\"\\nDetails: \" .. vim.inspect(details)) or \"\"),\n mimeType = \"text/plain\",\n },\n },\n }\n return self:send(self.result)\nend\n\n---@class PromptResponse : BaseResponse\nlocal PromptResponse = setmetatable({}, { __index = BaseResponse })\nPromptResponse.__index = PromptResponse\n\nfunction PromptResponse:new(output_handler, name, description)\n ---@class BaseResponse\n local instance = BaseResponse:new(output_handler)\n instance.name = name\n instance.description = description\n instance.result = { messages = {} }\n instance.current_role = \"user\" -- Default role is user\n setmetatable(instance, self)\n return instance\nend\n\n-- Role state setters\nfunction PromptResponse:user()\n self.current_role = \"user\"\n return self\nend\n\nfunction PromptResponse:llm()\n self.current_role = \"assistant\"\n return self\nend\n\nfunction PromptResponse:system()\n self.current_role = \"system\"\n return self\nend\n\nfunction PromptResponse:text(text)\n if type(text) ~= \"string\" then\n text = vim.inspect(text)\n end\n table.insert(self.result.messages, {\n role = self.current_role,\n content = {\n type = \"text\",\n text = text,\n },\n })\n return self\nend\n\nfunction PromptResponse:image(data, mime)\n table.insert(self.result.messages, {\n role = self.current_role,\n content = {\n type = \"image\",\n data = data,\n mimeType = mime or \"image/png\",\n },\n })\n return self\nend\n\nfunction PromptResponse:blob(data, mime)\n table.insert(self.result.messages, {\n role = self.current_role,\n content = {\n type = \"blob\",\n data = data,\n mimeType = mime or \"application/octet-stream\",\n },\n })\n return self\nend\n\nfunction PromptResponse:audio(data, mime)\n table.insert(self.result.messages, {\n role = self.current_role,\n content = {\n type = \"audio\",\n data = data,\n mimeType = mime or \"audio/mp3\",\n },\n })\n return self\nend\n\nfunction PromptResponse:resource(resource)\n table.insert(self.result.messages, {\n role = self.current_role,\n content = {\n type = \"resource\",\n resource = resource,\n },\n })\n return self\nend\n\nfunction PromptResponse:error(message, details)\n if type(message) ~= \"string\" then\n message = vim.inspect(message)\n end\n -- Switch to system role for error, then send\n self:user():text(message .. (details and (\"\\nDetails: \" .. vim.inspect(details)) or \"\"))\n return self:send(self.result)\nend\n\nreturn {\n ToolResponse = ToolResponse,\n ResourceResponse = ResourceResponse,\n PromptResponse = PromptResponse,\n}\n"], ["/mcphub.nvim/lua/mcphub/extensions/avante/init.lua", "---@module \"avante\"\n--[[\n*MCP Servers Tool*\nThis tool can be used to call tools and resources from the MCP Servers.\nM.mcp_tool() will return a use_mcp_tool and access_mcp_resource function schemas.\n\nM.use_mcp_tool() will return schema for calling tools on MCP servers.\nM.access_mcp_resource() will return schema for accessing resources on MCP servers.\n--]]\n\n---@class MCPHub.Extensions.Avante\n---@field setup function(config: MCPHub.Extensions.AvanteConfig) Setup slash commands and other configurations for Avante extension\n---@field mcp_tool fun(): AvanteLLMTool,AvanteLLMTool\n---@field use_mcp_tool AvanteLLMTool\n---@field access_mcp_resource AvanteLLMTool\n\n---@class MCPHub.Extensions.Avante\nlocal M = {}\n\n---@type table\nlocal tool_schemas = {\n use_mcp_tool = {\n name = \"use_mcp_tool\",\n description = \"Calls tools on MCP servers.\",\n param = {\n type = \"table\",\n fields = {\n {\n name = \"server_name\",\n description = \"Name of the server to call the tool on. Must be from one of the available servers.\",\n type = \"string\",\n },\n {\n name = \"tool_name\",\n description = \"Name of the tool to call.\",\n type = \"string\",\n },\n {\n name = \"tool_input\",\n description = \"Input for the tool call. Must be a valid JSON object.\",\n type = \"object\",\n },\n },\n },\n returns = {}, -- Will be added dynamically in mcp_tool()\n },\n\n access_mcp_resource = {\n name = \"access_mcp_resource\",\n description = \"Get resources on MCP servers.\",\n param = {\n type = \"table\",\n fields = {\n {\n name = \"server_name\",\n description = \"Name of the server to call the resource on. Must be from one of the available servers.\",\n type = \"string\",\n },\n {\n name = \"uri\",\n description = \"URI of the resource to access.\",\n type = \"string\",\n },\n },\n },\n returns = {}, -- Will be added dynamically in mcp_tool()\n },\n}\n\n---@return AvanteLLMTool use_mcp_tool\n---@return AvanteLLMTool access_mcp_resource\nfunction M.mcp_tool()\n ---@param str string\n ---@param max_length number\n ---@return string\n local function truncate_utf8(str, max_length)\n if type(str) ~= \"string\" or #str <= max_length then\n return str\n end\n local i = 1\n local bytes = #str\n while i <= bytes and i < max_length do\n local c = string.byte(str, i)\n if c < 0x80 then\n i = i + 1\n elseif c < 0xE0 then\n i = i + 2\n elseif c < 0xF0 then\n i = i + 3\n else\n i = i + 4\n end\n end\n return str:sub(1, i - 1) .. \"... (truncated)\"\n end\n\n local async = require(\"plenary.async\")\n local shared = require(\"mcphub.extensions.shared\")\n for action_name, schema in pairs(tool_schemas) do\n ---@type AvanteLLMToolFunc\n schema.func = function(args, opts)\n opts = opts or {}\n local on_complete = opts.on_complete or function() end\n local on_log = opts.on_log or function() end\n ---@diagnostic disable-next-line: missing-parameter\n async.run(function()\n local hub = require(\"mcphub\").get_hub_instance()\n if not hub then\n return on_complete(nil, \"MCP Hub not initialized\")\n end\n local params = shared.parse_params(args, action_name)\n if #params.errors > 0 then\n return on_complete(nil, table.concat(params.errors, \"\\n\"))\n end\n\n local result = shared.handle_auto_approval_decision(params)\n if result.error then\n return on_complete(nil, result.error)\n end\n local sidebar = require(\"avante\").get()\n if params.action == \"access_mcp_resource\" then\n if on_log and type(on_log) == \"function\" then\n on_log(\n string.format(\"Accessing `%s` resource from server `%s`\", params.uri, params.server_name)\n )\n end\n hub:access_resource(params.server_name, params.uri, {\n parse_response = true,\n caller = {\n type = \"avante\",\n avante = sidebar,\n auto_approve = result.approve,\n },\n callback = function(result, err)\n --result has .text and .images [{mimeType, data}]\n on_complete(result.text, err)\n end,\n })\n elseif params.action == \"use_mcp_tool\" then\n if on_log and type(on_log) == \"function\" then\n on_log(\n string.format(\n \"Calling tool `%s` on server `%s` with arguments: %s\",\n params.tool_name,\n params.server_name,\n vim.inspect(params.arguments, {\n indent = \" \",\n depth = 2,\n process = function(item)\n return truncate_utf8(item, 80)\n end,\n })\n )\n )\n end\n hub:call_tool(params.server_name, params.tool_name, params.arguments, {\n parse_response = true,\n caller = {\n type = \"avante\",\n avante = sidebar,\n auto_approve = result.approve,\n },\n callback = function(result, err)\n if result.error then\n on_complete(nil, result.error)\n else\n on_complete(result.text, err)\n end\n end,\n })\n else\n return on_complete(nil, \"Invalid action type\")\n end\n end)\n end\n\n ---@type AvanteLLMToolReturn[]\n schema.returns = {\n {\n name = \"result\",\n description = string.format(\"The `%s` call returned the following text:\\n\", action_name),\n type = \"string\",\n },\n {\n name = \"error\",\n description = string.format(\"The `%s` call failed with the following error:\\n\", action_name),\n type = \"string\",\n optional = true,\n },\n }\n M[action_name] = schema\n end\n ---@diagnostic disable-next-line: redundant-return-value\n return unpack(vim.tbl_values(tool_schemas))\nend\n\n---@param config MCPHub.Extensions.AvanteConfig\nfunction M.setup(config)\n if config.make_slash_commands then\n --Avoid checking for avante if the extension is not enabled\n local ok, _ = pcall(require, \"avante\")\n if not ok then\n return\n end\n require(\"mcphub.extensions.avante.slash_commands\").setup()\n end\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/ui/capabilities/prompt.lua", "local Base = require(\"mcphub.ui.capabilities.base\")\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal highlights = require(\"mcphub.utils.highlights\").groups\nlocal Handlers = require(\"mcphub.utils.handlers\")\nlocal log = require(\"mcphub.utils.log\")\n\n---@class PromptHandler : CapabilityHandler\nlocal PromptHandler = setmetatable({}, {\n __index = Base,\n})\nPromptHandler.__index = PromptHandler\nPromptHandler.type = \"prompt\"\nPromptHandler.arguments = {}\n\nfunction PromptHandler:new(server_name, capability_info, view)\n local instance = Base:new(server_name, capability_info, view)\n setmetatable(instance, PromptHandler)\n instance.state = vim.tbl_extend(\"force\", instance.state, {\n params = {\n values = {},\n errors = {},\n },\n })\n return instance\nend\n\nfunction PromptHandler:format_param_type(param)\n local handler = Handlers.TypeHandlers[param.type]\n if not handler then\n return param.type\n end\n return handler.format(param)\nend\n\nfunction PromptHandler:validate_all_params()\n if not self.arguments then\n return true, nil, {}\n end\n\n local errors = {}\n for _, argument in ipairs(self.arguments) do\n local value = self.state.params.values[argument.name]\n\n -- Check required fields\n if argument.required and (not value or value == \"\") then\n errors[argument.name] = \"Required argument\"\n -- Only validate non-empty values\n elseif value and value ~= \"\" then\n if type(value) ~= \"string\" then\n errors[argument.name] = \"Invalid type, expected string\"\n end\n end\n -- Skip validation for empty optional fields\n end\n\n if next(errors) then\n return false, \"Some required arguments are missing or invalid\", errors\n end\n\n return true, nil, {}\nend\n\n-- Action handling\n-- Common callback logic for input handling\nfunction PromptHandler:handle_param_update(param_name, input)\n -- Clear previous error\n self.state.params.errors[param_name] = nil\n local param = {}\n for _, v in ipairs(self.arguments) do\n if v.name == param_name then\n param = v\n end\n end\n\n -- Handle empty input\n if input == \"\" then\n -- Check if field is required\n local is_required = param.required == true\n if is_required then\n self.state.params.errors[param_name] = \"Required parameter\"\n else\n -- For optional fields, clear value and error\n self.state.params.values[param_name] = nil\n end\n else\n self.state.params.values[param_name] = input\n end\n self.view:draw()\nend\n\nfunction PromptHandler:handle_input_action(param_name)\n self:handle_input(\n string.format(\"%s (%s): \", param_name, \"string\"),\n self.state.params.values[param_name],\n function(input)\n self:handle_param_update(param_name, input)\n end\n )\nend\n\nfunction PromptHandler:handle_text_box(line)\n local type, context = self:get_line_info(line)\n if type == \"input\" then\n local param_name = context\n self:open_text_box(\n string.format(\"%s (%s)\", param_name, \"string\"),\n self.state.params.values[param_name] or \"\",\n function(input)\n self:handle_param_update(param_name, input)\n end\n )\n end\nend\n\nfunction PromptHandler:handle_action(line)\n local type, context = self:get_line_info(line)\n if not type then\n return\n end\n\n if type == \"input\" then\n self:handle_input_action(context)\n elseif type == \"submit\" then\n self:execute()\n end\nend\n\n-- Execution\nfunction PromptHandler:execute()\n -- Check if already executing\n if self.state.is_executing then\n vim.notify(\"Getting prompt...\", vim.log.levels.WARN)\n return\n end\n\n -- Validate all parameters first\n local ok, err, errors = self:validate_all_params()\n self.state.params.errors = errors\n self.state.error = err\n if not ok then\n self.view:draw()\n return\n end\n\n -- Set executing state\n self.state.is_executing = true\n self.state.error = nil\n self.view:draw()\n\n -- Convert all parameters to their proper types\n local converted_values = {}\n for name, value in pairs(self.state.params.values) do\n converted_values[name] = value\n end\n\n log.debug(string.format(\"Getting prompt %s with parameters: %s\", self.def.name, vim.inspect(converted_values)))\n -- Execute tool\n if State.hub_instance then\n State.hub_instance:get_prompt(self.server_name, self.def.name, converted_values, {\n caller = {\n type = \"hubui\",\n hubui = State.ui_instance,\n },\n parse_response = true,\n callback = function(response, error)\n self:handle_response(response, error)\n self.view:draw()\n end,\n })\n end\nend\n\nfunction PromptHandler:render_submit()\n local submit_content\n if self.state.is_executing then\n submit_content = NuiLine():append(\"[ \" .. Text.icons.event .. \" Processing... ]\", highlights.muted)\n else\n submit_content = NuiLine():append(\"[ \" .. Text.icons.gear .. \" Submit ]\", highlights.success_fill)\n end\n return submit_content\nend\n\n-- Rendering\nfunction PromptHandler:render_param_form(line_offset)\n -- Clear previous line tracking\n self:clear_line_tracking()\n\n local lines = {}\n\n local arguments = self.def.arguments\n local is_function = type(arguments) == \"function\"\n -- Parameters section\n vim.list_extend(\n lines,\n self:render_section_start((is_function and \"(\" .. Text.icons.event .. \" Dynamic) \" or \"\") .. \"Input Params\")\n )\n arguments = self:get_arguments(arguments)\n self.arguments = arguments\n if not arguments or not next(arguments) then\n -- No parameters case\n local placeholder = NuiLine():append(\"No arguments required \", highlights.muted)\n\n -- Submit button\n local submit_content = self:render_submit()\n vim.list_extend(\n lines,\n self:render_section_content({ placeholder, NuiLine():append(\" \", highlights.muted), submit_content }, 2)\n )\n\n -- Track submit line\n self:track_line(line_offset + #lines, \"submit\")\n else\n -- Render each parameter\n for _, argument in ipairs(arguments) do\n -- Parameter name and type\n local name_line = NuiLine()\n :append(argument.required and \"* \" or \" \", highlights.error)\n :append(argument.name, highlights.success)\n :append(string.format(\" (%s)\", \"string\"), highlights.muted)\n vim.list_extend(lines, self:render_section_content({ name_line }, 2))\n\n -- Description if any\n if argument.description then\n for _, desc_line in ipairs(Text.multiline(argument.description, highlights.muted)) do\n vim.list_extend(lines, self:render_section_content({ desc_line }, 4))\n end\n end\n\n -- Input field\n local value = self.state.params.values[argument.name]\n local input_line = NuiLine():append(\"> \", highlights.success):append(value or \"\", highlights.info)\n vim.list_extend(lines, self:render_section_content({ input_line }, 2))\n\n -- Track input line\n self:track_line(line_offset + #lines, \"input\", argument.name)\n\n -- Error if any\n if self.state.params.errors[argument.name] then\n local error_lines = Text.multiline(self.state.params.errors[argument.name], highlights.error)\n vim.list_extend(lines, self:render_section_content(error_lines, 2))\n end\n\n table.insert(lines, Text.pad_line(NuiLine():append(\"│\", highlights.muted)))\n end\n\n -- Submit button\n local submit_content = self:render_submit()\n vim.list_extend(lines, self:render_section_content({ submit_content }, 2))\n\n -- Track submit line\n self:track_line(line_offset + #lines, \"submit\")\n end\n\n -- Error message\n if self.state.error then\n local error_lines = Text.multiline(self.state.error, highlights.error)\n vim.list_extend(lines, self:render_section_content(error_lines, 2))\n end\n vim.list_extend(lines, self:render_section_end())\n return lines\nend\n\nfunction PromptHandler:get_arguments(arguments)\n local base = {}\n arguments = self.def.arguments\n if not arguments or (type(arguments) ~= \"function\" and not next(arguments or {})) then\n arguments = base\n end\n local parsedArguments = arguments\n if type(arguments) == \"function\" then\n local ok, schema = pcall(arguments, self.def)\n if not ok then\n local err = \"Error in arguments function: \" .. tostring(schema)\n self.state.error = err\n log.error(err)\n parsedArguments = base\n else\n parsedArguments = schema or base\n end\n end\n local function validate_arguments(args, name)\n for _, arg in ipairs(args) do\n if type(arg) ~= \"table\" then\n return {\n ok = false,\n error = \"Argument should be a table in \" .. name .. \" prompt\",\n }\n end\n if not arg.name or arg.name == \"\" then\n return {\n ok = false,\n error = \"Argument name is required in \" .. name .. \" prompt\",\n }\n end\n end\n return { ok = true }\n end\n local res = validate_arguments(parsedArguments, self.def.name)\n if not res.ok then\n local err = \"Error in arguments function: \" .. tostring(res.error)\n self.state.error = err\n log.error(err)\n return base\n end\n return parsedArguments\nend\n\nfunction PromptHandler:render(line_offset)\n line_offset = line_offset or 0\n local lines = {}\n vim.list_extend(lines, vim.tbl_map(Text.pad_line, Text.multiline(self:get_description(), highlights.muted)))\n table.insert(lines, Text.pad_line(NuiLine()))\n -- Parameter form\n vim.list_extend(lines, self:render_param_form(line_offset + #lines))\n table.insert(lines, Text.pad_line(NuiLine())) -- Empty line\n\n if not self.state.result then\n return lines\n end\n\n vim.list_extend(lines, self:render_section_start(\"Result\"))\n\n -- Handle text content\n if self.state.result then\n ---@diagnostic disable-next-line: undefined-field\n local messages = self.state.result.messages or {}\n for _, message in ipairs(messages) do\n vim.list_extend(lines, self:render_section_content({ \" \" }))\n local role = message.role\n local output = message.output\n vim.list_extend(lines, self:render_section_content({ NuiLine():append(role, highlights.success) }))\n vim.list_extend(lines, self:render_output(output))\n end\n end\n\n vim.list_extend(lines, self:render_section_end())\n return lines\nend\n\nreturn PromptHandler\n"], ["/mcphub.nvim/lua/mcphub/ui/capabilities/tool.lua", "local Base = require(\"mcphub.ui.capabilities.base\")\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal highlights = require(\"mcphub.utils.highlights\").groups\nlocal Handlers = require(\"mcphub.utils.handlers\")\nlocal log = require(\"mcphub.utils.log\")\nlocal validation = require(\"mcphub.utils.validation\")\n\n---@class ToolHandler : CapabilityHandler\nlocal ToolHandler = setmetatable({}, {\n __index = Base,\n})\nToolHandler.__index = ToolHandler\nToolHandler.type = \"tool\"\nToolHandler.parsedInputSchema = {}\n\nfunction ToolHandler:new(server_name, capability_info, view)\n local instance = Base:new(server_name, capability_info, view)\n setmetatable(instance, ToolHandler)\n instance.state = vim.tbl_extend(\"force\", instance.state, {\n params = {\n values = {},\n errors = {},\n },\n })\n return instance\nend\n\n-- Parameter ordering\nfunction ToolHandler:get_ordered_params(inputSchema)\n if not inputSchema or not inputSchema.properties then\n return {}\n end\n\n local params = {}\n for name, prop in pairs(inputSchema.properties) do\n table.insert(params, {\n name = name,\n type = prop.type,\n description = prop.description,\n required = vim.tbl_contains(inputSchema.required or {}, name),\n default = prop.default,\n value = self.state.params.values[name],\n })\n end\n\n -- Sort by required first, then name\n table.sort(params, function(a, b)\n if a.required ~= b.required then\n return a.required\n end\n return a.name < b.name\n end)\n\n return params\nend\n\n-- Parameter handling\nfunction ToolHandler:validate_param(name, value)\n local param_schema = self.parsedInputSchema.properties[name]\n if not param_schema then\n return false, \"Invalid parameter schema\"\n end\n --TODO: handle anyOf where type is nil\n if not param_schema.type then\n return true\n end\n\n -- Get type handler\n local handler = Handlers.TypeHandlers[param_schema.type]\n if not handler then\n return false, \"Unknown parameter type: \" .. param_schema.type\n end\n\n -- Validate value\n local is_valid = handler.validate(value, param_schema)\n if not is_valid then\n return false, string.format(\"Invalid %s value: %s\", param_schema.type, value)\n end\n\n return true, nil\nend\n\nfunction ToolHandler:convert_param(name, value)\n local param_schema = self.parsedInputSchema.properties[name]\n local handler = Handlers.TypeHandlers[param_schema.type]\n if not handler then\n return value\n end\n return handler.convert(value)\nend\n\nfunction ToolHandler:format_param_type(param)\n local handler = Handlers.TypeHandlers[param.type]\n if not handler then\n return param.type\n end\n return handler.format(param)\nend\n\nfunction ToolHandler:validate_all_params()\n if not self.parsedInputSchema then\n return true, nil, {}\n end\n\n local errors = {}\n local params = self:get_ordered_params(self.parsedInputSchema)\n\n for _, param in ipairs(params) do\n local value = self.state.params.values[param.name]\n\n -- Check required fields\n if param.required and (not value or value == \"\") then\n errors[param.name] = \"Required parameter\"\n -- Only validate non-empty values\n elseif value and value ~= \"\" then\n local ok, err = self:validate_param(param.name, value)\n if not ok then\n errors[param.name] = err\n end\n end\n -- Skip validation for empty optional fields\n end\n\n if next(errors) then\n return false, \"Some required parameters are missing or invalid\", errors\n end\n\n return true, nil, {}\nend\n\n-- Action handling\n-- Common callback logic for input handling\nfunction ToolHandler:handle_param_update(param_name, input)\n -- Clear previous error\n self.state.params.errors[param_name] = nil\n\n -- Handle empty input\n if input == \"\" then\n -- Check if field is required\n local is_required = vim.tbl_contains(self.parsedInputSchema.required or {}, param_name)\n if is_required then\n self.state.params.errors[param_name] = \"Required parameter\"\n else\n -- For optional fields, clear value and error\n self.state.params.values[param_name] = nil\n end\n else\n -- Only validate non-empty input\n local ok, err = self:validate_param(param_name, input)\n if not ok then\n self.state.params.errors[param_name] = err\n else\n -- Update value\n self.state.params.values[param_name] = input\n end\n end\n self.view:draw()\nend\n\nfunction ToolHandler:handle_input_action(param_name)\n local param_schema = self.parsedInputSchema.properties[param_name]\n if not param_schema then\n return\n end\n\n self:handle_input(\n string.format(\"%s (%s): \", param_name, self:format_param_type(param_schema)),\n self.state.params.values[param_name],\n function(input)\n self:handle_param_update(param_name, input)\n end\n )\nend\n\nfunction ToolHandler:handle_text_box(line)\n local type, context = self:get_line_info(line)\n if type == \"input\" then\n local param_name = context\n local param_schema = self.parsedInputSchema.properties[param_name]\n if not param_schema then\n return\n end\n\n self:open_text_box(\n string.format(\"%s (%s)\", param_name, self:format_param_type(param_schema)),\n self.state.params.values[param_name] or \"\",\n function(input)\n self:handle_param_update(param_name, input)\n end\n )\n end\nend\n\nfunction ToolHandler:handle_action(line)\n local type, context = self:get_line_info(line)\n if not type then\n return\n end\n\n if type == \"input\" then\n self:handle_input_action(context)\n elseif type == \"submit\" then\n self:execute()\n end\nend\n\n-- Execution\nfunction ToolHandler:execute()\n -- Check if already executing\n if self.state.is_executing then\n vim.notify(\"Tool is already running\", vim.log.levels.WARN)\n return\n end\n\n -- Validate all parameters first\n local ok, err, errors = self:validate_all_params()\n self.state.params.errors = errors\n self.state.error = err\n if not ok then\n self.view:draw()\n return\n end\n\n -- Set executing state\n self.state.is_executing = true\n self.state.error = nil\n self.view:draw()\n\n -- Convert all parameters to their proper types\n local converted_values = {}\n for name, value in pairs(self.state.params.values) do\n converted_values[name] = self:convert_param(name, value)\n end\n\n log.debug(string.format(\"Executing tool %s with parameters: %s\", self.def.name, vim.inspect(converted_values)))\n -- Execute tool\n if State.hub_instance then\n State.hub_instance:call_tool(self.server_name, self.def.name, converted_values, {\n caller = {\n type = \"hubui\",\n hubui = State.ui_instance,\n },\n parse_response = true,\n callback = function(response, error)\n self:handle_response(response, error)\n self.view:draw()\n end,\n })\n end\nend\n\nfunction ToolHandler:render_submit()\n local submit_content\n if self.state.is_executing then\n submit_content = NuiLine():append(\"[ \" .. Text.icons.event .. \" Processing... ]\", highlights.muted)\n else\n submit_content = NuiLine():append(\"[ \" .. Text.icons.gear .. \" Submit ]\", highlights.success_fill)\n end\n return submit_content\nend\n\n-- Rendering\nfunction ToolHandler:render_param_form(line_offset)\n -- Clear previous line tracking\n self:clear_line_tracking()\n\n local lines = {}\n\n local inputSchema = self.def.inputSchema\n local is_function = type(inputSchema) == \"function\"\n -- Parameters section\n vim.list_extend(\n lines,\n self:render_section_start((is_function and \"(\" .. Text.icons.event .. \" Dynamic) \" or \"\") .. \"Input Params\")\n )\n inputSchema = self:get_inputSchema(inputSchema)\n self.parsedInputSchema = inputSchema\n if not inputSchema or not next(inputSchema.properties or {}) then\n -- No parameters case\n local placeholder = NuiLine():append(\"No parameters required \", highlights.muted)\n\n -- Submit button\n local submit_content = self:render_submit()\n vim.list_extend(\n lines,\n self:render_section_content({ placeholder, NuiLine():append(\" \", highlights.muted), submit_content }, 2)\n )\n\n -- Track submit line\n self:track_line(line_offset + #lines, \"submit\")\n else\n -- Render each parameter\n local params = self:get_ordered_params(inputSchema)\n for _, param in ipairs(params) do\n -- Parameter name and type\n local name_line = NuiLine()\n :append(param.required and \"* \" or \" \", highlights.error)\n :append(param.name, highlights.success)\n :append(string.format(\" (%s)\", self:format_param_type(param)), highlights.muted)\n vim.list_extend(lines, self:render_section_content({ name_line }, 2))\n\n -- Description if any\n if param.description then\n for _, desc_line in ipairs(Text.multiline(param.description, highlights.muted)) do\n vim.list_extend(lines, self:render_section_content({ desc_line }, 4))\n end\n end\n\n -- Input field\n local value = self.state.params.values[param.name]\n local input_line = NuiLine():append(\"> \", highlights.success):append(value or \"\", highlights.info)\n vim.list_extend(lines, self:render_section_content({ input_line }, 2))\n\n -- Track input line\n self:track_line(line_offset + #lines, \"input\", param.name)\n\n -- Error if any\n if self.state.params.errors[param.name] then\n local error_lines = Text.multiline(self.state.params.errors[param.name], highlights.error)\n vim.list_extend(lines, self:render_section_content(error_lines, 2))\n end\n\n table.insert(lines, Text.pad_line(NuiLine():append(\"│\", highlights.muted)))\n end\n\n -- Submit button\n local submit_content = self:render_submit()\n vim.list_extend(lines, self:render_section_content({ submit_content }, 2))\n\n -- Track submit line\n self:track_line(line_offset + #lines, \"submit\")\n end\n\n -- Error message\n if self.state.error then\n local error_lines = Text.multiline(self.state.error, highlights.error)\n vim.list_extend(lines, self:render_section_content(error_lines, 2))\n end\n vim.list_extend(lines, self:render_section_end())\n return lines\nend\n\nfunction ToolHandler:get_inputSchema(inputSchema)\n local base = {\n type = \"object\",\n properties = {},\n }\n inputSchema = self.def.inputSchema\n if not inputSchema or (type(inputSchema) ~= \"function\" and not next(inputSchema or {})) then\n inputSchema = base\n end\n local parsedSchema = inputSchema\n if type(inputSchema) == \"function\" then\n local ok, schema = pcall(inputSchema, self.def)\n if not ok then\n local err = \"Error in inputSchema function: \" .. tostring(schema)\n self.state.error = err\n log.error(err)\n parsedSchema = base\n else\n parsedSchema = schema or base\n end\n end\n local res = validation.validate_inputSchema(parsedSchema, self.def.name)\n if not res.ok then\n local err = \"Error in inputSchema function: \" .. tostring(res.error)\n self.state.error = err\n log.error(err)\n return base\n end\n return parsedSchema\nend\n\nfunction ToolHandler:render(line_offset)\n line_offset = line_offset or 0\n local lines = {}\n vim.list_extend(lines, vim.tbl_map(Text.pad_line, Text.multiline(self:get_description(), highlights.muted)))\n table.insert(lines, Text.pad_line(NuiLine()))\n -- Parameter form\n vim.list_extend(lines, self:render_param_form(line_offset + #lines))\n\n -- Result if any\n vim.list_extend(lines, self:render_result())\n\n return lines\nend\n\nreturn ToolHandler\n"], ["/mcphub.nvim/lua/mcphub/ui/capabilities/base.lua", "local highlights = require(\"mcphub.utils.highlights\").groups\nlocal ImageCache = require(\"mcphub.utils.image_cache\")\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal ui_utils = require(\"mcphub.utils.ui\")\n\n---@class CapabilityHandler\nlocal CapabilityHandler = {\n type = nil, -- to be set by subclasses\n}\nCapabilityHandler.__index = CapabilityHandler\n\nfunction CapabilityHandler:new(server_name, capability_info, view)\n ---@class CapabilityHandler\n local handler = setmetatable({\n name = capability_info.def\n and (capability_info.def.name or capability_info.def.uri or capability_info.def.uriTemplate)\n or (capability_info.name or \"\"),\n server_name = server_name,\n info = capability_info,\n def = capability_info.def or {},\n view = view,\n state = {\n is_executing = false,\n result = nil,\n error = nil,\n },\n interactive_lines = {},\n }, self)\n return handler\nend\n\n--- Get preferred cursor position when entering capability mode\n---@return number[]|nil Line number to position cursor at\nfunction CapabilityHandler:get_cursor_position()\n -- Default to first interactive line if any\n if #self.interactive_lines > 0 then\n return { self.interactive_lines[1].line, 2 }\n end\n return nil\nend\n\n-- Line tracking for interactivity\nfunction CapabilityHandler:track_line(line_nr, type, context)\n table.insert(self.interactive_lines, {\n line = line_nr,\n type = type,\n context = context,\n })\nend\n\nfunction CapabilityHandler:clear_line_tracking()\n self.interactive_lines = {}\nend\n\nfunction CapabilityHandler:get_line_info(line_nr)\n for _, tracked in ipairs(self.interactive_lines) do\n if tracked.line == line_nr then\n return tracked.type, tracked.context\n end\n end\n return nil, nil\nend\n\n-- Common highlighting\nfunction CapabilityHandler:handle_cursor_move(view, line)\n local type, _ = self:get_line_info(line)\n if not type then\n return\n end\n\n if type == \"submit\" and not self.state.is_executing then\n view.cursor_highlight = vim.api.nvim_buf_set_extmark(view.ui.buffer, view.hover_ns, line - 1, 0, {\n virt_text = { { \"[ Submit]\", highlights.muted } },\n virt_text_pos = \"eol\",\n })\n elseif type == \"input\" then\n view.cursor_highlight = vim.api.nvim_buf_set_extmark(view.ui.buffer, view.hover_ns, line - 1, 0, {\n virt_text = { { \"[ Edit, Multiline Edit]\", highlights.muted } },\n virt_text_pos = \"eol\",\n })\n end\nend\n\n-- Input handling\nfunction CapabilityHandler:handle_input(prompt, default, callback)\n vim.ui.input({\n prompt = prompt,\n default = default or \"\",\n }, function(input)\n if input ~= nil then -- Only handle if not cancelled\n callback(input)\n end\n end)\nend\n\n-- Text box handling\nfunction CapabilityHandler:open_text_box(...)\n ui_utils.multiline_input(...)\nend\n\n-- Common section rendering utilities\nfunction CapabilityHandler:render_section_start(title, highlight)\n local lines = {}\n table.insert(\n lines,\n Text.pad_line(\n NuiLine():append(\"╭─\", highlights.muted):append(\" \" .. title .. \" \", highlight or highlights.header)\n )\n )\n return lines\nend\n\nfunction CapabilityHandler:render_section_content(content, indent_level)\n local lines = {}\n local padding = string.rep(\" \", indent_level or 1)\n for _, line in ipairs(content) do\n local rendered_line = NuiLine()\n rendered_line:append(\"│\", highlights.muted):append(padding, highlights.muted):append(line)\n table.insert(lines, Text.pad_line(rendered_line))\n end\n return lines\nend\n\nfunction CapabilityHandler:render_section_end(content, indent_level)\n local lines = {}\n local padding = string.rep(\" \", indent_level or 1)\n if content then\n for _, line in ipairs(content) do\n local rendered_line = NuiLine()\n rendered_line:append(\"╰─\", highlights.muted):append(padding, highlights.muted):append(line)\n table.insert(lines, Text.pad_line(rendered_line))\n end\n else\n table.insert(lines, Text.pad_line(NuiLine():append(\"╰─\", highlights.muted)))\n end\n return lines\nend\n\nfunction CapabilityHandler:render_output(output)\n local lines = {}\n --Handle text content\n if output.text and output.text ~= \"\" then\n vim.list_extend(lines, self:render_section_content(Text.multiline(output.text, highlights.info), 1))\n end\n -- Handle image content\n if output.images and #output.images > 0 then\n if #lines > 0 then\n vim.list_extend(lines, self:render_section_content({ \" \" }, 1))\n end\n for i, img in ipairs(output.images) do\n -- Save to temp file\n local ok, filepath = pcall(ImageCache.save_image, img.data, img.mimeType or \"application/octet-stream\")\n if ok and filepath then\n -- Create filesystem URL\n local url = \"file://\" .. filepath\n -- Show friendly name with URL\n local image_line = NuiLine()\n :append(\"Image \" .. i .. \": \", highlights.muted)\n :append(\" [\", highlights.muted)\n :append(url, highlights.link)\n :append(\"]\", highlights.muted)\n vim.list_extend(lines, self:render_section_content({ image_line }, 1))\n else\n vim.list_extend(lines, self:render_section_content({ \"Failed to save image: \" .. filepath }, 1))\n end\n end\n end\n\n if output.audios and #output.audios > 0 then\n if #lines > 0 then\n vim.list_extend(lines, self:render_section_content({ \" \" }, 1))\n end\n for i, _ in ipairs(output.audios) do\n local audio_line = NuiLine():append(\"Audio \" .. i .. \": Audio data cannot be shown\", highlights.muted)\n vim.list_extend(lines, self:render_section_content({ audio_line }, 1))\n end\n end\n\n --Handle blobs content\n if output.blobs and #output.blobs > 0 then\n if #lines > 0 then\n vim.list_extend(lines, self:render_section_content({ \" \" }, 1))\n end\n for i, _ in ipairs(output.blobs) do\n local blob_line = NuiLine():append(\"Blob \" .. i .. \": Blob data cannot be shown\", highlights.muted)\n vim.list_extend(lines, self:render_section_content({ blob_line }, 1))\n end\n end\n return lines\nend\n\n-- Common result rendering\nfunction CapabilityHandler:render_result()\n if not self.state.result then\n return {}\n end\n\n local lines = {}\n table.insert(lines, Text.pad_line(NuiLine())) -- Empty line\n vim.list_extend(lines, self:render_section_start(\"Result\"))\n vim.list_extend(lines, self:render_output(self.state.result))\n vim.list_extend(lines, self:render_section_end())\n return lines\nend\n\n-- Error handling\nfunction CapabilityHandler:handle_response(response, err)\n self.state.is_executing = false\n if err then\n vim.notify(string.format(\"%s execution failed: %s\", self.type, err), vim.log.levels.ERROR)\n self.state.error = err\n self.state.result = response\n else\n if response.error then\n self.state.error = response.error\n self.state.result = response\n else\n self.state.result = response\n self.state.error = nil\n end\n end\nend\n\nfunction CapabilityHandler:get_description(def_description)\n local description = def_description or self.def.description or \"\"\n if type(description) == \"function\" then\n local ok, desc = pcall(description, self.def)\n if not ok then\n description = \"Failed to get description :\" .. (desc or \"\")\n else\n description = \"(\" .. Text.icons.event .. \" Dynamic) \" .. (desc or \"Nothing returned\")\n end\n end\n return description\nend\n\n-- Abstract methods to be implemented by subclasses\nfunction CapabilityHandler:execute()\n error(string.format(\"execute() not implemented for capability type: %s\", self.type))\nend\n\nfunction CapabilityHandler:handle_action(...)\n error(string.format(\"handle_action() not implemented for capability type: %s\", self.type))\nend\n\n---@return NuiLine[]\nfunction CapabilityHandler:render(...)\n error(string.format(\"render() not implemented for capability type: %s\", self.type))\nend\n\nreturn CapabilityHandler\n"], ["/mcphub.nvim/lua/mcphub/utils/config_manager.lua", "local Error = require(\"mcphub.utils.errors\")\nlocal State = require(\"mcphub.state\")\nlocal log = require(\"mcphub.utils.log\")\nlocal utils = require(\"mcphub.utils\")\nlocal validation = require(\"mcphub.utils.validation\")\n\nlocal M = {}\n\n--- Find server by name in current active servers\n--- @param server_name string\n--- @param from_non_native? boolean Whether to search in non-native servers\n--- @return table|nil server object with config_source field\nlocal function find_server_by_name(server_name, from_non_native)\n -- Search in native servers\n if from_non_native ~= true then\n for _, server in ipairs(State.server_state.native_servers or {}) do\n if server.name == server_name then\n return vim.tbl_extend(\"force\", server, { is_native = true })\n end\n end\n end\n -- Search in regular MCP servers\n for _, server in ipairs(State.server_state.servers or {}) do\n if server.name == server_name then\n return server\n end\n end\n return nil\nend\n\n--- Read and parse a config file\n--- @param file_path string Path to the config file\n--- @return table|nil config Parsed config or nil on error\n--- @return string|nil error Error message if parsing failed\nlocal function read_config_file(file_path)\n -- Check if file exists, create with default content if not\n local file = io.open(file_path, \"r\")\n if not file then\n -- Ensure parent directory exists\n local dir_path = vim.fn.fnamemodify(file_path, \":h\")\n if vim.fn.isdirectory(dir_path) == 0 then\n vim.fn.mkdir(dir_path, \"p\")\n end\n\n local create_file = io.open(file_path, \"w\")\n if not create_file then\n return nil, \"Failed to create config file: \" .. file_path\n end\n\n -- Write default config\n local default_config = { mcpServers = vim.empty_dict() }\n create_file:write(vim.json.encode(default_config))\n create_file:close()\n\n -- Reopen for reading\n file = io.open(file_path, \"r\")\n if not file then\n return nil, \"Failed to reopen created config file: \" .. file_path\n end\n end\n\n -- Read and parse JSON\n local content = file:read(\"*a\")\n file:close()\n\n local success, json = utils.json_decode(content, { use_custom_parser = true })\n if not success then\n local error_msg = [[Invalid JSON in config file: ]]\n .. file_path\n .. [[\n\nIf your config file uses JSON5 syntax (comments, trailing commas), please:\n1. Install lua-json5: https://github.com/Joakker/lua-json5\n2. Add to your mcphub setup: json_decode = require('json5').parse\n\nExample:\n require('mcphub').setup({\n json_decode = require('json5').parse,\n -- other config...\n })\n\nParse error: ]]\n .. tostring(json)\n return nil, error_msg\n end\n\n return json, nil\nend\n\n--- Detect original format and normalize config\n--- @param config table Raw config object\n--- @param file_path string File path for logging\n--- @return table normalized_config Config with mcpServers key\n--- @return string original_servers_key Original key used (\"servers\" or \"mcpServers\")\n--- @return string|nil error Error message if validation failed\nlocal function normalize_config_format(config, file_path)\n -- Format detection\n local has_servers = config.servers and type(config.servers) == \"table\"\n local has_mcp_servers = config.mcpServers and type(config.mcpServers) == \"table\"\n local original_servers_key = \"mcpServers\" -- default\n\n if not has_servers and not has_mcp_servers then\n return nil, nil, \"Config file must contain either 'servers' or 'mcpServers' object: \" .. file_path\n end\n\n local normalized = vim.deepcopy(config)\n\n -- Determine original format and normalize\n if has_servers and not has_mcp_servers then\n -- Pure VS Code format\n original_servers_key = \"servers\"\n normalized.mcpServers = config.servers\n log.debug(\"ConfigManager: VS Code format detected in \" .. file_path)\n elseif has_servers and has_mcp_servers then\n -- Both exist, prefer servers (VS Code format takes precedence)\n original_servers_key = \"servers\"\n normalized.mcpServers = config.servers\n log.debug(\"ConfigManager: Both 'servers' and 'mcpServers' found in \" .. file_path .. \", using 'servers'\")\n end\n return normalized, original_servers_key, nil\nend\n\n--- Validate all servers in a config\n--- @param config table Config with mcpServers\n--- @param file_path string File path for error reporting\n--- @return boolean success True if all servers are valid\n--- @return string|nil error Error message if validation failed\nlocal function validate_servers_in_config(config, file_path)\n for server_name, server_config in pairs(config.mcpServers or {}) do\n local validation_result = validation.validate_server_config(server_name, server_config)\n if not validation_result.ok then\n return false,\n \"Server validation failed for '\"\n .. server_name\n .. \"' in \"\n .. file_path\n .. \": \"\n .. validation_result.error.message\n end\n end\n return true, nil\nend\n\n--- Write config back to file preserving original format\n--- @param config table Config to write\n--- @param file_path string Path to write to\n--- @param original_servers_key string Original key format (\"servers\" or \"mcpServers\")\n--- @return boolean success True if write succeeded\n--- @return string|nil error Error message if write failed\nlocal function write_config_file(config, file_path, original_servers_key)\n local output_config = vim.deepcopy(config)\n\n -- Convert back to original format if needed\n if original_servers_key == \"servers\" and output_config.mcpServers then\n output_config.servers = output_config.mcpServers\n output_config.mcpServers = nil\n end\n\n local utils = require(\"mcphub.utils\")\n local json_str = utils.pretty_json(vim.json.encode(output_config), { use_jq = true })\n\n local file = io.open(file_path, \"w\")\n if not file then\n return false, \"Failed to open config file for writing: \" .. file_path\n end\n\n file:write(json_str)\n file:close()\n return true, nil\nend\n\n--- Read, parse, normalize and validate a config file - returns table with all info\n--- @param file_path string Path to the config file\n--- @return table result {ok: boolean, json: table?, content: string?, original_key: string?, error: string?}\nlocal function validate_config_file(file_path)\n -- Read raw config\n local raw_config, read_error = read_config_file(file_path)\n if not raw_config then\n return {\n ok = false,\n error = read_error,\n }\n end\n\n -- Normalize format and detect original key\n local normalized_config, original_servers_key, normalize_error = normalize_config_format(raw_config, file_path)\n if not normalized_config then\n return {\n ok = false,\n error = normalize_error,\n }\n end\n\n -- Validate all servers\n local valid, validation_error = validate_servers_in_config(normalized_config, file_path)\n if not valid then\n return {\n ok = false,\n error = validation_error,\n }\n end\n\n return {\n ok = true,\n json = normalized_config,\n original_json = raw_config,\n original_key = original_servers_key,\n }\nend\n\n--- Load a single config file and cache it\n--- @param file_path string Path to the config file\n--- @return boolean success Whether the file was loaded successfully\n--- @return string|nil error Error message if loading failed\nfunction M.load_config(file_path)\n if not file_path or file_path == \"\" then\n log.warn(\"ConfigManager: Empty file path provided\")\n return false, \"Empty file path provided\"\n end\n\n local file_result = validate_config_file(file_path)\n if not file_result.ok then\n log.error(\"ConfigManager: \" .. file_result.error)\n return false, file_result.error\n end\n\n -- Cache the normalized config, ensuring empty objects stay as objects\n State.config_files_cache = State.config_files_cache or {}\n State.config_files_cache[file_path] = {\n mcpServers = file_result.json.mcpServers or vim.empty_dict(),\n nativeMCPServers = file_result.json.nativeMCPServers or vim.empty_dict(),\n }\n vim.schedule(function()\n State:notify_subscribers({ config_files_cache = true }, \"ui\")\n end)\n\n log.debug(\"ConfigManager: Loaded config file: \" .. file_path .. \" (format: \" .. file_result.original_key .. \")\")\n return true, nil\nend\n\n--- Get the config source for a server\n--- @param server string|table Server name or server object\n--- @return string|nil Config source path or nil if not found\nfunction M.get_config_source(server)\n local server_obj\n\n if type(server) == \"string\" then\n -- Find server in active servers list\n server_obj = find_server_by_name(server)\n if not server_obj then\n log.debug(\"ConfigManager: Server not found: \" .. server)\n return nil\n end\n else\n -- server is an object\n server_obj = server\n end\n return server_obj.config_source or State.config.config\nend\n\n--- Get server config by server name or server object\n--- @param server string|table Server name or server object with config_source\n--- @param from_non_native? boolean Whether to get from non-native servers\n--- @return table|nil Server config or nil if not found\nfunction M.get_server_config(server, from_non_native)\n local server_name, config_source, is_native\n\n if type(server) == \"string\" then\n -- Find server in active servers list to get config_source\n local server_obj = find_server_by_name(server, from_non_native)\n if not server_obj then\n log.debug(\"ConfigManager: Server not found: \" .. server)\n return nil\n end\n server_name = server\n config_source = server_obj.config_source\n is_native = server_obj.is_native or false\n else\n -- server is an object\n server_name = server.name\n config_source = server.config_source\n is_native = server.is_native or false\n end\n\n if not config_source then\n log.warn(\"ConfigManager: No config_source for server: \" .. server_name)\n return nil\n end\n\n -- Ensure config is loaded\n if not State.config_files_cache or not State.config_files_cache[config_source] then\n log.debug(\"ConfigManager: Config not cached, loading: \" .. config_source)\n if not M.load_config(config_source) then\n return nil\n end\n end\n\n -- Get config from cache\n local file_config = State.config_files_cache[config_source]\n if is_native then\n return file_config.nativeMCPServers[server_name]\n else\n return file_config.mcpServers[server_name]\n end\nend\n\n--- Update server config in the correct source file\n--- @param server string|table Server name or server object\n--- @param config table | nil New config to merge/replace\n--- @param options? { merge : boolean?, config_source: string?} Options\n--- @return boolean success Whether the update was successful\nfunction M.update_server_config(server, config, options)\n options = options or {}\n local merge = options.merge ~= false -- default to true\n\n local server_name, config_source, is_native\n\n if type(server) == \"string\" then\n -- Use {} so that we can add a new server\n local server_obj = find_server_by_name(server) or {}\n server_name = server\n -- For servers without config_source, or new servers use global config\n config_source = server_obj.config_source or State.config.config\n is_native = server_obj.is_native or false\n else\n server_name = server.name\n if not server_name then\n log.error(\"ConfigManager: Invalid server object provided, missing name\")\n return false\n end\n config_source = server.config_source or State.config.config\n is_native = server.is_native or false\n end\n if options.config_source then\n config_source = options.config_source\n end\n if not config_source then\n log.error(\"ConfigManager: No config_source for server: \" .. server_name)\n return false\n end\n\n -- Load current config file\n local file_result = validate_config_file(config_source)\n if not file_result.ok then\n log.error(\n \"ConfigManager: Failed to load config file for update: \" .. config_source .. \" - \" .. file_result.error\n )\n return false\n end\n\n local file_config = file_result.json\n local original_servers_key = file_result.original_key\n local server_section = is_native and \"nativeMCPServers\" or \"mcpServers\"\n\n -- Ensure section exists\n file_config[server_section] = file_config[server_section] or {}\n\n -- Update server config\n if merge and type(config) == \"table\" and file_config[server_section][server_name] then\n file_config[server_section][server_name] =\n vim.tbl_deep_extend(\"force\", file_config[server_section][server_name], config)\n else\n file_config[server_section][server_name] = config\n end\n\n -- Write back to file preserving original format\n local write_success, write_error = write_config_file(file_config, config_source, original_servers_key)\n if not write_success then\n log.error(\"ConfigManager: \" .. write_error)\n return false\n end\n\n -- Update cache\n State.config_files_cache = State.config_files_cache or {}\n State.config_files_cache[config_source] = {\n mcpServers = file_config.mcpServers or {},\n nativeMCPServers = file_config.nativeMCPServers or {},\n }\n State:notify_subscribers({\n config_files_cache = true,\n }, \"ui\")\n\n log.debug(\"ConfigManager: Updated server config: \" .. server_name .. \" in \" .. config_source)\n return true\nend\n\n--- Refresh config cache from files in current hub context\n--- Uses State.current_hub.config_files to know which files to reload\n--- @param paths string[]|nil Array of file paths to refresh, if nil uses current hub context\n--- @return boolean success Whether all files were refreshed successfully\n--- @return string|nil error Error message if any file failed to refresh\nfunction M.refresh_config(paths)\n if not paths and (not State.current_hub or not State.current_hub.config_files) then\n log.debug(\"ConfigManager: No current hub context for refresh\")\n return false, \"No current hub context for refresh\"\n end\n\n State.config_files_cache = {} -- Clear cache\n paths = paths or State.current_hub.config_files\n\n for _, file_path in ipairs(paths) do\n local ok, error_msg = M.load_config(file_path)\n if not ok then\n return false, \"Failed to load config file '\" .. file_path .. \"': \" .. (error_msg or \"unknown error\")\n end\n end\n\n log.debug(\"ConfigManager: Refreshed \" .. #paths .. \" config files\")\n return true, nil\nend\n\n--- Get all active config files from current hub context\n--- @param reverse? boolean Whether to reverse the order of files\n--- @return string[] Array of config file paths\nfunction M.get_active_config_files(reverse)\n if not State.current_hub or not State.current_hub.config_files then\n return {}\n end\n local config_files = vim.deepcopy(State.current_hub.config_files)\n if reverse then\n return vim.fn.reverse(config_files)\n end\n return State.current_hub.config_files\nend\n\n--- Get the raw config content for a specific file (for UI display)\n--- @param file_path string Path to the config file\n--- @return table|nil config content or nil if not found/invalid\nfunction M.get_file_config(file_path)\n -- Ensure file is loaded in cache\n if not State.config_files_cache or not State.config_files_cache[file_path] then\n if not M.load_config(file_path) then\n return nil\n end\n end\n\n return State.config_files_cache[file_path]\nend\n\n--- Get the full config file content as JSON string (for Config UI)\n--- @param file_path string Path to the config file\n--- @return table|nil JSON content or nil if not found\n--- @return string|nil error Error message if loading failed\nfunction M.get_file_content_json(file_path)\n local file_result = validate_config_file(file_path)\n if not file_result.ok then\n return nil, file_result.error\n end\n return file_result.original_json, nil\nend\n\n--- Initialize config cache with current hub context\n--- Should be called when hub context changes\n--- @return boolean success\nfunction M.initialize()\n log.debug(\"ConfigManager: Initializing with current hub context\")\n return M.refresh_config()\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/state.lua", "---[[\n--- Global state management for MCPHub\n--- Handles setup, server, and UI state\n---]]\nlocal constants = require(\"mcphub.utils.constants\")\nlocal log = require(\"mcphub.utils.log\")\n\n---@class MCPHub.State\nlocal State = {\n ---@type \"not_started\" | \"in_progress\" | \"completed\" | \"failed\" MCPHub setup state\n setup_state = \"not_started\",\n ---@type MCPHub.Config\n config = {},\n\n ---@type MCPHub.Hub?\n hub_instance = nil,\n ---@type MCPHub.UI?\n ui_instance = nil,\n\n -- Current hub context\n current_hub = {\n port = nil,\n workspace_root = nil,\n config_files = {}, -- Array of config files being used\n is_workspace_mode = false,\n },\n\n -- Config files cache\n config_files_cache = {}, -- Map of file_path -> {mcpServers, nativeMCPServers}\n\n -- Marketplace state\n marketplace_state = {\n ---@type \"empty\" | \"loading\" | \"loaded\" | \"error\"\n status = \"empty\",\n catalog = {\n ---@type MarketplaceItem[]\n items = {},\n ---@type number\n last_updated = nil,\n },\n filters = {\n search = \"\",\n category = \"\",\n sort = \"stars\", -- newest/stars/name\n },\n ---@type MarketplaceItem\n selected_server = nil,\n ---@type table\n server_details = {}, -- Map of mcpId -> details\n },\n\n -- Server state\n server_state = {\n ---@type MCPHub.Constants.HubState\n state = constants.HubState.STARTING,\n ---@type number?\n pid = nil, -- Server process ID when running\n ---@type number?\n started_at = nil, -- When server was started\n ---@type MCPServer[]\n servers = {}, -- Regular MCP servers\n ---@type NativeServer[]\n native_servers = {}, -- Native MCP servers\n\n ---@type MCPHub.Workspaces\n workspaces = {},\n },\n\n -- Error management\n errors = {\n ---@type MCPError[]\n items = {}, -- Array of error objects with type property\n },\n\n -- Server output\n server_output = {\n ---@type LogEntry[]\n entries = {}, -- Chronological server output entries\n },\n\n -- State management\n last_update = 0,\n subscribers = {\n ui = {}, -- UI-related subscribers\n server = {}, -- Server state subscribers\n all = {}, -- All state changes subscribers\n errors = {},\n },\n\n -- subscribers\n ---@type table\n event_subscribers = {},\n}\n\n---@return boolean\nfunction State:is_connected()\n return self.server_state.state == constants.HubState.READY\n or self.server_state.state == constants.HubState.RESTARTED\nend\n\nfunction State:reset()\n State.server_state = {\n status = \"disconnected\",\n pid = nil,\n started_at = nil,\n servers = {},\n native_servers = State.server_state.native_servers or {},\n }\n State.errors = {\n items = {},\n }\n State.server_output = {\n entries = {},\n }\n State.marketplace_state = {\n status = \"loading\",\n catalog = {\n items = {},\n last_updated = nil,\n },\n filters = {\n search = \"\",\n category = \"\",\n sort = \"stars\",\n },\n selected_server = nil,\n server_details = {},\n }\n State.last_update = 0\nend\n\n---@param partial_state table\n---@param update_type? string\nfunction State:update(partial_state, update_type)\n update_type = update_type or \"all\"\n local changes = {}\n\n -- Track changes\n for k, v in pairs(partial_state) do\n if type(v) == \"table\" then\n if not vim.deep_equal(self[k], v) then\n changes[k] = true\n self[k] = vim.tbl_deep_extend(\"force\", self[k] or {}, v)\n end\n else\n if self[k] ~= v then\n changes[k] = true\n self[k] = v\n end\n end\n end\n\n -- Notify if changed\n if next(changes) then\n self.last_update = vim.loop.now()\n self:notify_subscribers(changes, update_type)\n end\nend\n\n--- Add an error to state and optionally log it\n---@param err MCPError The error to add\n---@param log_level? string Optional explicit log level (debug/info/warn/error)\nfunction State:add_error(err, log_level)\n -- Add error to list\n table.insert(self.errors.items, err)\n\n -- Sort errors with newest first\n table.sort(self.errors.items, function(a, b)\n return (a.timestamp or 0) > (b.timestamp or 0)\n end)\n\n -- Keep reasonable history (max 100 errors)\n if #self.errors.items > 100 then\n table.remove(self.errors.items)\n end\n\n -- Notify subscribers\n self:notify_subscribers({\n errors = true,\n }, \"errors\")\n\n -- Log with explicit level or infer from error type\n if log_level then\n log[log_level:lower()](tostring(err))\n else\n -- Default logging behavior based on error type\n local level = err.type == \"SETUP\" and \"error\" or err.type == \"SERVER\" and \"warn\" or \"info\"\n log[level](tostring(err))\n end\nend\n\n--- Clear errors of a specific type or all errors\n---@param type? string Optional error type to clear (setup/server/runtime)\nfunction State:clear_errors(type)\n if type then\n -- Filter out errors of specified type\n local filtered = {}\n for _, err in ipairs(self.errors.items) do\n if err.type:lower() ~= type:lower() then\n table.insert(filtered, err)\n end\n end\n self.errors.items = filtered\n else\n -- Clear all errors\n self.errors.items = {}\n end\n self:notify_subscribers({\n errors = true,\n }, \"errors\")\nend\n\nfunction State:clear_logs()\n self.server_output.entries = {}\n self.errors.items = {}\n self:notify_subscribers({\n logs = true,\n }, \"logs\")\nend\n\n--- Get all errors of a specific type\n---@param type? string Optional error type (setup/server/runtime)\n---@return MCPError[]\nfunction State:get_errors(type)\n if type then\n -- Filter by type\n local filtered = {}\n for _, err in ipairs(self.errors.items) do\n if err.type:lower() == type:lower() then\n table.insert(filtered, err)\n end\n end\n return vim.deepcopy(filtered)\n end\n return vim.deepcopy(self.errors.items)\nend\n--- Check if a server is installed by comparing id\n--- @param id string Server ID to check\n--- @return boolean true if server is installed\nfunction State:is_server_installed(id)\n local servers = self.server_state.servers or {}\n for _, server in ipairs(servers) do\n if server.name == id then\n return true\n end\n end\n return false\nend\n\n---@param event string\n---@param data any\nfunction State:emit(event, data)\n local event_subscribers = self.event_subscribers[event]\n if event_subscribers then\n for _, cb in ipairs(event_subscribers) do\n cb(data)\n end\n end\nend\n\n---@param event string\n---@param callback function\nfunction State:add_event_listener(event, callback)\n self.event_subscribers[event] = self.event_subscribers[event] or {}\n table.insert(self.event_subscribers[event], callback)\nend\n\n---@param event string\n---@param callback function\nfunction State:remove_event_listener(event, callback)\n if self.event_subscribers[event] then\n for i, cb in ipairs(self.event_subscribers[event]) do\n if cb == callback then\n table.remove(self.event_subscribers[event], i)\n break\n end\n end\n end\nend\n\n---@param event string\nfunction State:remove_all_event_listeners(event)\n self.event_subscribers[event] = {}\nend\n\n---@param entry LogEntry\nfunction State:add_server_output(entry)\n if not entry or not entry.type or not entry.message then\n return\n end\n\n -- Ensure entry has timestamp\n entry.timestamp = entry.timestamp or vim.loop.now()\n\n table.insert(self.server_output.entries, {\n type = entry.type, -- info/warn/error/debug\n message = entry.message, -- The actual message\n timestamp = entry.timestamp,\n data = entry.data, -- Optional extra data\n })\n\n -- Keep reasonable history\n if #self.server_output.entries > 1000 then\n table.remove(self.server_output.entries, 1)\n end\n\n self:notify_subscribers({\n logs = true,\n }, \"logs\")\nend\n\n---@param status string\n---@param ... any\nfunction State:update_hub_state(status, ...)\n self:update({\n server_state = {\n state = status,\n unpack(... or {}),\n },\n }, \"server\")\n local utils = require(\"mcphub.utils\")\n utils.fire(\"MCPHubStateChange\", {\n state = status,\n active_servers = 0,\n })\nend\n\n---@param callback function\n---@param types string[]\nfunction State:subscribe(callback, types)\n types = types or { \"all\" }\n for _, type in ipairs(types) do\n self.subscribers[type] = self.subscribers[type] or {}\n table.insert(self.subscribers[type], callback)\n end\nend\n\n---@param changes table\n---@param update_type string\nfunction State:notify_subscribers(changes, update_type)\n -- Notify type-specific subscribers\n if update_type ~= \"all\" and self.subscribers[update_type] then\n for _, callback in ipairs(self.subscribers[update_type]) do\n callback(self, changes)\n end\n end\n -- Always notify 'all' subscribers\n for _, callback in ipairs(self.subscribers.all) do\n callback(self, changes)\n end\nend\n\nreturn State\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/edit_ui.lua", "local keymap_utils = require(\"mcphub.native.neovim.utils.keymap\")\nlocal text = require(\"mcphub.utils.text\")\n\n---@class EditUI\n---@field config UIConfig Configuration options\n---@field state UIState Current UI state\n---@field highlights table Highlight management\nlocal EditUI = {}\nEditUI.__index = EditUI\n\n-- UI State tracking\n---@class UIState\n---@field origin_winnr integer Window number of the start\n---@field bufnr integer Buffer number being edited\n---@field file_path string Path to the file\n---@field located_blocks LocatedBlock[] Blocks to process\n---@field original_content string Original file content\n---@field callbacks table Success/cancel callbacks\n---@field augroup integer Autocommand group ID\n---@field is_replacing_entire_file boolean Whether the entire file is being replaced\n---@field hunk_extmarks table A map of block_id to a list of extmark IDs for its hunks\n---@field has_completed boolean Whether the session has been completed\n---@field hunk_blocks DiffHunk[] Generated hunk blocks for granular navigation\n---@field completed_hunks table Map of hunk_id to completion status\n---@field current_hunk_index integer Currently active hunk (1-based)\n---@field original_keymaps table Stored original keymaps before session\n\n-- Default UI configuration\nlocal DEFAULT_CONFIG = {\n auto_navigate = true,\n go_to_origin_on_complete = true,\n send_diagnostics = true,\n wait_for_diagnostics = 1000,\n diagnostic_severity = vim.diagnostic.severity.WARN, -- Only show warnings and above by default\n keybindings = {\n accept = \".\", -- Accept current change\n reject = \",\", -- Reject current change\n next = \"n\", -- Next diff\n prev = \"p\", -- Previous diff\n accept_all = \"ga\", -- Accept all remaining changes\n reject_all = \"gr\", -- Reject all remaining changes\n },\n}\n\n-- Create new EditUI instance\n---@param config UIConfig? Optional configuration\n---@return EditUI\nfunction EditUI.new(config)\n local self = setmetatable({}, EditUI)\n self.config = vim.tbl_deep_extend(\"force\", DEFAULT_CONFIG, config or {})\n self.state = nil\n self.highlights = {\n namespace_diff = vim.api.nvim_create_namespace(\"mcphub-editor-diff\"),\n namespace_hints = vim.api.nvim_create_namespace(\"mcphub-editor-hints\"),\n priority = 20000,\n }\n return self\nend\n\n-- Start interactive editing session\n---@param opts table Session options\nfunction EditUI:start_interactive_editing(opts)\n local buf_utils = require(\"mcphub.native.neovim.utils.buffer\")\n local bufnr = buf_utils.open_file_in_editor(opts.file_path)\n if not bufnr then\n return opts.on_error(\"Couldn't open buffer for editing\")\n end\n self.state = {\n origin_winnr = opts.origin_winnr,\n bufnr = bufnr,\n is_replacing_entire_file = opts.is_replacing_entire_file,\n file_path = opts.file_path,\n located_blocks = opts.located_blocks,\n original_content = opts.original_content,\n hunk_extmarks = {},\n current_hunk_index = 1,\n completed_hunks = {},\n callbacks = {\n on_complete = opts.on_complete,\n on_cancel = opts.on_cancel,\n },\n has_completed = false,\n augroup = vim.api.nvim_create_augroup(\"mcphub_editor_ui\", { clear = true }),\n }\n\n self:_setup_autocmds()\n self:_apply_all_changes()\n\n -- Generate hunk blocks for granular navigation\n self:_generate_hunk_blocks()\n\n -- Early completion if no actual changes were found\n if not self.state.hunk_blocks or #self.state.hunk_blocks == 0 then\n return self:_complete_session()\n end\n\n if opts.interactive == false then\n return self:_handle_save()\n end\n\n self:_highlight_all_blocks()\n\n self:_setup_keybindings()\n\n if self.config.auto_navigate then\n self:_navigate_to_hunk(1)\n end\n\n self:_update_hints()\nend\n-- Apply all changes from located blocks to the buffer\nfunction EditUI:_apply_all_changes()\n local base_line_offset = 0\n\n local sorted_blocks = self.state.located_blocks\n table.sort(sorted_blocks, function(a, b)\n return a.location_result.start_line < b.location_result.start_line\n end)\n\n -- Apply each block's changes\n for _, block in ipairs(sorted_blocks) do\n local start_line = block.location_result.start_line + base_line_offset\n local end_line = block.location_result.end_line + base_line_offset\n\n -- Apply the replacement\n vim.api.nvim_buf_set_lines(\n self.state.bufnr,\n start_line - 1, -- Convert to 0-based\n end_line,\n false,\n block.replace_lines\n )\n\n -- Update the block's position after changes\n block.applied_start_line = start_line\n block.applied_end_line = start_line + #block.replace_lines - 1\n\n -- Calculate offset for next blocks\n local line_diff = #block.replace_lines - (end_line - start_line + 1)\n base_line_offset = base_line_offset + line_diff\n end\nend\n\n---Generate hunk blocks from located blocks for granular navigation\n---@return DiffHunk[]\nfunction EditUI:_generate_hunk_blocks()\n self.state.hunk_blocks = {}\n\n for _, located_block in ipairs(self.state.located_blocks) do\n -- Calculate precise diff hunks\n local precise_diff_hunks = {}\n local location_result = located_block.location_result\n if location_result.found then\n precise_diff_hunks = vim.diff(\n table.concat(location_result.found_lines, \"\\n\"),\n table.concat(located_block.replace_lines, \"\\n\"),\n { result_type = \"indices\", algorithm = \"histogram\", ctxlen = 3 }\n ) or {} --[[@as table]]\n end\n -- Process each precise_diff_hunk\n for hunk_index, hunk in ipairs(precise_diff_hunks) do\n local old_start_idx, old_count, new_start_idx, new_count = unpack(hunk)\n\n -- Extract actual old/new content for this hunk\n local old_lines = {}\n for i = old_start_idx, old_start_idx + old_count - 1 do\n table.insert(old_lines, located_block.location_result.found_lines[i] or \"\")\n end\n\n local new_lines = {}\n for i = new_start_idx, new_start_idx + new_count - 1 do\n table.insert(new_lines, located_block.replace_lines[i] or \"\")\n end\n\n -- Determine hunk type\n local hunk_type = \"change\"\n if old_count == 0 then\n hunk_type = \"addition\"\n elseif new_count == 0 then\n hunk_type = \"deletion\"\n end\n\n -- Calculate absolute position in buffer\n local absolute_start = located_block.applied_start_line + new_start_idx - 1\n local absolute_end = absolute_start + new_count - 1\n\n -- For pure deletions, position is where content was removed\n if new_count == 0 then\n absolute_start = located_block.applied_start_line + old_start_idx - 1\n absolute_end = absolute_start -- No actual lines in buffer\n end\n\n ---@type DiffHunk\n local hunk_block = {\n hunk_id = string.format(\"%s_hunk_%d\", located_block.block_id, hunk_index),\n parent_id = located_block.block_id,\n old_lines = old_lines,\n new_lines = new_lines,\n type = hunk_type,\n applied_start_line = absolute_start,\n applied_end_line = absolute_end,\n extmark_id = nil, -- Will be set during highlighting\n deletion_position = new_count == 0 and absolute_start or nil,\n confidence = located_block.location_result.confidence or 100, -- Default to 100% confidence\n }\n\n table.insert(self.state.hunk_blocks, hunk_block)\n end\n end\n return self.state.hunk_blocks\nend\n\n-- Highlight hunk blocks in the buffer (new hunk-based approach)\nfunction EditUI:_highlight_all_blocks()\n vim.api.nvim_buf_clear_namespace(self.state.bufnr, self.highlights.namespace_diff, 0, -1)\n\n if not self.state.hunk_blocks then\n return\n end\n\n for _, hunk_block in ipairs(self.state.hunk_blocks) do\n self:_highlight_hunk_block(hunk_block)\n end\nend\n\n--- Highlight a single hunk block with proper boundary handling\n---@param hunk_block DiffHunk Block to highlight\nfunction EditUI:_highlight_hunk_block(hunk_block)\n -- Handle new content highlighting (changes and additions)\n if hunk_block.type == \"change\" or hunk_block.type == \"addition\" then\n hunk_block.extmark_id = vim.api.nvim_buf_set_extmark(\n self.state.bufnr,\n self.highlights.namespace_diff,\n hunk_block.applied_start_line - 1,\n 0,\n {\n hl_group = text.highlights.diff_add,\n end_row = hunk_block.applied_end_line,\n hl_eol = true,\n hl_mode = \"combine\",\n priority = self.highlights.priority,\n }\n )\n end\n\n -- Handle old content as virtual lines (changes and deletions)\n if hunk_block.type == \"change\" or hunk_block.type == \"deletion\" then\n local virt_lines = {}\n local function pad_line(line)\n local max_cols = vim.o.columns\n local line_length = #line\n if line_length < max_cols then\n return line .. string.rep(\" \", max_cols - line_length)\n end\n return line\n end\n\n -- Add deletion indicator for pure deletions\n if hunk_block.type == \"deletion\" then\n table.insert(virt_lines, {\n {\n pad_line(\n string.format(\n \"[DELETED %d line%s]\",\n #hunk_block.old_lines,\n #hunk_block.old_lines > 1 and \"s\" or \"\"\n )\n ),\n text.highlights.diff_delete,\n },\n })\n end\n\n -- Add old content lines\n for _, line in ipairs(hunk_block.old_lines) do\n table.insert(virt_lines, { { pad_line(line), text.highlights.diff_delete } })\n end\n\n -- Calculate virtual line placement with boundary handling\n local virt_line_row, virt_lines_above = self:_calculate_virtual_line_placement(hunk_block)\n\n local extmark_opts = {\n virt_lines = virt_lines,\n virt_lines_above = virt_lines_above,\n priority = self.highlights.priority,\n }\n -- For pure deletions, store the extmark_id for navigation\n if hunk_block.type == \"deletion\" then\n hunk_block.extmark_id = vim.api.nvim_buf_set_extmark(\n self.state.bufnr,\n self.highlights.namespace_diff,\n virt_line_row,\n 0,\n extmark_opts\n )\n hunk_block.del_extmark_id = hunk_block.extmark_id\n else\n -- For changes, just add virtual lines (extmark_id already set above)\n hunk_block.del_extmark_id = vim.api.nvim_buf_set_extmark(\n self.state.bufnr,\n self.highlights.namespace_diff,\n virt_line_row,\n 0,\n extmark_opts\n )\n end\n end\nend\n\n--- Calculate proper placement for virtual lines handling file boundaries\n---@param hunk_block DiffHunk block to calculate placement for\n---@return integer virt_line_row The row to place the virtual line\n---@return boolean virt_lines_above Whether to place virtual lines above the target line\nfunction EditUI:_calculate_virtual_line_placement(hunk_block)\n local file_line_count = vim.api.nvim_buf_line_count(self.state.bufnr)\n local target_line = hunk_block.applied_start_line - 1 -- Convert to 0-based\n\n -- At start of file (line 0 or 1)\n if target_line <= 0 then\n if #hunk_block.new_lines > 0 then\n return #hunk_block.new_lines - 1, false -- Place at line 0, above (since below doesn't work at start)\n end\n return 0, false -- Place at line 0, below (since above doesn't work at start)\n end\n\n -- At end of file\n if target_line >= file_line_count then\n return file_line_count - 1, false -- Place at last line, below\n end\n\n -- Middle of file - place above the target line\n return target_line, true\nend\n\n-- Set up keybindings for diff operations (hunk-based)\nfunction EditUI:_setup_keybindings()\n local bufnr = self.state.bufnr\n\n local KEYBINDINGS = self.config.keybindings\n\n -- Store original keymaps before setting temporary ones\n self.state.original_keymaps = keymap_utils.store_original_keymaps(\"n\", KEYBINDINGS, bufnr)\n\n -- Accept current change\n vim.keymap.set({ \"n\" }, KEYBINDINGS.accept, function()\n self:_accept_current_hunk()\n end, { buffer = bufnr, desc = \"Accept current hunk\" })\n\n -- Reject current change\n vim.keymap.set({ \"n\" }, KEYBINDINGS.reject, function()\n self:_reject_current_hunk()\n end, { buffer = bufnr, desc = \"Reject current hunk\" })\n\n -- Navigate to next hunk\n vim.keymap.set({ \"n\" }, KEYBINDINGS.next, function()\n self:_navigate_next_hunk()\n end, { buffer = bufnr, desc = \"Go to next hunk\" })\n\n -- Navigate to previous hunk\n vim.keymap.set({ \"n\" }, KEYBINDINGS.prev, function()\n self:_navigate_prev_hunk()\n end, { buffer = bufnr, desc = \"Go to previous hunk\" })\n\n -- Accept all remaining changes\n vim.keymap.set({ \"n\" }, KEYBINDINGS.accept_all, function()\n self:_accept_all_remaining_hunks()\n end, { buffer = bufnr, desc = \"Accept all remaining hunks\" })\n\n -- Reject all remaining changes\n vim.keymap.set({ \"n\" }, KEYBINDINGS.reject_all, function()\n self:_reject_all_remaining_hunks()\n end, { buffer = bufnr, desc = \"Reject all remaining hunks\" })\nend\n\n-- Set up autocommands for buffer events\nfunction EditUI:_setup_autocmds()\n local bufnr = self.state.bufnr\n\n -- Update hints on cursor movement\n vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\" }, {\n buffer = bufnr,\n group = self.state.augroup,\n callback = vim.schedule_wrap(function()\n self:_update_hints()\n end),\n })\n\n -- Handle buffer save\n vim.api.nvim_create_autocmd({ \"BufWritePost\" }, {\n buffer = bufnr,\n group = self.state.augroup,\n callback = vim.schedule_wrap(function()\n self:_handle_save()\n end),\n })\n\n -- Handle buffer close\n vim.api.nvim_create_autocmd({ \"BufUnload\", \"BufWipeout\" }, {\n buffer = bufnr,\n group = self.state.augroup,\n callback = vim.schedule_wrap(function()\n self:_handle_buffer_close()\n end),\n })\nend\n\n-- Accept all remaining hunks\nfunction EditUI:_accept_all_remaining_hunks()\n if not self.state.hunk_blocks then\n return self:_complete_session()\n end\n\n for _, hunk in ipairs(self.state.hunk_blocks) do\n if not self.state.completed_hunks[hunk.hunk_id] then\n self:_accept_current_hunk(hunk)\n end\n end\n self:_complete_session()\nend\n\n-- Reject all remaining hunks\nfunction EditUI:_reject_all_remaining_hunks()\n if not self.state.hunk_blocks then\n return self:_complete_session()\n end\n\n for _, hunk in ipairs(self.state.hunk_blocks) do\n if not (self.state.completed_hunks and self.state.completed_hunks[hunk.hunk_id]) then\n self:_reject_current_hunk(hunk)\n end\n end\n self:_complete_session()\nend\n\nfunction EditUI:write_if_modified()\n local file = self.state.file_path\n local buf_state = vim.bo[self.state.bufnr]\n if file and (buf_state and buf_state.modified) then\n local ok, err = pcall(vim.cmd.write, file)\n if not ok and err:match(\"E212\") then\n local dir = vim.fn.fnamemodify(file, \":h\")\n if vim.fn.isdirectory(dir) == 0 then\n vim.fn.mkdir(dir, \"p\")\n end\n vim.cmd.write(file)\n end\n end\nend\n\n-- Navigate to next hunk\n---@return boolean success True if navigated to next hunk\nfunction EditUI:_navigate_next_hunk()\n if not self.state.hunk_blocks then\n return false\n end\n\n local current_index = self.state.current_hunk_index or 1\n\n -- Find next uncompleted hunk\n for i = current_index + 1, #self.state.hunk_blocks do\n local hunk = self.state.hunk_blocks[i]\n if not (self.state.completed_hunks and self.state.completed_hunks[hunk.hunk_id]) then\n if self:_navigate_to_hunk(i) then\n self.state.current_hunk_index = i\n return true\n end\n end\n end\n\n -- Wrap to beginning\n for i = 1, current_index do\n local hunk = self.state.hunk_blocks[i]\n if not (self.state.completed_hunks and self.state.completed_hunks[hunk.hunk_id]) then\n if self:_navigate_to_hunk(i) then\n self.state.current_hunk_index = i\n return true\n end\n end\n end\n\n return false -- No more hunks\nend\n\n-- Navigate to previous hunk\n---@return boolean success True if navigated to previous hunk\nfunction EditUI:_navigate_prev_hunk()\n if not self.state.hunk_blocks then\n return false\n end\n\n local current_index = self.state.current_hunk_index or 1\n\n -- Find previous uncompleted hunk\n for i = current_index - 1, 1, -1 do\n local hunk = self.state.hunk_blocks[i]\n if not (self.state.completed_hunks and self.state.completed_hunks[hunk.hunk_id]) then\n if self:_navigate_to_hunk(i) then\n self.state.current_hunk_index = i\n return true\n end\n end\n end\n\n -- Wrap to end\n for i = #self.state.hunk_blocks, current_index + 1, -1 do\n local hunk = self.state.hunk_blocks[i]\n if not (self.state.completed_hunks and self.state.completed_hunks[hunk.hunk_id]) then\n if self:_navigate_to_hunk(i) then\n self.state.current_hunk_index = i\n return true\n end\n end\n end\n\n return false -- No more hunks\nend\n\n-- Validate hunk block and return location info to avoid duplicate extmark fetching\n---@param hunk_block table Hunk block to validate\n---@return table result Validation result with location info\nfunction EditUI:_validate_hunk_block(hunk_block)\n -- Check if extmark_id exists\n if not hunk_block.extmark_id then\n return {\n status = \"no_extmark_id\",\n navigable = false,\n start_row = hunk_block.deletion_position or hunk_block.applied_start_line or 0,\n end_row = hunk_block.deletion_position or hunk_block.applied_end_line or 0,\n }\n end\n\n local extmark_details = vim.api.nvim_buf_get_extmark_by_id(\n self.state.bufnr,\n self.highlights.namespace_diff,\n hunk_block.extmark_id,\n { details = true }\n )\n\n -- Return both validation and location info\n local start_row = extmark_details[1] or 0\n local end_row = extmark_details[3] and extmark_details[3].end_row or start_row\n\n local result = {\n start_row = start_row,\n end_row = end_row,\n extmark_details = extmark_details,\n }\n\n -- Check if extmark exists\n if #extmark_details == 0 then\n result.status = \"extmark_missing\"\n result.navigable = false\n return result\n end\n\n -- Special handling for pure deletions\n if hunk_block.type == \"deletion\" then\n -- For deletions, extmark should point to virtual line with deletion marker\n result.status = \"deletion_marker_present\"\n result.navigable = true\n result.end_row = start_row -- Same line for deletion marker\n return result\n end\n\n -- Check if hunk was deleted (start == end but we expect multiple lines)\n if start_row == end_row and #hunk_block.new_lines > 1 then\n result.status = \"content_deleted\"\n result.navigable = false\n return result\n end\n\n -- Get current content in the range for additions and changes\n local current_lines = vim.api.nvim_buf_get_lines(self.state.bufnr, start_row, end_row, false)\n\n -- Check content status\n if vim.deep_equal(current_lines, hunk_block.new_lines) then\n result.status = \"matches_new\"\n result.navigable = true\n elseif vim.deep_equal(current_lines, hunk_block.old_lines) then\n result.status = \"matches_old\"\n result.navigable = true\n else\n result.status = \"user_modified\"\n result.navigable = true\n end\n return result\nend\n\n-- Navigate to specific hunk using validation result (avoids duplicate extmark fetching)\n---@param hunk_index integer Hunk index to navigate to\n---@return boolean success True if navigation was successful\nfunction EditUI:_navigate_to_hunk(hunk_index)\n if not self.state.hunk_blocks then\n return false\n end\n\n local hunk_block = self.state.hunk_blocks[hunk_index]\n if not hunk_block then\n return false\n end\n\n local validation = self:_validate_hunk_block(hunk_block)\n if not validation.navigable then\n -- Skip this hunk, try next\n return self:_find_next_navigable_hunk(hunk_index)\n end\n\n -- Use validation.start_row directly, no need to fetch extmark again\n local winid = self:_get_window_for_buffer()\n if winid then\n vim.api.nvim_win_set_cursor(winid, { validation.start_row + 1, 0 })\n vim.api.nvim_win_call(winid, function()\n vim.cmd(\"normal! zz\")\n end)\n return true\n end\n\n return false\nend\n\n-- Reject current hunk using validation result (avoids duplicate extmark fetching)\n---@param hunk_block table? Optional specific hunk to reject\nfunction EditUI:_reject_current_hunk(hunk_block)\n local target_hunk = hunk_block or self:_get_current_hunk()\n if not target_hunk then\n return\n end\n\n local validation = self:_validate_hunk_block(target_hunk)\n if not validation.navigable then\n -- Hunk is not available, just mark as completed\n self.state.completed_hunks[target_hunk.hunk_id] = \"skipped\"\n return\n end\n\n -- Handle different hunk types for rejection\n if target_hunk.type == \"deletion\" then\n -- For deletions, we need to restore the deleted content\n -- Insert the old lines at the deletion position\n local insert_pos = target_hunk.deletion_position or validation.start_row\n vim.api.nvim_buf_set_lines(\n self.state.bufnr,\n insert_pos - 1,\n insert_pos - 1, -- Insert without replacing\n false,\n target_hunk.old_lines\n )\n elseif target_hunk.type == \"addition\" then\n -- For additions, remove the added lines\n vim.api.nvim_buf_set_lines(\n self.state.bufnr,\n validation.start_row,\n validation.end_row,\n false,\n {} -- Remove lines\n )\n else\n -- For changes, replace new content with old content\n vim.api.nvim_buf_set_lines(\n self.state.bufnr,\n validation.start_row,\n validation.end_row,\n false,\n target_hunk.old_lines\n )\n end\n\n -- Mark as rejected and remove highlights\n self.state.completed_hunks = self.state.completed_hunks or {}\n self.state.completed_hunks[target_hunk.hunk_id] = \"rejected\"\n self:_remove_hunk_highlights(target_hunk)\n if not self:_navigate_next_hunk() then\n return self:_complete_session()\n end\nend\n\n-- Accept current hunk (just remove highlights and mark as accepted)\n---@param hunk_block table? Optional specific hunk to accept\nfunction EditUI:_accept_current_hunk(hunk_block)\n local target_hunk = hunk_block or self:_get_current_hunk()\n if not target_hunk then\n return\n end\n\n -- Mark as accepted and remove highlights\n self.state.completed_hunks = self.state.completed_hunks or {}\n self.state.completed_hunks[target_hunk.hunk_id] = \"accepted\"\n self:_remove_hunk_highlights(target_hunk)\n if not self:_navigate_next_hunk() then\n return self:_complete_session()\n end\nend\n\n-- Find next navigable hunk starting from given index\n---@param current_index integer Current hunk index\n---@return boolean success True if found and navigated to next hunk\nfunction EditUI:_find_next_navigable_hunk(current_index)\n if not self.state.hunk_blocks then\n return false\n end\n\n -- Search forward from current position\n for i = current_index + 1, #self.state.hunk_blocks do\n local hunk_block = self.state.hunk_blocks[i]\n if not self.state.completed_hunks[hunk_block.hunk_id] then\n local validation = self:_validate_hunk_block(hunk_block)\n if validation.navigable then\n return self:_navigate_to_hunk(i)\n end\n end\n end\n\n -- Wrap around to beginning\n for i = 1, current_index do\n local hunk_block = self.state.hunk_blocks[i]\n if not self.state.completed_hunks[hunk_block.hunk_id] then\n local validation = self:_validate_hunk_block(hunk_block)\n if validation.navigable then\n return self:_navigate_to_hunk(i)\n end\n end\n end\n\n return false -- No more navigable hunks\nend\n\n-- Get current hunk based on cursor position\n---@return DiffHunk? Current hunk block or nil if not found\nfunction EditUI:_get_current_hunk()\n if not self.state.hunk_blocks then\n return\n end\n\n local winid = self:_get_window_for_buffer()\n if not winid then\n return\n end\n\n local cursor_line = vim.api.nvim_win_get_cursor(winid)[1] - 1\n\n for _, hunk_block in ipairs(self.state.hunk_blocks) do\n if self.state.completed_hunks[hunk_block.hunk_id] then\n goto continue\n end\n\n local validation = self:_validate_hunk_block(hunk_block)\n if validation.navigable then\n if cursor_line >= validation.start_row and cursor_line <= validation.end_row then\n return hunk_block\n end\n end\n\n ::continue::\n end\nend\n\n-- Remove highlights for a specific hunk\n---@param hunk_block DiffHunk Hunk block to remove highlights from\nfunction EditUI:_remove_hunk_highlights(hunk_block)\n if hunk_block.extmark_id then\n pcall(vim.api.nvim_buf_del_extmark, self.state.bufnr, self.highlights.namespace_diff, hunk_block.extmark_id)\n hunk_block.extmark_id = nil\n end\n if hunk_block.del_extmark_id then\n pcall(vim.api.nvim_buf_del_extmark, self.state.bufnr, self.highlights.namespace_diff, hunk_block.del_extmark_id)\n hunk_block.extmark_id = nil\n end\n -- Clear current hint for the removed block's line\n vim.api.nvim_buf_clear_namespace(self.state.bufnr, self.highlights.namespace_hints, 0, -1)\nend\n\n-- Get window ID for the buffer\n---@return integer? winid Window ID or nil if not found\nfunction EditUI:_get_window_for_buffer()\n for _, winid in ipairs(vim.api.nvim_list_wins()) do\n if vim.api.nvim_win_get_buf(winid) == self.state.bufnr then\n return winid\n end\n end\n return nil\nend\n\n-- Restore original content for a block\n---@param block LocatedBlock Block to restore\nfunction EditUI:_restore_block_original_content(block)\n local start_line = block.applied_start_line or 1\n local end_line = block.applied_end_line or 1\n vim.api.nvim_buf_set_lines(self.state.bufnr, start_line - 1, end_line, false, block.location_result.found_lines)\n\n -- Update the block's position after restoration\n block.applied_end_line = start_line + #block.location_result.found_lines - 1\nend\n\n-- Update hint display (hunk-based)\nfunction EditUI:_update_hints()\n if not self.state or not self.state.hunk_blocks then\n return\n end\n\n vim.api.nvim_buf_clear_namespace(self.state.bufnr, self.highlights.namespace_hints, 0, -1)\n local current_hunk = self:_get_current_hunk()\n if not current_hunk then\n return\n end\n\n -- For all hunks of a block, show the block confidence\n local confidence = current_hunk.confidence or 0\n local current_index = self.state.current_hunk_index or 1\n local index = string.format(\"%d/%d\", current_index, #self.state.hunk_blocks)\n\n -- Get position from hunk validation for accurate placement\n local validation = self:_validate_hunk_block(current_hunk)\n local start_line = math.max(0, validation.start_row)\n\n -- If at start of buffer, place hint at a visible location\n if start_line == 0 then\n start_line = math.max(1, validation.end_row or 1)\n end\n local file_line_count = vim.api.nvim_buf_line_count(self.state.bufnr)\n -- -- At end of file\n if start_line >= file_line_count - 1 then\n start_line = file_line_count\n end\n\n vim.api.nvim_buf_set_extmark(self.state.bufnr, self.highlights.namespace_hints, start_line - 1, 0, {\n virt_text = self:_create_hint_line(confidence, index),\n virt_text_pos = \"right_align\",\n priority = self.highlights.priority,\n })\nend\n\n-- Handle buffer save\nfunction EditUI:_handle_save()\n -- If there are still pending hunks, treat save as accept all\n local has_pending = #vim.tbl_filter(function(hunk)\n return not self.state.completed_hunks[hunk.hunk_id]\n end, self.state.hunk_blocks) > 0\n\n if has_pending then\n return self:_accept_all_remaining_hunks()\n end\n self:_complete_session()\nend\n\n-- Handle buffer close\nfunction EditUI:_handle_buffer_close()\n if not self.state or self.state.has_completed then\n return\n end\n self.state.callbacks.on_cancel(\"User closed the editor without accepting the changes.\")\nend\n\n-- Complete the editing session\nfunction EditUI:_complete_session()\n if not self.state or self.state.has_completed then\n return\n end\n self.state.has_completed = true\n self:write_if_modified()\n vim.schedule(function()\n local origin_winnr = self.state.origin_winnr\n -- Signal completion to the session without arguments\n self.state.callbacks.on_complete()\n if self.config.go_to_origin_on_complete and origin_winnr and vim.api.nvim_win_is_valid(origin_winnr) then\n pcall(vim.api.nvim_set_current_win, origin_winnr)\n end\n end)\nend\n\n--- Generate block-focused summary for LLM\n--- @param final_content string Final content after edits\n--- @param config table Configuration options for summary generation\n--- @return string Summary of block results formatted for markdown\nfunction EditUI:_generate_block_summary(final_content, config)\n -- Handle case where no hunk blocks were generated (no actual changes)\n if not self.state.hunk_blocks or #self.state.hunk_blocks == 0 then\n return string.format(\n \"No changes were applied in `%s` file. Because, REPLACE content of all provided SEARCH/REPLACE block(s) was found identical to the content found at that location\",\n self.state.file_path\n )\n end\n\n -- Analyze block results\n local block_results = self:_analyze_block_results()\n\n -- Count block statuses\n local fully_applied = 0\n local partially_applied = 0\n local fully_rejected = 0\n\n for _, result in pairs(block_results) do\n if result.status == \"FULLY_APPLIED\" then\n fully_applied = fully_applied + 1\n elseif result.status == \"PARTIALLY_APPLIED\" then\n partially_applied = partially_applied + 1\n else\n fully_rejected = fully_rejected + 1\n end\n end\n\n local total_blocks = fully_applied + partially_applied + fully_rejected\n local summary = \"\"\n\n -- Simple messages for straightforward cases\n if fully_applied == total_blocks then\n summary = string.format(\"All %d block(s) were successfully applied to `%s`\", total_blocks, self.state.file_path)\n elseif fully_rejected == total_blocks then\n summary = string.format(\n \"All %d block(s) were rejected - no changes were applied to `%s`\",\n total_blocks,\n self.state.file_path\n )\n else\n -- Detailed breakdown for mixed results\n local applied_count = fully_applied + partially_applied\n summary = string.format(\n \"%d of %d block(s) were applied to `%s`\\n\\n\",\n applied_count,\n total_blocks,\n self.state.file_path\n )\n\n -- Add details for each block in order\n local sorted_blocks = {}\n for block_id, result in pairs(block_results) do\n table.insert(sorted_blocks, result)\n end\n table.sort(sorted_blocks, function(a, b)\n return a.block_id < b.block_id\n end)\n\n for _, result in ipairs(sorted_blocks) do\n summary = summary .. self:_format_block_result(result) .. \"\\n\\n\"\n end\n end\n\n -- Always add final diff\n if config.include_final_diff then\n summary = summary .. self:_create_final_diff_section(final_content)\n end\n\n return summary\nend\n\n--- Analyze hunk results grouped by parent blocks\n---@return table block_results\nfunction EditUI:_analyze_block_results()\n local block_results = {}\n\n -- Group hunks by parent block\n for _, hunk in ipairs(self.state.hunk_blocks) do\n local parent_id = hunk.parent_id\n if not block_results[parent_id] then\n block_results[parent_id] = {\n block_id = parent_id,\n rejected_lines = {},\n total_hunks = 0,\n accepted_hunks = 0,\n }\n end\n\n block_results[parent_id].total_hunks = block_results[parent_id].total_hunks + 1\n\n local status = self.state.completed_hunks[hunk.hunk_id] or \"accepted\"\n if status == \"accepted\" then\n block_results[parent_id].accepted_hunks = block_results[parent_id].accepted_hunks + 1\n else\n block_results[parent_id].rejected_lines = vim.deepcopy(hunk.new_lines)\n end\n end\n\n -- Determine status for each block\n for _, result in pairs(block_results) do\n if result.accepted_hunks == result.total_hunks then\n result.status = \"FULLY_APPLIED\"\n elseif result.accepted_hunks == 0 then\n result.status = \"REJECTED\"\n else\n result.status = \"PARTIALLY_APPLIED\"\n end\n end\n\n return block_results\nend\n\n--- Format individual block result for summary\n--- @param result table Block result containing status and details\n--- @return string Formatted block result for markdown\nfunction EditUI:_format_block_result(result)\n if result.status == \"FULLY_APPLIED\" then\n return string.format(\"### %s: FULLY APPLIED\\nAll changes from this block were accepted.\", result.block_id)\n elseif result.status == \"REJECTED\" then\n return string.format(\"### %s: REJECTED\\nAll changes from this block were rejected.\", result.block_id)\n else\n -- PARTIALLY_APPLIED\n local rejected_content = table.concat(result.rejected_lines, \"\\n\")\n return string.format(\n \"### %s: PARTIALLY APPLIED\\nThe following lines from your REPLACE content were NOT accepted by the user:\\n```\\n%s\\n```\",\n result.block_id,\n rejected_content\n )\n end\nend\n\n---Create final diff section only for edits\n---@param final_content string Final content after edits\n---@param original_content string? Original content (fallback to state if not provided)\n---@return string Final diff section formatted for markdown\nfunction EditUI:_create_final_diff_section(final_content, original_content)\n local function add_new_lines(content)\n if content:sub(-1) ~= \"\\n\" then\n return content .. \"\\n\"\n end\n return content\n end\n\n -- Use provided original content or fallback to state\n local orig_content = original_content or self.state.original_content\n\n -- Avoiding diff generation if the entire file is being replaced\n if self.state.is_replacing_entire_file then\n return \"\"\n end\n\n local diff_output = vim.trim(\n vim.diff(add_new_lines(orig_content), add_new_lines(final_content), { result_type = \"unified\", ctxlen = 1 })\n or \"\"\n )\n\n return string.format(\n \"\\n\\n### BEFORE vs AFTER EDIT SESSION DIFF for `%s`:\\nIMPORTANT: Carefully observe this diff to understand the changes applied in the edit session including user edits or formatters etc \\n```diff\\n%s\\n```\",\n self.state.file_path,\n diff_output\n )\nend\n\n--- Add diagnostic feedback to the summary\n--- @param summary string Initial summary text\n--- @param config table Configuration options for diagnostics\n--- @param callback function Callback to execute with the final summary\nfunction EditUI:_add_diagnostic_feedback(summary, config, callback)\n local lsp_feedback = \"\"\n local bufnr = self.state.bufnr\n local file_path = self.state.file_path\n if not config.send_diagnostics then\n return callback(summary)\n end\n vim.defer_fn(function()\n local min_severity = config.diagnostic_severity or vim.diagnostic.severity.WARN\n local all_diagnostics = vim.diagnostic.get(bufnr)\n local diagnostics = vim.tbl_filter(function(diag)\n return diag.severity <= min_severity\n end, all_diagnostics)\n if #diagnostics > 0 then\n lsp_feedback = string.format(\"\\n\\n## CURRENT DIAGNOSTICS FOR `%s` :\\n\", file_path)\n\n -- Get file content for context\n local file_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)\n\n -- Group diagnostics by line number\n local diag_by_line = {}\n for _, diag in ipairs(diagnostics) do\n local line_num = diag.lnum + 1 -- Convert to 1-based\n if not diag_by_line[line_num] then\n diag_by_line[line_num] = {}\n end\n table.insert(diag_by_line[line_num], diag)\n end\n\n -- Format each line with its diagnostics\n for line_num in vim.spairs(diag_by_line) do\n local line_content = file_lines[line_num] or \"\"\n local number = string.format(\"%d \", line_num)\n lsp_feedback = lsp_feedback .. string.format(\"\\n%s| %s\\n\", number, line_content)\n\n for _, diag in ipairs(diag_by_line[line_num]) do\n lsp_feedback = lsp_feedback\n .. string.format(\n string.rep(\" \", #number) .. \"| %s (%s from %s)\\n\",\n diag.message or \"No message\",\n vim.diagnostic.severity[diag.severity],\n diag.source or \"Unknown\"\n )\n end\n end\n end\n callback(summary .. lsp_feedback)\n end, config.wait_for_diagnostics or 0)\nend\n\n-- Generate comprehensive summary of the editing session\n---@param config table Options including final_content, original_content, config\n---@param callback function Callback to receive the summary string\nfunction EditUI:get_summary(config, callback)\n if not self.state then\n return callback(\"\")\n end\n\n local file_lines = vim.api.nvim_buf_get_lines(self.state.bufnr, 0, -1, false)\n local final_content = table.concat(file_lines, \"\\n\")\n\n local summary_parts = {}\n\n -- Generate session summary if enabled\n if config.include_session_summary then\n local session_summary = self:_generate_block_summary(final_content, config)\n if session_summary and session_summary ~= \"\" then\n table.insert(summary_parts, session_summary)\n end\n end\n\n local base_summary = table.concat(summary_parts, \"\\n\\n\")\n\n -- Add diagnostic feedback if enabled (asynchronous)\n if config.send_diagnostics then\n self:_add_diagnostic_feedback(base_summary, config, callback)\n else\n callback(base_summary)\n end\nend\n\n-- Cleanup UI resources\nfunction EditUI:cleanup()\n if not self.state then\n return\n end\n\n local bufnr = self.state.bufnr\n\n -- Clear namespaces\n if vim.api.nvim_buf_is_valid(bufnr) then\n vim.api.nvim_buf_clear_namespace(bufnr, self.highlights.namespace_diff, 0, -1)\n vim.api.nvim_buf_clear_namespace(bufnr, self.highlights.namespace_hints, 0, -1)\n\n -- Restore original keymaps and clean up temporary ones\n if self.state.original_keymaps then\n keymap_utils.restore_keymaps(\"n\", self.config.keybindings, bufnr, self.state.original_keymaps)\n end\n end\n\n -- Clean up autocommands\n pcall(vim.api.nvim_del_augroup_by_id, self.state.augroup)\n\n self.state = nil\nend\n\n--- Create a hint line for the current hunk\n--- @param confidence number Confidence percentage of the current hunk\n--- @param progress string Progress string in the format \"current/total\"\n--- @return table Hint line as a table of text segments with highlights\nfunction EditUI:_create_hint_line(confidence, progress)\n local KEYBINDINGS = self.config.keybindings\n local hint_line = {}\n local hl_type = confidence < 100 and \"warn\" or \"success\"\n table.insert(hint_line, { \"\", text.highlights[hl_type] })\n table.insert(hint_line, {\n string.format(\" %d%% │ %s \", confidence, progress),\n text.highlights[hl_type .. \"_fill\"],\n })\n\n local full_line = string.format(\n \" accept (%s) reject (%s) accept-all (%s) reject-all (%s) \",\n KEYBINDINGS.accept,\n KEYBINDINGS.reject,\n KEYBINDINGS.accept_all,\n KEYBINDINGS.reject_all\n )\n table.insert(hint_line, { full_line, \"ColorColumn\" })\n table.insert(hint_line, { \"\", text.highlights[hl_type] })\n return hint_line\nend\n\nreturn EditUI\n"], ["/mcphub.nvim/lua/mcphub/ui/views/marketplace.lua", "---[[\n--- Marketplace view for MCPHub UI\n--- Browse, search and install MCP servers\n---]]\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal View = require(\"mcphub.ui.views.base\")\nlocal utils = require(\"mcphub.utils\")\n\n---@class MarketplaceView: View\n---@field active_mode \"browse\"|\"details\" Current view mode\n---@field selected_server MarketplaceItem|nil Currently selected server\n---@field cursor_positions table\n---@field active_installation_index number Currently selected installation method index\nlocal MarketplaceView = setmetatable({}, {\n __index = View,\n})\nMarketplaceView.__index = MarketplaceView\n\nfunction MarketplaceView:new(ui)\n local instance = View:new(ui, \"marketplace\") -- Create base view with name\n instance = setmetatable(instance, MarketplaceView)\n\n -- Initialize state\n instance.active_mode = \"browse\"\n instance.selected_server = nil\n instance.cursor_positions = {\n browse_mode = nil, -- Will store [line, col]\n details_mode = nil, -- Will store [line, col]\n }\n -- Setup initial keymaps (mode-specific keymaps set in setup_active_mode)\n instance.keymaps = {}\n\n return instance\nend\n\n---Extract unique categories and tags from catalog items\n---@return string[]\nfunction MarketplaceView:get_available_categories()\n local categories = {}\n local seen = {}\n\n -- Get items from state\n local items = State.marketplace_state.catalog.items or {}\n\n for _, item in ipairs(items) do\n -- Add main category\n if item.category and not seen[item.category] then\n seen[item.category] = true\n table.insert(categories, item.category)\n end\n\n -- Add tags\n if item.tags then\n for _, tag in ipairs(item.tags) do\n if not seen[tag] then\n seen[tag] = true\n table.insert(categories, tag)\n end\n end\n end\n end\n\n -- Sort categories alphabetically\n table.sort(categories)\n\n return categories\nend\n\n--- Filter and sort catalog items\n---@param items MarketplaceItem[] List of items to filter and sort\n---@return MarketplaceItem[] Filtered and sorted items\nfunction MarketplaceView:filter_and_sort_items(items)\n if not items or #items == 0 then\n return {}\n end\n\n local filters = State.marketplace_state.filters\n local filtered = items\n\n -- Apply search filter with ranking\n if filters.search ~= \"\" and #filters.search > 0 then\n local ranked_items = {}\n local search_text = filters.search:lower()\n\n -- First pass: collect items with ranks\n for _, item in ipairs(filtered) do\n local rank = 5 -- Default rank (no match)\n\n if item.name then\n local name_lower = item.name:lower()\n if name_lower == search_text then\n rank = 1 -- Exact name match\n elseif name_lower:find(\"^\" .. search_text) then\n rank = 2 -- Name starts with search text\n elseif name_lower:find(search_text) then\n rank = 3 -- Name contains search text\n end\n end\n\n -- Check description only if we haven't found a name match\n if rank == 5 and item.description and item.description:lower():find(search_text) then\n rank = 4 -- Description match\n end\n\n -- Only include items that actually matched\n if rank < 5 then\n table.insert(ranked_items, {\n item = item,\n rank = rank,\n })\n end\n end\n\n -- Sort by rank\n table.sort(ranked_items, function(a, b)\n if a.rank ~= b.rank then\n return a.rank < b.rank\n end\n -- If ranks are equal, sort by name\n return (a.item.name or \"\"):lower() < (b.item.name or \"\"):lower()\n end)\n\n -- Extract just the items\n filtered = vim.tbl_map(function(ranked)\n return ranked.item\n end, ranked_items)\n return filtered\n end\n\n -- Apply category filter\n if filters.category ~= \"\" then\n filtered = vim.tbl_filter(function(item)\n -- Match against main category or tags\n return (item.category == filters.category) or (item.tags and vim.tbl_contains(item.tags, filters.category))\n end, filtered)\n end\n\n -- Sort results\n local sort_funcs = {\n newest = function(a, b)\n return (a.lastCommit or 0) > (b.lastCommit or 0)\n end,\n downloads = function(a, b)\n return #(a.installations or {}) > #(b.installations or {})\n end,\n stars = function(a, b)\n return (a.stars or 0) > (b.stars or 0)\n end,\n name = function(a, b)\n return (a.name or \"\"):lower() < (b.name or \"\"):lower()\n end,\n }\n\n if filters.sort and sort_funcs[filters.sort] then\n table.sort(filtered, sort_funcs[filters.sort])\n end\n\n return filtered\nend\n\nfunction MarketplaceView:before_enter()\n View.before_enter(self)\n self:setup_active_mode()\nend\n\n-- Add this to the MarketplaceView:after_enter() function\nfunction MarketplaceView:after_enter()\n View.after_enter(self)\n\n -- Restore appropriate cursor position for current mode\n local line_count = vim.api.nvim_buf_line_count(self.ui.buffer)\n if self.active_mode == \"browse\" and self.cursor_positions.browse_mode then\n local new_pos = {\n math.min(self.cursor_positions.browse_mode[1], line_count),\n self.cursor_positions.browse_mode[2],\n }\n vim.api.nvim_win_set_cursor(0, new_pos)\n elseif self.active_mode == \"details\" then\n local install_line = self.interactive_lines[1]\n vim.api.nvim_win_set_cursor(0, { install_line and install_line.line or 7, 0 })\n end\n\n local group = vim.api.nvim_create_augroup(\"MarketplaceView\", { clear = true })\n -- Set up autocmd for visual selection in details mode\n if self.active_mode == \"details\" then\n -- Clear any existing autocmds for this buffer\n vim.api.nvim_clear_autocmds({\n buffer = self.ui.buffer,\n group = group,\n })\n end\nend\n\nfunction MarketplaceView:before_leave()\n -- Store current position based on mode\n if self.active_mode == \"browse\" then\n self.cursor_positions.browse_mode = vim.api.nvim_win_get_cursor(0)\n else\n self.cursor_positions.details_mode = vim.api.nvim_win_get_cursor(0)\n end\n -- Clear visual mode keymap if it was set\n if self._visual_keymap_set then\n pcall(vim.api.nvim_buf_del_keymap, self.ui.buffer, \"v\", \"a\")\n self._visual_keymap_set = false\n end\n\n View.before_leave(self)\nend\n\nfunction MarketplaceView:setup_active_mode()\n local function enter_detail_mode()\n local cursor = vim.api.nvim_win_get_cursor(0)\n local server = self:get_server_at_line(cursor[1])\n if server then\n self.cursor_positions.browse_mode = cursor\n self.selected_server = server\n self.active_mode = \"details\"\n self.active_installation_index = 1\n self:setup_active_mode()\n self:draw()\n local install_line = self.interactive_lines[1]\n vim.api.nvim_win_set_cursor(0, { install_line and install_line.line or 7, 0 })\n end\n end\n local function go_to_browse_mode()\n self.cursor_positions.details_mode = vim.api.nvim_win_get_cursor(0)\n self.active_mode = \"browse\"\n self.selected_server = nil\n self:setup_active_mode()\n self:draw()\n -- Restore browse mode position\n if self.cursor_positions.browse_mode then\n vim.api.nvim_win_set_cursor(0, self.cursor_positions.browse_mode)\n end\n end\n local function install_server()\n local cursor = vim.api.nvim_win_get_cursor(0)\n local type, context = self:get_line_info(cursor[1])\n\n if type == \"install_with_method\" and not State:is_server_installed(self.selected_server.id) then\n -- Open installation editor directly\n self:handle_installation_selection(\n context --[[@as { server: MarketplaceItem, installation: MarketplaceInstallation }]]\n )\n elseif type == \"uninstall_server\" and State:is_server_installed(self.selected_server.id) then\n -- Show confirmation and uninstall\n if context then\n local server_id = context.server.id --[[@as string]]\n utils.confirm_and_delete_server(server_id, function()\n self.active_installation_index = 1\n end)\n end\n end\n end\n local function cycle_method(forward)\n if self.selected_server and self.selected_server.installations then\n local num_installations = #self.selected_server.installations\n if num_installations >= 1 then\n local is_installed = State:is_server_installed(self.selected_server.id)\n local max_index = is_installed and num_installations + 1 or num_installations\n\n if forward then\n self.active_installation_index = (self.active_installation_index % max_index) + 1\n else\n self.active_installation_index = ((self.active_installation_index - 2) % max_index) + 1\n end\n\n self:draw()\n -- Keep cursor on install/uninstall line\n if self.interactive_lines and #self.interactive_lines > 0 then\n for _, line_info in ipairs(self.interactive_lines) do\n if line_info.type == \"install_with_method\" or line_info.type == \"uninstall_server\" then\n vim.api.nvim_win_set_cursor(0, { line_info.line, 0 })\n break\n end\n end\n end\n end\n end\n end\n if self.active_mode == \"browse\" then\n self.keymaps = {\n [\"/\"] = {\n action = function()\n vim.ui.input({\n prompt = \"Search: \",\n }, function(input)\n local trimmed = input and vim.trim(input)\n if trimmed and #trimmed > 0 then -- Only update if input has content\n -- When searching, clear category filter\n local current = State.marketplace_state.filters or {}\n State:update({\n marketplace_state = {\n filters = {\n search = input,\n category = \"\", -- Clear category when searching\n sort = current.sort, -- Preserve sort\n },\n },\n }, \"marketplace\")\n self:focus_first_interactive_line()\n end\n end)\n end,\n desc = \"Search\",\n },\n [\"s\"] = {\n action = function()\n local sorts = {\n { text = \"Most Stars\", value = \"stars\" },\n -- { text = \"Most Installations\", value = \"downloads\" },\n { text = \"Recently Updated\", value = \"newest\" },\n { text = \"Name (A-Z)\", value = \"name\" },\n }\n vim.ui.select(sorts, {\n prompt = \"Sort by:\",\n format_item = function(item)\n return item.text\n end,\n }, function(choice)\n if choice then\n State:update({\n marketplace_state = {\n filters = {\n sort = choice.value,\n },\n },\n }, \"marketplace\")\n end\n end)\n end,\n desc = \"Sort\",\n },\n [\"c\"] = {\n action = function()\n local categories = self:get_available_categories()\n table.insert(categories, 1, \"All Categories\")\n\n vim.ui.select(categories, {\n prompt = \"Filter by category:\",\n }, function(choice)\n if choice then\n -- When selecting category, clear search filter\n local current = State.marketplace_state.filters or {}\n State:update({\n marketplace_state = {\n filters = {\n category = choice ~= \"All Categories\" and choice or \"\",\n search = \"\", -- Clear search when filtering by category\n sort = current.sort, -- Preserve sort\n },\n },\n }, \"marketplace\")\n self:focus_first_interactive_line()\n end\n end)\n end,\n desc = \"Category\",\n },\n [\"\"] = {\n action = function()\n -- Only clear filters if any are active\n local current = State.marketplace_state.filters or {}\n if current.category or #(current.search or \"\") > 0 then\n State:update({\n marketplace_state = {\n filters = {\n sort = current.sort, -- Preserve sort\n search = \"\",\n category = \"\",\n },\n },\n }, \"marketplace\")\n end\n end,\n desc = \"Clear filters\",\n },\n [\"l\"] = {\n action = enter_detail_mode,\n desc = \"View details\",\n },\n [\"\"] = {\n action = enter_detail_mode,\n desc = \"View details\",\n },\n }\n else\n self.keymaps = {\n [\"\"] = {\n action = go_to_browse_mode,\n desc = \"Back to list\",\n },\n [\"l\"] = {\n action = function()\n cycle_method(true)\n end,\n desc = \"Switch method\",\n },\n [\"h\"] = {\n action = function()\n cycle_method(false)\n end,\n desc = \"Switch method\",\n },\n [\"\"] = {\n action = install_server,\n desc = \"Install/Uninstall\",\n },\n }\n end\n\n -- Add silent keymap aliases for common navigation keys\n if self.active_mode == \"browse\" then\n -- In browse mode, add silent alias for viewing details\n self:add_keymap_alias(\"o\", \"l\") -- 'o' as alias for view details\n elseif self.active_mode == \"details\" then\n -- In details mode, add silent aliases for method cycling\n self:add_keymap_alias(\"\", \"l\") -- Tab as alias for next method\n self:add_keymap_alias(\"\", \"h\") -- Shift+Tab as alias for previous method\n end\n self:apply_keymaps()\nend\n\n--- Handle installation selection from details mode\n---@param context { server: MarketplaceItem, installation: MarketplaceInstallation }\nfunction MarketplaceView:handle_installation_selection(context)\n local server = context.server\n local installation = context.installation\n\n local ok, config = utils.json_decode(installation.config or \"{}\")\n -- Create server config object with the server ID\n local server_config = {\n [server.id] = ok and config or {}, -- Use parsed config or empty table\n }\n\n -- Open the editor with the pre-populated config\n utils.open_server_editor({\n title = \"Install \" .. server.name .. \" (\" .. installation.name .. \")\",\n placeholder = utils.pretty_json(vim.json.encode(server_config)),\n start_insert = false,\n go_to_placeholder = true, -- Position cursor at first ${} placeholder\n ask_for_source = true,\n virtual_lines = {\n {\n Text.icons.hint\n .. \" ${VARIABLES} will be resolved from config.global_env or environment if not replaced\",\n Text.highlights.muted,\n },\n { Text.icons.hint .. \" ${cmd: echo 'secret'} will run command and replace ${}\", Text.highlights.muted },\n },\n on_success = function()\n -- Switch to main view and browse mode after successful installation\n self.active_mode = \"browse\"\n self.selected_server = nil\n self.active_installation_index = nil\n self.ui:switch_view(\"main\")\n end,\n })\nend\n\n--- Render installation details for a server\n---@param installation MarketplaceInstallation\n---@param line_offset number\nfunction MarketplaceView:render_installation_details(installation, line_offset)\n local lines = {}\n installation = installation or {}\n\n -- Configuration preview (no indent)\n if installation.config then\n vim.list_extend(lines, Text.render_json(installation.config))\n table.insert(lines, Text.pad_line(NuiLine()))\n end\n\n -- Placeholders section (only show if parameters exist)\n if installation.parameters and #installation.parameters > 0 then\n table.insert(lines, Text.pad_line(NuiLine():append(\"Placeholders\", Text.highlights.muted)))\n\n for _, param in ipairs(installation.parameters) do\n -- Single line: key: placeholder\n local placeholder_line = NuiLine()\n if param.required ~= false then\n placeholder_line:append(\"* \", Text.highlights.error)\n else\n placeholder_line:append(\" \", Text.highlights.error)\n end\n placeholder_line:append(param.key, Text.highlights.json_property)\n placeholder_line:append(\": \", Text.highlights.json_punctuation)\n if param.placeholder then\n placeholder_line:append(param.placeholder, Text.highlights.muted)\n end\n table.insert(lines, Text.pad_line(placeholder_line))\n end\n\n table.insert(lines, Text.pad_line(NuiLine()))\n end\n\n return lines\nend\n\n--- Render current server configuration in details mode\n---@param server MarketplaceItem\n---@param line_offset number\nfunction MarketplaceView:render_current_server_config(server, line_offset)\n local lines = {}\n\n local config_manager = require(\"mcphub.utils.config_manager\")\n local server_config = config_manager.get_server_config(server.id, true) or {}\n\n if server_config then\n -- Render current config as JSON\n vim.list_extend(lines, Text.render_json(vim.json.encode(server_config)))\n table.insert(lines, Text.pad_line(NuiLine()))\n else\n table.insert(lines, Text.pad_line(NuiLine():append(\"Current configuration not found\", Text.highlights.warn)))\n table.insert(lines, Text.pad_line(NuiLine()))\n end\n\n return lines\nend\n\n--- Helper to find server at cursor line\n--- @param line number Line number to check\n---@return MarketplaceItem|nil\nfunction MarketplaceView:get_server_at_line(line)\n local type, context = self:get_line_info(line)\n if type == \"server\" and (context and context.id) then\n -- Look up server in catalog by id\n for _, server in ipairs(State.marketplace_state.catalog.items) do\n if server.id == context.id then\n return server\n end\n end\n end\n return nil\nend\n\nfunction MarketplaceView:render_header_controls()\n local lines = {}\n local width = self:get_width() - (Text.HORIZONTAL_PADDING * 2)\n local filters = State.marketplace_state.filters\n\n -- Create status sections showing current filters and controls\n local left_section = NuiLine()\n :append(Text.icons.sort .. \" \", Text.highlights.muted)\n :append(\"(\", Text.highlights.muted)\n :append(\"s\", Text.highlights.keymap)\n :append(\")\", Text.highlights.muted)\n :append(\"ort: \", Text.highlights.muted)\n :append(filters.sort == \"\" and \"stars\" or filters.sort, Text.highlights.info)\n :append(\" \", Text.highlights.muted)\n :append(Text.icons.tag .. \" \", Text.highlights.muted)\n :append(\"(\", Text.highlights.muted)\n :append(\"c\", Text.highlights.keymap)\n :append(\")\", Text.highlights.muted)\n :append(\"ategory: \", Text.highlights.muted)\n :append(filters.category == \"\" and \"All\" or filters.category, Text.highlights.info)\n\n -- Show filter clear hint if any filters active\n local has_filters = filters.category ~= \"\" or #(filters.search or \"\") > 0\n if has_filters then\n left_section\n :append(\" (\", Text.highlights.muted)\n :append(\"\", Text.highlights.keymap)\n :append(\" to clear)\", Text.highlights.muted)\n end\n\n local right_section =\n NuiLine():append(\"/\", Text.highlights.keymap):append(\" Search: \", Text.highlights.muted):append(\n filters.search == \"\" and \"\" or filters.search,\n #(filters.search or \"\") > 0 and Text.highlights.info or Text.highlights.muted\n )\n\n -- Calculate padding needed between sections\n local total_content_width = left_section:width() + right_section:width()\n local padding = width - total_content_width\n\n -- Combine sections with padding\n local controls_line = NuiLine():append(left_section):append(string.rep(\" \", padding)):append(right_section)\n\n table.insert(lines, Text.pad_line(controls_line))\n\n return lines\nend\n\n--- Render a server card for the marketplace\n---@param server MarketplaceItem\n---@param index number\n---@param line_offset number\nfunction MarketplaceView:render_server_card(server, index, line_offset)\n local lines = {}\n local is_installed = State:is_server_installed(server.id)\n\n -- Create server name section (left part)\n local name_section = NuiLine():append(\n tostring(index) .. \") \" .. server.name,\n is_installed and Text.highlights.success or Text.highlights.title\n )\n\n -- Show checkmark if installed\n if is_installed then\n name_section:append(\" \", Text.highlights.muted):append(Text.icons.install, Text.highlights.success)\n end\n\n -- Create metadata section (right part)\n local meta_section = NuiLine()\n\n -- Add featured badge if server is featured\n if server.featured then\n meta_section:append(Text.icons.sparkles .. \" \", Text.highlights.success)\n end\n\n -- Show stars and installations count\n meta_section\n :append(Text.icons.favorite, Text.highlights.muted)\n :append(\" \" .. (server.stars or \"0\"), Text.highlights.muted)\n :append(\" \", Text.highlights.muted)\n\n -- Calculate padding between name and metadata\n local padding = 2 -- width - (name_section:width() + meta_section:width())\n\n -- Combine name and metadata with padding\n local title_line = NuiLine():append(name_section):append(string.rep(\" \", padding)):append(meta_section)\n\n -- Track line for server selection (storing only id)\n self:track_line(line_offset, \"server\", {\n type = \"server\",\n id = server.id,\n hint = \"[ Details]\",\n })\n table.insert(lines, Text.pad_line(title_line))\n\n if server.description then\n table.insert(lines, Text.pad_line(NuiLine():append(server.description, Text.highlights.muted)))\n end\n\n table.insert(lines, Text.pad_line(NuiLine()))\n return lines\nend\n\n--- Render marketplace in browse mode\n--- @param line_offset number Offset to apply to line numbers for tracking\nfunction MarketplaceView:render_browse_mode(line_offset)\n local lines = {}\n\n -- Show appropriate state\n local state = State.marketplace_state\n if state.status == \"loading\" or state.status == \"empty\" then\n table.insert(lines, Text.pad_line(NuiLine():append(\"Loading marketplace catalog...\", Text.highlights.muted)))\n elseif state.status == \"error\" then\n table.insert(\n lines,\n Text.pad_line(\n NuiLine()\n :append(Text.icons.error .. \" \", Text.highlights.error)\n :append(\"Failed to load marketplace\", Text.highlights.error)\n )\n )\n else\n -- Get filtered and sorted items\n local all_items = state.catalog.items or {}\n local filtered_items = self:filter_and_sort_items(all_items)\n\n -- Show result count if filters are active\n if #(state.filters.search or \"\") > 0 or state.filters.category ~= \"\" then\n local count_line = NuiLine()\n :append(\"Found \", Text.highlights.muted)\n :append(tostring(#filtered_items), Text.highlights.info)\n :append(\" of \", Text.highlights.muted)\n :append(tostring(#all_items), Text.highlights.muted)\n :append(\" servers\", Text.highlights.muted)\n table.insert(lines, Text.pad_line(count_line))\n table.insert(lines, Text.empty_line())\n end\n\n -- Show filtered catalog\n if #filtered_items == 0 then\n if #all_items == 0 then\n table.insert(\n lines,\n Text.pad_line(NuiLine():append(\"No servers found in marketplace\", Text.highlights.muted))\n )\n else\n table.insert(lines, Text.pad_line(NuiLine():append(\"No matching servers found\", Text.highlights.muted)))\n end\n else\n for i, server in ipairs(filtered_items) do\n vim.list_extend(lines, self:render_server_card(server, i, #lines + line_offset + 1))\n end\n end\n end\n\n local info_line = NuiLine()\n info_line:append(Text.icons.bug .. \" Report issues or suggest changes: \", Text.highlights.title)\n info_line:append(\"https://github.com/ravitemer/mcp-registry\", Text.highlights.link)\n table.insert(lines, Text.pad_line(info_line))\n return lines\nend\n\nfunction MarketplaceView:render_details_mode(line_offset)\n local lines = {}\n local server = self.selected_server\n if not server then\n return lines\n end\n\n -- Description\n if server.description then\n vim.list_extend(lines, vim.tbl_map(Text.pad_line, Text.multiline(server.description, Text.highlights.muted)))\n end\n\n table.insert(lines, Text.empty_line())\n\n -- Server info section\n local info_lines = {\n {\n label = \"URL \",\n icon = Text.icons.link,\n value = server.url,\n is_url = true,\n },\n {\n label = \"ID \",\n icon = Text.icons.info,\n value = server.id,\n },\n {\n label = \"Author \",\n icon = Text.icons.octoface,\n value = server.author or \"Unknown\",\n },\n }\n\n -- Add category and tags together\n if server.category then\n local category_value = server.category\n if type(server.tags) == \"table\" and #server.tags > 0 then\n category_value = category_value .. \" [\" .. table.concat(server.tags, \", \") .. \"]\"\n end\n table.insert(info_lines, {\n label = \"Tags \",\n icon = Text.icons.tag,\n value = server.category,\n suffix = type(server.tags) == \"table\"\n and #server.tags > 0\n and (\" [\" .. table.concat(server.tags, \", \") .. \"]\")\n or nil,\n })\n end\n\n -- Render info lines\n for _, info in ipairs(info_lines) do\n if info.value then\n local line = NuiLine()\n :append(info.icon .. \" \", Text.highlights.title)\n :append(info.label .. \" : \", Text.highlights.muted)\n :append(info.value, info.is_url and Text.highlights.link or info.highlight or Text.highlights.info)\n\n if info.suffix then\n line:append(info.suffix, Text.highlights.muted)\n end\n\n table.insert(lines, Text.pad_line(line))\n end\n end\n table.insert(lines, Text.pad_line(NuiLine()))\n\n -- Install section\n if server.id then\n local is_installed = State:is_server_installed(server.id)\n\n if is_installed then\n -- Create uninstall button with Current as first tab\n local uninstall_line = NuiLine()\n uninstall_line:append(Text.icons.uninstall .. \" Uninstall: \", Text.highlights.error)\n\n -- Add Current as index 0 (special case)\n uninstall_line:append(\" \")\n local current_active = self.active_installation_index == 1\n local current_highlight = current_active and Text.highlights.button_active\n or Text.highlights.button_inactive\n uninstall_line:append(\" Current Config \", current_highlight)\n\n if #server.installations > 0 then\n uninstall_line:append(\" \" .. Text.icons.vertical_bar, Text.highlights.muted)\n uninstall_line:append(\" Available: \", Text.highlights.muted)\n end\n -- Add installation method tabs\n for i, installation in ipairs(server.installations) do\n uninstall_line:append(\" \")\n\n local is_active = self.active_installation_index == (i + 1)\n local tab_highlight = is_active and Text.highlights.button_active or Text.highlights.button_inactive\n\n uninstall_line:append(\" \" .. installation.name .. \" \", tab_highlight)\n end\n table.insert(lines, Text.pad_line(uninstall_line))\n\n -- Track the uninstall line for interaction\n self:track_line(#lines + line_offset, \"uninstall_server\", {\n type = \"uninstall_server\",\n server = server,\n hint = \"[ Uninstall, Switch Method]\",\n })\n\n table.insert(lines, Text.pad_line(NuiLine()))\n -- local prereq_line = NuiLine()\n -- prereq_line:append(\"PREVIEW \", Text.highlights.muted)\n -- table.insert(lines, Text.pad_line(prereq_line))\n table.insert(lines, self:divider())\n\n -- Show details based on active tab\n if self.active_installation_index == 1 then\n -- Show current server configuration when Current tab is active\n vim.list_extend(lines, self:render_current_server_config(server, line_offset))\n else\n -- Show installation details when an installation method is active\n local active_installation = server.installations[self.active_installation_index - 1]\n if active_installation then\n vim.list_extend(lines, self:render_installation_details(active_installation, line_offset))\n end\n end\n else\n -- Show installation interface\n if server.installations and #server.installations > 0 then\n local active_installation = server.installations[self.active_installation_index]\n\n -- Create install button with method tabs\n local install_line = NuiLine()\n install_line:append(Text.icons.install .. \" Install \", Text.highlights.success)\n install_line:append(\"using: \", Text.highlights.muted)\n\n -- Add installation method tabs\n for i, installation in ipairs(server.installations) do\n if i > 1 then\n install_line:append(\" \")\n end\n\n local is_active = i == self.active_installation_index\n local tab_highlight = is_active and Text.highlights.button_active or Text.highlights.button_inactive\n\n install_line:append(\" \" .. installation.name .. \" \", tab_highlight)\n end\n\n table.insert(lines, Text.pad_line(install_line))\n\n -- Track the install line for interaction\n self:track_line(#lines + line_offset, \"install_with_method\", {\n type = \"install_with_method\",\n server = server,\n installation = active_installation,\n hint = \"[ Install, Switch Method]\",\n })\n\n table.insert(lines, Text.pad_line(NuiLine()))\n\n -- Show prerequisites before divider (single line)\n -- if active_installation.prerequisites and #active_installation.prerequisites > 0 then\n -- local prereq_line = NuiLine()\n -- prereq_line:append(\"Requires: \", Text.highlights.muted)\n -- prereq_line:append(table.concat(active_installation.prerequisites, \", \"), Text.highlights.warn)\n -- table.insert(lines, Text.pad_line(prereq_line))\n -- end\n\n -- local prereq_line = NuiLine()\n -- prereq_line:append(\"PREVIEW \", Text.highlights.muted)\n -- table.insert(lines, Text.pad_line(prereq_line))\n table.insert(lines, self:divider())\n\n -- Show active installation details\n vim.list_extend(lines, self:render_installation_details(active_installation, line_offset))\n else\n table.insert(\n lines,\n Text.pad_line(NuiLine():append(\"No installation methods available\", Text.highlights.warn))\n )\n end\n end\n end\n\n -- Show info links\n local info_line = NuiLine()\n info_line:append(\"For more information, visit: \", Text.highlights.muted)\n info_line:append(server.url, Text.highlights.muted)\n table.insert(lines, Text.pad_line(info_line))\n\n local bug_line = NuiLine()\n bug_line:append(\"Report issues or suggest changes: \", Text.highlights.muted)\n bug_line:append(\"https://github.com/ravitemer/mcp-registry\", Text.highlights.muted)\n table.insert(lines, Text.pad_line(bug_line))\n return lines\nend\n\nfunction MarketplaceView:render()\n -- Handle special states from base view\n if State.setup_state == \"failed\" or State.setup_state == \"in_progress\" or State.setup_state == \"not_started\" then\n return View.render(self)\n end\n -- Get base header\n local lines = self:render_header(false)\n\n -- Add title/breadcrumb\n if self.active_mode == \"browse\" then\n -- Render controls\n vim.list_extend(lines, self:render_header_controls())\n elseif self.selected_server then\n local is_installed = State:is_server_installed(self.selected_server.id)\n local breadcrumb = NuiLine():append(\"Marketplace > \", Text.highlights.muted):append(\n self.selected_server.name,\n is_installed and Text.highlights.success or Text.highlights.title\n )\n if is_installed then\n breadcrumb:append(\" \", Text.highlights.muted):append(Text.icons.install, Text.highlights.success)\n end\n if self.selected_server.stars and self.selected_server.stars > 0 then\n breadcrumb:append(\n \" (\" .. Text.icons.favorite .. \" \" .. tostring(self.selected_server.stars) .. \")\",\n Text.highlights.muted\n )\n end\n table.insert(lines, Text.pad_line(breadcrumb))\n else\n -- Fallback if server not loaded yet\n local breadcrumb = NuiLine():append(\"Marketplace\", Text.highlights.title)\n table.insert(lines, Text.pad_line(breadcrumb))\n end\n table.insert(lines, self:divider())\n\n -- Calculate line offset from header\n local line_offset = #lines\n\n -- Render current mode with line offset\n if self.active_mode == \"browse\" then\n vim.list_extend(lines, self:render_browse_mode(line_offset))\n else\n vim.list_extend(lines, self:render_details_mode(line_offset))\n end\n\n return lines\nend\n\nfunction MarketplaceView:focus_first_interactive_line()\n vim.schedule(function()\n if self.interactive_lines and #self.interactive_lines > 0 then\n vim.api.nvim_win_set_cursor(0, { self.interactive_lines[1].line, 0 })\n end\n end)\nend\n\nreturn MarketplaceView\n"], ["/mcphub.nvim/lua/mcphub/utils/handlers.lua", "local Error = require(\"mcphub.utils.errors\")\nlocal State = require(\"mcphub.state\")\nlocal constants = require(\"mcphub.utils.constants\")\nlocal log = require(\"mcphub.utils.log\")\nlocal utils = require(\"mcphub.utils\")\n\nlocal M = {}\n\nlocal function format_config_changes(changes)\n local removed = changes.removed or {}\n local added = changes.added or {}\n local modified = changes.modified or {}\n local msg = \"\"\n if #added > 0 then\n msg = msg .. \"Added:\\n\"\n for _, item in ipairs(added) do\n msg = msg .. string.format(\" - %s\\n\", item)\n end\n end\n if #modified > 0 then\n msg = msg .. \"Modified:\\n\"\n for _, item in ipairs(modified) do\n msg = msg .. string.format(\" - %s\\n\", item)\n end\n end\n if #removed > 0 then\n msg = msg .. \"Removed:\\n\"\n for _, item in ipairs(removed) do\n msg = msg .. string.format(\" - %s\\n\", item)\n end\n end\n return msg\nend\n\n-- SSE Event handlers\nM.SSEHandlers = {\n ---@param event string Event type\n ---@param data table Event data\n ---@param hub MCPHub.Hub Hub instance\n handle_sse_event = function(event, data, hub)\n local is_ui_shown = State.ui_instance and State.ui_instance.is_shown or false\n if event == constants.EventTypes.HEARTBEAT then\n log.trace(\"Heartbeat event received\")\n else\n log.debug(\n string.format(\n \"Event: %s %s \",\n event,\n (data.type or data.state) and \": \" .. (data.type or data.state) or \"\"\n )\n )\n end\n if event == constants.EventTypes.HUB_STATE then\n local state = data.state\n if state then\n State:update_hub_state(state)\n end\n if state == constants.HubState.ERROR then\n hub:handle_hub_stopped(\"Hub entered error state: \" .. (data.message or \"unknown error\"))\n elseif state == constants.HubState.STOPPING then\n hub:handle_hub_stopping()\n elseif state == constants.HubState.STOPPED then\n hub:handle_hub_stopped(\"Hub stopped\")\n elseif state == constants.HubState.RESTARTING then\n hub:handle_hub_restarting()\n elseif state == constants.HubState.READY or state == constants.HubState.RESTARTED then\n hub:handle_hub_ready()\n end\n elseif event == constants.EventTypes.SUBSCRIPTION_EVENT then\n local is_capability_type = vim.tbl_contains({\n constants.SubscriptionTypes.TOOL_LIST_CHANGED,\n constants.SubscriptionTypes.RESOURCE_LIST_CHANGED,\n constants.SubscriptionTypes.PROMPT_LIST_CHANGED,\n }, data.type)\n if is_capability_type then\n hub:handle_capability_updates(data)\n elseif data.type == constants.SubscriptionTypes.CONFIG_CHANGED then\n -- if not is_ui_shown then\n -- local has_significant_changes = data.isSignificant == true\n -- if not has_significant_changes then\n -- vim.notify(\"MCP Hub Config Changed: No Significant changes found\", vim.log.levels.INFO, {\n -- title = \"MCP Hub\",\n -- })\n -- end\n -- end\n hub:reload_config()\n elseif data.type == constants.SubscriptionTypes.SERVERS_UPDATING then\n if not is_ui_shown then\n vim.notify(\"MCP Hub Config Changed\", vim.log.levels.INFO)\n end\n hub:refresh()\n elseif data.type == constants.SubscriptionTypes.SERVERS_UPDATED then\n if not is_ui_shown then\n vim.notify(\n \"MCP Servers Updated:\\n\\n\" .. format_config_changes(data.changes or {}),\n vim.log.levels.INFO\n )\n end\n hub:refresh()\n elseif data.type == constants.SubscriptionTypes.WORKSPACES_UPDATED then\n hub:refresh()\n end\n elseif event == constants.EventTypes.LOG then\n -- Use message timestamp if valid ISO string, otherwise system time\n local timestamp = vim.loop.now()\n if data.timestamp then\n -- Try to convert ISO string to unix timestamp\n local success, ts = pcall(function()\n return vim.fn.strptime(\"%Y-%m-%dT%H:%M:%S\", data.timestamp)\n end)\n if success then\n timestamp = ts\n end\n end\n State:add_server_output({\n type = data.type,\n message = data.message,\n code = data.code,\n timestamp = timestamp,\n data = data.data,\n })\n -- Handle errors specially\n if data.type == \"error\" then\n local error_obj = Error(\"SERVER\", data.code or Error.Types.SERVER.CONNECTION, data.message, data.data)\n State:add_error(error_obj)\n end\n end\n end,\n}\n\n-- Parameter type handlers for validation and conversion\nM.TypeHandlers = {\n string = {\n validate = function(value)\n return type(value) == \"string\"\n end,\n convert = function(value)\n return tostring(value)\n end,\n format = function()\n return \"string\"\n end,\n },\n number = {\n validate = function(value)\n return tonumber(value) ~= nil\n end,\n convert = function(value)\n return tonumber(value)\n end,\n format = function()\n return \"number\"\n end,\n },\n integer = {\n validate = function(value)\n local num = tonumber(value)\n return num and math.floor(num) == num\n end,\n convert = function(value)\n return math.floor(tonumber(value) and tonumber(value) or 0)\n end,\n format = function()\n return \"integer\"\n end,\n },\n boolean = {\n validate = function(value)\n return value == \"true\" or value == \"false\"\n end,\n convert = function(value)\n return value == \"true\"\n end,\n format = function()\n return \"boolean\"\n end,\n },\n object = {\n validate = function(value, schema)\n -- Parse JSON object string and validate each property\n -- FIXME: need to implement proper validation for objects\n local ok, obj = utils.json_decode(value)\n if not ok or type(obj) ~= \"table\" then\n return false\n end\n return true\n end,\n format = function(schema)\n if schema.properties then\n local props = {}\n for k, v in pairs(schema.properties) do\n if v.type then\n local type_handler = M.TypeHandlers[v.type]\n table.insert(\n props,\n string.format(\"%s: %s\", k, type_handler and type_handler.format(v) or v.type)\n )\n elseif v.anyOf then\n table.insert(\n props,\n string.format(\n \"%s: anyOf(%s)\",\n k,\n vim.iter(v.anyOf)\n :map(function(item)\n return vim.inspect(item.type or \"unknown\")\n end)\n :join(\",\")\n )\n )\n else\n table.insert(props, string.format(\"%s: %s\", k, \"unknown\"))\n end\n end\n return string.format(\"{%s}\", table.concat(props, \", \"))\n end\n return \"object\"\n end,\n convert = function(value)\n local ok, result = utils.json_decode(value)\n return ok and result or {}\n end,\n },\n array = {\n validate = function(value, schema)\n -- Parse JSON array string and validate each item\n local ok, arr = utils.json_decode(value)\n if not ok or type(arr) ~= \"table\" then\n return false\n end\n -- If items has enum, validate against allowed values\n if schema.items and schema.items.enum then\n for _, item in ipairs(arr) do\n if not vim.tbl_contains(schema.items.enum, item) then\n return false\n end\n end\n end\n -- If items has type, validate each item's type\n if schema.items and schema.items.type then\n local item_validator = M.TypeHandlers[schema.items.type].validate\n for _, item in ipairs(arr) do\n if not item_validator(item, schema.items) then\n return false\n end\n end\n end\n return true\n end,\n convert = function(value)\n local ok, result = utils.json_decode(value)\n return ok and result or {}\n end,\n format = function(schema)\n if schema.items then\n if schema.items.enum then\n return string.format(\n \"[%s]\",\n table.concat(\n vim.tbl_map(function(v)\n return string.format(\"%q\", v)\n end, schema.items.enum),\n \", \"\n )\n )\n elseif schema.items.type then\n return string.format(\"%s[]\", M.TypeHandlers[schema.items.type].format(schema.items))\n end\n end\n return \"array\"\n end,\n },\n}\n\n--- API response handlers\nM.ResponseHandlers = {\n --- Process API errors and create structured error objects\n --- @param error table|string Error from API\n --- @param context? table Additional context to include\n --- @return MCPError Structured error object\n process_error = function(error, context)\n if type(error) == \"table\" then\n if error.code and error.message then\n -- Already structured error\n if context then\n error.data = vim.tbl_extend(\"force\", error.data or {}, context)\n end\n return Error(\"SERVER\", Error.Types.SERVER.API_ERROR, vim.inspect(error), context)\n end\n -- Table error without proper structure\n return Error(\"SERVER\", Error.Types.SERVER.API_ERROR, vim.inspect(error), context)\n end\n -- String error\n return Error(\"SERVER\", Error.Types.SERVER.API_ERROR, error, context)\n end,\n\n --- Handle curl specific errors\n --- @param response table Curl response\n --- @param context table Request context\n --- @return MCPError|nil error Structured error if any\n handle_curl_error = function(response, context)\n if not response then\n return Error(\"SERVER\", Error.Types.SERVER.CURL_ERROR, \"No response from server\", context)\n end\n\n if response.exit ~= 0 then\n local error_code = ({\n [7] = Error.Types.SERVER.CONNECTION,\n [28] = Error.Types.SERVER.TIMEOUT,\n })[response.exit] or Error.Types.SERVER.CURL_ERROR\n\n local error_msg = ({\n [7] = \"Connection refused - Server not running\",\n [28] = \"Request timed out\",\n })[response.exit] or string.format(\"Request failed (code %d)\", response.exit or 0)\n\n return Error(\n \"SERVER\",\n error_code,\n error_msg,\n vim.tbl_extend(\"force\", context, {\n exit_code = response.exit,\n })\n )\n end\n\n return nil\n end,\n\n --- Handle HTTP error responses\n --- @param response table HTTP response\n --- @param context table Request context\n --- @return MCPError|nil error Structured error if any\n handle_http_error = function(response, context)\n if response.status < 400 then\n return nil\n end\n\n local ok, parsed_error = utils.json_decode(response.body)\n if ok and parsed_error.error then\n return Error(\n \"SERVER\",\n parsed_error.code or Error.Types.SERVER.API_ERROR,\n parsed_error.error,\n parsed_error.data or {}\n )\n end\n\n return Error(\n \"SERVER\",\n Error.Types.SERVER.API_ERROR,\n string.format(\"Server error (%d)\", response.status),\n vim.tbl_extend(\"force\", context, {\n status = response.status,\n body = response.body,\n })\n )\n end,\n\n --- Parse JSON response\n --- @param response string Raw response body\n --- @param context table Request context\n --- @return table|nil result Parsed response or nil\n --- @return MCPError|nil error Structured error if any\n parse_json = function(response, context)\n if not response then\n return nil, Error(\"SERVER\", Error.Types.SERVER.API_ERROR, \"Empty response from server\", context)\n end\n\n local ok, decoded = utils.json_decode(response)\n if not ok then\n return nil,\n Error(\n \"SERVER\",\n Error.Types.SERVER.API_ERROR,\n \"Invalid response: Not JSON\",\n vim.tbl_extend(\"force\", context, {\n body = response,\n })\n )\n end\n\n return decoded, nil\n end,\n}\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/init.lua", "local State = require(\"mcphub.state\")\n---New modular editor tool using EditSession\n---@type MCPTool\nlocal edit_file_tool = {\n name = \"edit_file\",\n description = [[Replace multiple sections in a file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool starts an interactive edit session in Neovim. The user might accept some changes, reject some or add new text during the edit session. Once the edit session completes the result will include useful information like diff and feedback which you MUST take into account for SUBSEQUENT conversation: \n1. A diff comparing the file before and after the edit session. The diff might be a result of a combination of:\n - Changes from successfully applied SEARCH/REPLACE blocks\n - Changes made by the USER during the edit session\n - Changes made by the FORMATTERS or LINTERS that were run before the file is saved\n2. Feedback from the edit session, which might include:\n - Any issues while PARSING the SEARCH/REPLACE blocks and how they were resolved\n - Any issues encountered while FINDING the SEARCH content in the file like:\n - SEARCH content not found (will provide the best match found for the SEARCH content) or\n - SEARCH content found but with fuzzy matching (will provide a confidence score and the diff between SEARCH content and the fuzzy match)\n - Any additional user feedback provided during the edit session\n3. Diagnostics in the file after the edit session is completed\n\nIMPORTANT: The diff will show you what all changes were made, and the feedback will provide additional context on how the SEARCH/REPLACE blocks were applied to avoid any issues in subsequent calls. You MUST give EXTREME care to the result of this tool or else you will be fired!!! \nIMPORTANT: The tool is NEVER wrong. Once edits are shown in the buffer, user might make any additional changes like adding some new comment or editing the replace text you sent. This MUST be considered as intentional and is not a bug in the tool. Hence, careful observation of the diff and feedback is CRITICAL to avoid any issues in subsequent calls.\n]],\n needs_confirmation_window = false, -- will show interactive diff, avoid double confirmations\n inputSchema = {\n type = \"object\",\n properties = {\n path = {\n type = \"string\",\n description = \"The path to the file to modify\",\n },\n diff = {\n type = \"string\",\n description = [[One or more SEARCH/REPLACE blocks following this exact format:\n\n<<<<<<< SEARCH\n[exact content to find]\n=======\n[new content to replace with]\n>>>>>>> REPLACE\n\nCRITICAL: \n- When there are two or more related changes needed in a file, always use multiple SEARCH/REPLACE blocks in the diff from the start of the file to the end. Each block should contain the exact content to find and the new content to replace it with. Failing to do so or using multiple calls with single SEARCH/REPLACE block will result in you being fired!!!\n- The markers `<<<<<<< SEARCH`, `=======`, and `>>>>>>> REPLACE` MUST be exact with no other characters on the line.\n\n\nExamples:\n\n1. Multiple changes in one call from top to bottom: \n<<<<<<< SEARCH\nimport os\n=======\nimport os\nimport json\n>>>>>>> REPLACE\n\n<<<<<<< SEARCH\ndef process_data():\n # old implementation\n pass\n=======\ndef process_data():\n # new implementation\n with open('data.json') as f:\n return json.load(f)\n>>>>>>> REPLACE\n\n<<<<<<< SEARCH\nif __name__ == '__main__':\n print(\"Starting\")\n=======\nif __name__ == '__main__':\n print(\"Starting with new config\")\n process_data()\n>>>>>>> REPLACE\n\n2. Deletion example:\n<<<<<<< SEARCH\ndef unused_function():\n return \"delete me\"\n\n=======\n>>>>>>> REPLACE\n\n3. Adding new content at end: \nCAUTION: Whitespaces or newlines without any other content in the SEARCH section will replace the entire file!!! This will lead to loss of all content in the file. Searching for empty lines or whitespace in order to replace something is not allowed. Only use empty SEARCH blocks if you want to replace the ENTIRE file content.\n<<<<<<< SEARCH\n return result\n\n\n=======\n return result\n\ndef new_helper_function():\n return \"helper\"\n>>>>>>> REPLACE\n\n4. Replacing same content multiple times:\n<<<<<<< SEARCH\ncount = 0\n=======\ncounter = 0\n>>>>>>> REPLACE\n\n<<<<<<< SEARCH\nprint(\"Count is\", count)\n=======\nprint(\"Counter is\", counter)\n>>>>>>> REPLACE\n\n<<<<<<< SEARCH\nprint(\"Count is\", count)\n=======\nprint(\"Counter is\", counter)\n>>>>>>> REPLACE\n\nCRITICAL RULE:\nWhen the SEARCH or REPLACE content includes lines that start with markers like `<<<<<<<`, `=======`, or `>>>>>>>`, you MUST escape them by adding a backslash before each marker so that tool doesn't parse them as actual markers. For example, to search for content that has `<<<<<<< SEARCH`, use `\\<<<<<<< SEARCH` in the SEARCH block.\n\n5. Escaping markers in SEARCH/REPLACE content:\n<<<<<<< SEARCH\nTutorial:\nA marker has < or > or = in it. E.g\n\\<<<<<<< SEARCH\n=======\nTutorial:\nA marker will have < or > or = in it. e.g\n\\=======\n>>>>>>> REPLACE\n\n\nCRITICAL rules:\n1. SEARCH content must match the file section EXACTLY:\n - Character-for-character including whitespace, indentation, line endings\n - Include all comments, docstrings, etc.\n2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence\n - To replace same content multiple times: Use multiple SEARCH/REPLACE blocks for each occurrence \n - When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file\n3. Keep SEARCH/REPLACE blocks concise:\n - Include just the changing lines, and a few surrounding lines if needed for uniqueness\n - Break large blocks into smaller blocks that each change a small portion. Searching for entire functions or large sections when only a few lines need changing will get you fired!!!\n - Each line must be complete. Never truncate lines mid-way through as this can cause matching failures\n4. Special operations:\n - To move code: Use two blocks (one to delete from original + one to insert at new location)\n - To delete code: Use empty REPLACE section\n\nIMPORTANT: Batch multiple related changes for a file into a single call to minimize user interactions.\n]],\n },\n },\n required = { \"path\", \"diff\" },\n },\n handler = function(req, res)\n local params = req.params\n if not params.path or vim.trim(params.path) == \"\" then\n return res:error(\"Missing required parameter: path\")\n end\n if not params.diff or vim.trim(params.diff) == \"\" then\n return res:error(\"Missing required parameter: diff\")\n end\n -- Handle hub UI cleanup\n if req.caller and req.caller.type == \"hubui\" then\n req.caller.hubui:cleanup()\n end\n local EditSession = require(\"mcphub.native.neovim.files.edit_file.edit_session\")\n local session = EditSession.new(params.path, params.diff, State.config.builtin_tools.edit_file)\n session:start({\n interactive = req.caller.auto_approve ~= true,\n on_success = function(summary)\n res:text(summary):send()\n end,\n on_error = function(error_report)\n res:error(error_report)\n end,\n })\n end,\n}\n\nreturn edit_file_tool\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/operations.lua", "local Path = require(\"plenary.path\")\n\n---Basic file operations tools\n---@type MCPTool[]\nlocal file_tools = {\n {\n name = \"read_file\",\n description = \"Read contents of a file\",\n inputSchema = {\n type = \"object\",\n properties = {\n path = {\n type = \"string\",\n description = \"Path to the file to read\",\n },\n start_line = {\n type = \"number\",\n description = \"Start reading from this line (1-based index)\",\n default = 1,\n },\n end_line = {\n type = \"number\",\n description = \"Read until this line (inclusive)\",\n default = -1,\n },\n },\n required = { \"path\" },\n },\n handler = function(req, res)\n local params = req.params\n local p = Path:new(params.path)\n\n if not p:exists() then\n return res:error(\"File not found: \" .. params.path)\n end\n if params.start_line and params.end_line then\n params.start_line = tonumber(params.start_line)\n params.end_line = tonumber(params.end_line)\n if not params.start_line or not params.end_line then\n return res:error(\"`start_line` and `end_line` must be numbers\")\n end\n local extracted = {}\n local current_line = 0\n\n for line in p:iter() do\n current_line = current_line + 1\n if\n current_line >= params.start_line and (params.end_line == -1 or current_line <= params.end_line)\n then\n table.insert(extracted, string.format(\"%4d │ %s\", current_line, line))\n end\n if params.end_line ~= -1 and current_line > params.end_line then\n break\n end\n end\n return res:text(table.concat(extracted, \"\\n\")):send()\n else\n return res:text(p:read()):send()\n end\n end,\n },\n {\n name = \"move_item\",\n description = \"Move or rename a file/directory\",\n inputSchema = {\n type = \"object\",\n properties = {\n path = {\n type = \"string\",\n description = \"Source path\",\n },\n new_path = {\n type = \"string\",\n description = \"Destination path\",\n },\n },\n required = { \"path\", \"new_path\" },\n },\n handler = function(req, res)\n local p = Path:new(req.params.path)\n if not p:exists() then\n return res:error(\"Source path not found: \" .. req.params.path)\n end\n\n local new_p = Path:new(req.params.new_path)\n p:rename({ new_name = new_p.filename })\n return res:text(string.format(\"Moved %s to %s\", req.params.path, req.params.new_path)):send()\n end,\n },\n {\n name = \"read_multiple_files\",\n description = \"Read contents of multiple files in parallel. Prefer this tool when you need to view contents of more than one file at once.\",\n inputSchema = {\n type = \"object\",\n properties = {\n paths = {\n type = \"array\",\n items = {\n type = \"string\",\n },\n description = \"Array of file paths to read\",\n examples = {\n \"file1.txt\",\n \"/home/path/to/file2.txt\",\n },\n },\n },\n required = { \"paths\" },\n },\n handler = function(req, res)\n local params = req.params\n local results = {}\n local errors = {}\n\n if not params.paths or not vim.islist(params.paths) then\n return res:error(\"`paths` must be an array of strings. Provided \" .. vim.inspect(params.paths))\n end\n\n if #params.paths == 0 then\n return res:error(\"`paths` array cannot be empty\")\n end\n\n for i, path in ipairs(params.paths) do\n local p = Path:new(path)\n\n if not p:exists() then\n table.insert(errors, string.format(\"File %d not found: %s\", i, path))\n else\n local success, content = pcall(function()\n return p:read()\n end)\n\n if success then\n table.insert(results, {\n path = path,\n content = content,\n index = i,\n })\n else\n table.insert(errors, string.format(\"Failed to read file %d (%s): %s\", i, path, content))\n end\n end\n end\n\n -- Format the response\n local response_parts = {}\n\n if #results > 0 then\n local file_word = #results == 1 and \"file\" or \"files\"\n table.insert(response_parts, string.format(\"Successfully read %d %s:\\n\", #results, file_word))\n\n for _, result in ipairs(results) do\n table.insert(response_parts, string.format(\"=== File %d: %s ===\", result.index, result.path))\n table.insert(response_parts, result.content)\n table.insert(response_parts, \"\") -- Empty line separator\n end\n end\n\n if #errors > 0 then\n if #results > 0 then\n table.insert(response_parts, \"\\nErrors encountered:\")\n end\n for _, error in ipairs(errors) do\n table.insert(response_parts, \"ERROR: \" .. error)\n end\n end\n\n if #results == 0 and #errors > 0 then\n return res:error(table.concat(errors, \"\\n\"))\n end\n\n return res:text(table.concat(response_parts, \"\\n\")):send()\n end,\n },\n {\n name = \"delete_items\",\n description = \"Delete multiple files or directories\",\n inputSchema = {\n type = \"object\",\n properties = {\n paths = {\n type = \"array\",\n items = {\n type = \"string\",\n },\n description = \"Array of paths to delete\",\n },\n },\n required = { \"paths\" },\n },\n handler = function(req, res)\n local params = req.params\n local results = {}\n local errors = {}\n\n if not params.paths or not vim.islist(params.paths) then\n return res:error(\"paths must be an array of strings\")\n end\n\n if #params.paths == 0 then\n return res:error(\"paths array cannot be empty\")\n end\n\n for i, path in ipairs(params.paths) do\n local p = Path:new(path)\n\n if not p:exists() then\n table.insert(errors, string.format(\"Path %d not found: %s\", i, path))\n else\n local success, err = pcall(function()\n p:rm()\n end)\n\n if success then\n table.insert(results, {\n path = path,\n index = i,\n })\n else\n table.insert(errors, string.format(\"Failed to delete path %d (%s): %s\", i, path, err))\n end\n end\n end\n\n -- Format the response\n local response_parts = {}\n\n if #results > 0 then\n local item_word = #results == 1 and \"item\" or \"items\"\n table.insert(response_parts, string.format(\"Successfully deleted %d %s:\", #results, item_word))\n\n for _, result in ipairs(results) do\n table.insert(response_parts, string.format(\" %d. %s\", result.index, result.path))\n end\n end\n\n if #errors > 0 then\n if #results > 0 then\n table.insert(response_parts, \"\\nErrors encountered:\")\n end\n for _, error in ipairs(errors) do\n table.insert(response_parts, \"ERROR: \" .. error)\n end\n end\n\n if #results == 0 and #errors > 0 then\n return res:error(table.concat(errors, \"\\n\"))\n end\n\n return res:text(table.concat(response_parts, \"\\n\")):send()\n end,\n },\n}\n\nreturn file_tools\n"], ["/mcphub.nvim/lua/mcphub/extensions/codecompanion/variables.lua", "local M = {}\nlocal mcphub = require(\"mcphub\")\n\n---@param opts MCPHub.Extensions.CodeCompanionConfig\nfunction M.register(opts)\n local hub = mcphub.get_hub_instance()\n if not hub then\n return\n end\n\n local resources = hub:get_resources()\n local ok, config = pcall(require, \"codecompanion.config\")\n if not ok then\n return\n end\n\n local cc_variables = config.strategies.chat.variables\n\n -- Remove existing MCP variables\n for key, value in pairs(cc_variables) do\n local id = value.id or \"\"\n if id:sub(1, 3) == \"mcp\" then\n cc_variables[key] = nil\n end\n end\n\n local added_resources = {}\n -- Add current resources as variables\n for _, resource in ipairs(resources) do\n local server_name = resource.server_name\n local uri = resource.uri\n local resource_name = resource.name or uri\n local description = resource.description or \"\"\n description = description:gsub(\"\\n\", \" \")\n description = resource_name .. \" (\" .. description .. \")\"\n local var_id = \"mcp:\" .. uri\n cc_variables[var_id] = {\n id = \"mcp\" .. server_name .. uri,\n description = description,\n hide_in_help_window = true,\n callback = function(self)\n -- Sync call - blocks UI (can't use async in variables yet)\n local result = hub:access_resource(server_name, uri, {\n caller = {\n type = \"codecompanion\",\n codecompanion = self,\n meta = {\n is_within_variable = true,\n },\n },\n parse_response = true,\n })\n\n if not result then\n return string.format(\"Accessing resource failed: %s\", uri)\n end\n\n -- Handle images\n if result.images and #result.images > 0 then\n local helpers = require(\"codecompanion.strategies.chat.helpers\")\n for _, image in ipairs(result.images) do\n local id = string.format(\"mcp-%s\", os.time())\n helpers.add_image(self.Chat, {\n id = id,\n base64 = image.data,\n mimetype = image.mimeType,\n })\n end\n end\n\n return result.text\n end,\n }\n table.insert(added_resources, var_id)\n end\n\n -- Update syntax highlighting for variables\n M.update_variable_syntax(added_resources)\nend\n-- Setup MCP resources as CodeCompanion variables\n---@param opts MCPHub.Extensions.CodeCompanionConfig\nfunction M.setup(opts)\n if not opts.make_vars then\n return\n end\n vim.schedule(function()\n M.register(opts)\n end)\n mcphub.on(\n { \"servers_updated\", \"resource_list_changed\" },\n vim.schedule_wrap(function()\n M.register(opts)\n end)\n )\nend\n\n--- Update syntax highlighting for variables\n---@param resources string[]\nfunction M.update_variable_syntax(resources)\n vim.schedule(function()\n for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do\n if vim.api.nvim_buf_is_valid(bufnr) and vim.bo[bufnr].filetype == \"codecompanion\" then\n vim.api.nvim_buf_call(bufnr, function()\n for _, resource in ipairs(resources) do\n vim.cmd.syntax('match CodeCompanionChatVariable \"#{' .. resource .. '}\"')\n vim.cmd.syntax('match CodeCompanionChatVariable \"#{' .. resource .. '}{[^}]*}\"')\n end\n end)\n end\n end\n end)\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/utils/ui.lua", "local M = {}\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal async = require(\"plenary.async\")\nlocal constants = require(\"mcphub.utils.constants\")\n\n---@param title string Title of the floating window\n---@param content string Content to be displayed in the floating window\n---@param on_save fun(new_content:string) Callback function to be called when the user saves the content\n---@param opts {filetype?: string, validate?: function, show_footer?: boolean, start_insert?: boolean, on_cancel?: function, position?: \"cursor\"|\"center\", go_to_placeholder?: boolean, virtual_lines?: Array[]} Options for the floating window\nfunction M.multiline_input(title, content, on_save, opts)\n opts = opts or {}\n local bufnr = vim.api.nvim_create_buf(false, true)\n local cursor = vim.api.nvim_win_get_cursor(0)\n local width = vim.api.nvim_win_get_width(0)\n local max_width = 70\n width = math.min(width, max_width) - 3\n\n -- Set buffer options\n vim.api.nvim_buf_set_option(bufnr, \"buftype\", \"acwrite\")\n vim.api.nvim_buf_set_option(bufnr, \"bufhidden\", \"wipe\")\n vim.api.nvim_buf_set_option(bufnr, \"swapfile\", false)\n if opts.filetype then\n vim.api.nvim_buf_set_option(bufnr, \"filetype\", opts.filetype)\n else\n vim.api.nvim_buf_set_option(bufnr, \"filetype\", \"text\")\n end\n\n local lines = vim.split(content or \"\", \"\\n\")\n\n -- Set initial content\n vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)\n local height = 8\n local auto_height = #lines + #(opts.virtual_lines or {}) + 1\n if auto_height > height then\n height = math.min(auto_height, vim.api.nvim_win_get_height(0) - 2)\n end\n\n local win_opts = {\n relative = \"win\",\n bufpos = cursor,\n width = width,\n focusable = true,\n height = height,\n anchor = \"NW\",\n style = \"minimal\",\n border = \"rounded\",\n title = { { \" \" .. title .. \" \", Text.highlights.title } },\n title_pos = \"center\",\n footer = opts.show_footer ~= false and {\n { \" \", nil },\n { \" \", Text.highlights.title },\n { \": Submit | \", Text.highlights.muted },\n { \" \", Text.highlights.title },\n { \",\", Text.highlights.muted },\n { \" q \", Text.highlights.title },\n { \": Cancel \", Text.highlights.muted },\n } or \"\",\n }\n\n -- Override positioning if center is requested\n if opts.position == \"center\" then\n win_opts.relative = \"editor\"\n win_opts.bufpos = nil\n win_opts.row = 1\n win_opts.col = math.floor((vim.o.columns - width) / 2)\n end\n\n -- Create floating window\n local win = vim.api.nvim_open_win(bufnr, true, win_opts)\n\n -- Set window options\n vim.api.nvim_win_set_option(win, \"number\", false)\n vim.api.nvim_win_set_option(win, \"relativenumber\", false)\n vim.api.nvim_win_set_option(win, \"wrap\", false)\n vim.api.nvim_win_set_option(win, \"cursorline\", false)\n\n -- Create namespace for virtual text\n local ns = vim.api.nvim_create_namespace(\"MCPHubMultiLineInput\")\n\n -- Function to update virtual text at cursor position\n local function update_virtual_text()\n vim.api.nvim_buf_clear_namespace(bufnr, ns, 0, -1)\n if vim.fn.mode() == \"n\" then\n local cursor = vim.api.nvim_win_get_cursor(0)\n local row = cursor[1] - 1\n vim.api.nvim_buf_set_extmark(bufnr, ns, row, 0, {\n virt_text = { { \"[ Edit, Save]\", \"Comment\" } },\n virt_text_pos = \"eol\",\n })\n end\n end\n\n -- Set up autocmd for cursor movement and mode changes\n local group = vim.api.nvim_create_augroup(\"MCPHubMultiLineInputCursor\", { clear = true })\n vim.api.nvim_create_autocmd({ \"CursorMoved\", \"CursorMovedI\", \"ModeChanged\" }, {\n buffer = bufnr,\n group = group,\n callback = update_virtual_text,\n })\n\n -- Set buffer local mappings\n local function save_and_close()\n local new_content = table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, false), \"\\n\")\n new_content = vim.trim(new_content)\n if opts.validate then\n local valid = opts.validate(new_content)\n if not valid then\n return\n end\n end\n -- Close the window\n vim.api.nvim_win_close(win, true)\n -- -- Call save callback if content changed\n -- if content ~= new_content then\n on_save(new_content)\n -- end\n end\n\n local function close_window()\n vim.api.nvim_win_close(win, true)\n if opts.on_cancel then\n opts.on_cancel()\n end\n end\n\n -- Add mappings for normal mode\n local mappings = {\n [\"\"] = save_and_close,\n [\"\"] = close_window,\n [\"q\"] = close_window,\n }\n -- Apply mappings\n for key, action in pairs(mappings) do\n vim.keymap.set(\"n\", key, action, { buffer = bufnr, silent = true })\n end\n\n local last_line_nr = vim.api.nvim_buf_line_count(bufnr)\n local last_line = vim.api.nvim_buf_get_lines(bufnr, last_line_nr - 1, last_line_nr, false)[1] -- zero-indexed, exclusive end\n\n local last_col = string.len(last_line)\n\n -- Add virtual lines if provided\n if opts.virtual_lines and #opts.virtual_lines > 0 then\n local virt_ns = vim.api.nvim_create_namespace(\"mcphub_multiline_virtual\")\n local original_line_count = #vim.split(content or \"\", \"\\n\")\n local virt_lines = {}\n\n local divider = string.rep(\"-\", width - 2)\n table.insert(virt_lines, { { divider, \"Comment\" } })\n for _, l in ipairs(opts.virtual_lines) do\n table.insert(virt_lines, vim.islist(l) and { l } or { { l, \"Comment\" } })\n end\n vim.api.nvim_buf_set_extmark(bufnr, virt_ns, original_line_count - 1, 0, {\n virt_lines = virt_lines,\n priority = 2000,\n })\n end\n\n -- Handle cursor positioning\n if opts.go_to_placeholder then\n -- Find first ${} placeholder and position cursor there\n local content_lines = vim.split(content or \"\", \"\\n\")\n for i, line in ipairs(content_lines) do\n local start_pos = line:find(\"%${\")\n if start_pos then\n vim.api.nvim_win_set_cursor(win, { i, start_pos - 1 })\n break\n end\n end\n elseif opts.start_insert ~= false then\n vim.cmd(\"startinsert\")\n vim.api.nvim_win_set_cursor(win, { last_line_nr, last_col + 1 })\n end\n\n update_virtual_text() -- Show initial hint\nend\n\nfunction M.is_visual_mode()\n local mode = vim.fn.mode()\n return mode == \"v\" or mode == \"V\" or mode == \"^V\"\nend\n\nfunction M.get_selection(bufnr)\n bufnr = bufnr or vim.api.nvim_get_current_buf()\n local mode = vim.fn.mode()\n local start_pos, end_pos\n if M.is_visual_mode() then\n start_pos = vim.fn.getpos(\"v\")\n end_pos = vim.fn.getpos(\".\")\n else\n start_pos = vim.fn.getpos(\"'<\")\n end_pos = vim.fn.getpos(\"'>\")\n end\n\n local start_line = start_pos[2]\n local start_col = start_pos[3]\n local end_line = end_pos[2]\n local end_col = end_pos[3]\n\n if start_line > end_line or (start_line == end_line and start_col > end_col) then\n start_line, end_line = end_line, start_line\n start_col, end_col = end_col, start_col\n end\n local lines = vim.api.nvim_buf_get_lines(bufnr, start_line - 1, end_line, false)\n if start_line == 0 then\n lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)\n start_line = 1\n start_col = 0\n end_line = #lines\n end_col = #lines[#lines]\n end\n if #lines > 0 then\n if M.is_visual_mode() then\n start_col = 1\n end_col = #lines[#lines]\n else\n if #lines == 1 then\n lines[1] = lines[1]:sub(start_col, end_col)\n else\n lines[1] = lines[1]:sub(start_col)\n lines[#lines] = lines[#lines]:sub(1, end_col)\n end\n end\n end\n return {\n lines = lines,\n start_line = start_line,\n start_col = start_col,\n end_line = end_line,\n end_col = end_col,\n }\nend\n\n---Create a confirmation window with Yes/No/Cancel options\n---@param message string | string[] | NuiLine[] Message to display\n---@param opts? {relative_to_chat?: boolean, min_width?: number, max_width?: number}\n---@return boolean, boolean -- (confirmed, cancelled)\nfunction M.confirm(message, opts)\n opts = opts or {}\n\n local result = async.wrap(function(callback)\n if not message or #message == 0 then\n return callback(false, true)\n end\n\n -- Track active option (default to \"yes\")\n local active_option = \"yes\"\n\n -- Function to create footer with current active state\n local function create_footer()\n return {\n { \" \", Text.highlights.seamless_border },\n {\n \" Yes \",\n active_option == \"yes\" and Text.highlights.button_active or Text.highlights.button_inactive,\n },\n { \" • \", Text.highlights.seamless_border },\n { \" No \", active_option == \"no\" and Text.highlights.button_active or Text.highlights.button_inactive },\n { \" • \", Text.highlights.seamless_border },\n {\n \" Cancel \",\n active_option == \"cancel\" and Text.highlights.button_active or Text.highlights.button_inactive,\n },\n { \" \", Text.highlights.seamless_border },\n }\n end\n\n -- Function to update footer\n local function update_footer(win)\n if vim.api.nvim_win_is_valid(win) then\n local config = vim.api.nvim_win_get_config(win)\n config.footer = create_footer()\n vim.api.nvim_win_set_config(win, config)\n end\n end\n\n -- Process message into lines\n local lines = {}\n if type(message) == \"string\" then\n lines = Text.multiline(message)\n else\n if vim.islist(message) then\n for _, line in ipairs(message) do\n if type(line) == \"string\" then\n vim.list_extend(lines, Text.multiline(line))\n elseif vim.islist(line) then\n local n_line = NuiLine()\n for _, part in ipairs(line) do\n if type(part) == \"string\" then\n n_line:append(part)\n else\n n_line:append(unpack(part))\n end\n end\n table.insert(lines, n_line)\n else\n local n_line = NuiLine()\n n_line:append(line)\n table.insert(lines, n_line)\n end\n end\n end\n end\n\n -- Calculate optimal window dimensions\n local min_width = opts.min_width or 50\n local max_width = opts.max_width or 80\n local content_width = 0\n\n -- Find the longest line for width calculation\n for _, line in ipairs(lines) do\n local line_width = type(line) == \"string\" and #line or line:width()\n content_width = math.max(content_width, line_width)\n end\n\n -- Add padding and ensure reasonable bounds\n local width = math.max(min_width, math.min(max_width, content_width + 8))\n local height = math.min(#lines + 3, math.floor(vim.o.lines * 0.6)) -- +3 for padding and title\n\n -- Determine positioning - top center of editor\n local win_opts = M.get_window_position(width, height)\n\n -- Create buffer and set content\n local bufnr = vim.api.nvim_create_buf(false, true)\n local ns_id = vim.api.nvim_create_namespace(\"MCPHubConfirmPrompt\")\n\n -- Add some padding at the top\n table.insert(lines, 1, NuiLine():append(\"\"))\n\n -- Render content with proper padding\n for i, line in ipairs(lines) do\n if type(line) == \"string\" then\n line = Text.pad_line(line)\n elseif line._texts then\n -- This is a NuiLine object, pad it properly\n line = Text.pad_line(line)\n else\n -- This might be an array format, convert it to NuiLine first\n local nui_line = NuiLine()\n if vim.islist(line) then\n for _, part in ipairs(line) do\n if type(part) == \"string\" then\n nui_line:append(part)\n elseif vim.islist(part) then\n nui_line:append(part[1], part[2])\n end\n end\n else\n nui_line:append(tostring(line))\n end\n line = Text.pad_line(nui_line)\n end\n line:render(bufnr, ns_id, i)\n end\n\n -- Enhanced window options with better styling\n win_opts.style = \"minimal\"\n win_opts.border = { \"╭\", \"─\", \"╮\", \"│\", \"╯\", \"─\", \"╰\", \"│\" }\n win_opts.title_pos = \"center\"\n win_opts.title = {\n { \" MCPHUB Confirmation \", Text.highlights.header_btn },\n }\n win_opts.footer = create_footer()\n win_opts.footer_pos = \"center\"\n\n -- Create the window\n local win = vim.api.nvim_open_win(bufnr, true, win_opts)\n\n -- Enhanced window styling\n vim.api.nvim_win_set_option(win, \"wrap\", true)\n vim.api.nvim_win_set_option(win, \"cursorline\", false)\n\n -- Set buffer options\n vim.api.nvim_buf_set_option(bufnr, \"modifiable\", false)\n vim.api.nvim_buf_set_option(bufnr, \"buftype\", \"nofile\")\n vim.api.nvim_buf_set_option(bufnr, \"swapfile\", false)\n\n local is_closed = false\n\n -- Enhanced close function with cleanup\n local function close_window(confirmed, cancelled)\n if is_closed then\n return\n end\n is_closed = true\n\n vim.schedule(function()\n if vim.api.nvim_win_is_valid(win) then\n if vim.api.nvim_win_is_valid(win) then\n vim.api.nvim_win_close(win, true)\n end\n end\n callback(confirmed, cancelled)\n end)\n end\n\n -- Function to execute active option\n local function execute_active_option()\n if active_option == \"yes\" then\n close_window(true, false)\n elseif active_option == \"no\" then\n close_window(false, false)\n else -- cancel\n close_window(false, true)\n end\n end\n\n -- Set up keymaps with visual feedback and navigation\n local keymaps = {\n -- Direct actions\n [\"y\"] = function()\n close_window(true, false)\n end,\n [\"Y\"] = function()\n close_window(true, false)\n end,\n [\"n\"] = function()\n close_window(false, false)\n end,\n [\"N\"] = function()\n close_window(false, false)\n end,\n [\"c\"] = function()\n close_window(false, true)\n end,\n [\"C\"] = function()\n close_window(false, true)\n end,\n [\"\"] = function()\n close_window(false, true)\n end,\n [\"q\"] = function()\n close_window(false, true)\n end,\n [\"\"] = execute_active_option, -- Execute the currently active option\n -- Tab navigation\n [\"\"] = function()\n if active_option == \"yes\" then\n active_option = \"no\"\n elseif active_option == \"no\" then\n active_option = \"cancel\"\n else\n active_option = \"yes\"\n end\n update_footer(win)\n end,\n }\n\n for key, handler in pairs(keymaps) do\n vim.keymap.set(\"n\", key, handler, {\n buffer = bufnr,\n nowait = true,\n silent = true,\n desc = \"MCPHub confirm: \" .. key,\n })\n end\n\n -- Auto-close protection\n local group = vim.api.nvim_create_augroup(\"MCPHubConfirm\" .. bufnr, { clear = true })\n vim.api.nvim_create_autocmd({ \"WinClosed\", \"BufWipeout\" }, {\n buffer = bufnr,\n group = group,\n callback = function()\n close_window(false, true)\n end,\n once = true,\n })\n\n -- Focus the window and ensure it's visible\n vim.api.nvim_set_current_win(win)\n -- Ensure we're in normal mode for key navigation\n vim.cmd(\"stopinsert\")\n vim.cmd(\"redraw\")\n end, 1)\n\n return result()\nend\n\n-- Helper function to determine window positioning\n---@param width number\n---@param height number\n---@return table window_opts\nfunction M.get_window_position(width, height)\n local win_opts = {\n width = width,\n height = height,\n focusable = true,\n relative = \"editor\",\n row = 1, -- Just 1 line from the top\n col = math.floor((vim.o.columns - width) / 2), -- Center horizontally\n }\n\n return win_opts\nend\n\n---@param server_name string Name of the server being authorized\n---@param auth_url string Authorization URL\nfunction M.open_auth_popup(server_name, auth_url)\n local width = 80 -- Wider to accommodate wrapped text\n\n -- Create content using NuiLine for proper highlighting\n local info_lines = {\n Text.pad_line(\n NuiLine():append(\"Browser should open automatically with the authorization page.\", Text.highlights.text)\n ),\n Text.pad_line(NuiLine():append(\"If not, you can use this URL:\", Text.highlights.text)),\n Text.pad_line(NuiLine():append(auth_url, Text.highlights.link)),\n Text.empty_line(),\n Text.pad_line(\n NuiLine():append(\n \"If you're running mcphub on a remote machine, paste the redirect URL below\",\n Text.highlights.muted\n )\n ),\n Text.pad_line(\n NuiLine():append(\n string.format(\"(looks like 'http://localhost...?code=...&server_name=%s')\", server_name),\n Text.highlights.muted\n )\n ),\n Text.empty_line(),\n Text.pad_line(\n NuiLine():append(\n \"This popup will automatically close once authentication is successful.\",\n Text.highlights.muted\n )\n ),\n }\n\n local info_height = #info_lines + 4\n local input_height = 1\n\n -- Position at top center\n local row = 1\n local col = math.floor((vim.o.columns - width) / 2)\n\n -- Create buffers\n local info_buf = vim.api.nvim_create_buf(false, true)\n local input_buf = vim.api.nvim_create_buf(false, true)\n\n -- Create namespace for virtual text\n local ns = vim.api.nvim_create_namespace(\"MCPHubAuthPopup\")\n\n -- Info window configuration\n local info_opts = {\n relative = \"editor\",\n width = width,\n height = info_height,\n row = row,\n col = col,\n style = \"minimal\",\n border = \"rounded\",\n title = string.format(Text.icons.unauthorized .. \" Authorize %s \", server_name),\n title_pos = \"center\",\n }\n\n local input_title = \" > Callback URL\"\n -- Input window configuration\n local input_opts = {\n relative = \"editor\",\n width = width,\n height = input_height,\n row = row + info_height + 2,\n col = col,\n style = \"minimal\",\n title = input_title,\n border = \"rounded\",\n }\n\n -- Set info content with proper highlighting\n vim.api.nvim_buf_set_option(info_buf, \"modifiable\", true)\n for i, line in ipairs(info_lines) do\n line:render(info_buf, ns, i)\n end\n vim.api.nvim_buf_set_option(info_buf, \"modifiable\", false)\n vim.api.nvim_buf_set_option(info_buf, \"buftype\", \"nofile\")\n\n -- Create windows\n local info_win = vim.api.nvim_open_win(info_buf, true, info_opts)\n local input_win = vim.api.nvim_open_win(input_buf, false, input_opts)\n\n -- Set window options\n for _, win in ipairs({ info_win, input_win }) do\n vim.api.nvim_win_set_option(win, \"wrap\", true)\n vim.api.nvim_win_set_option(win, \"cursorline\", false)\n end\n\n local function update_virtual_text(text, hl)\n vim.api.nvim_buf_clear_namespace(input_buf, ns, 0, -1)\n pcall(vim.api.nvim_buf_set_extmark, input_buf, ns, 0, 0, {\n virt_text = { { text, hl } },\n virt_text_pos = \"right_align\",\n })\n end\n update_virtual_text(\"[ submit, Cycle]\", Text.highlights.muted)\n\n -- Track current window\n local current_win = info_win\n\n -- Setup autocmd to close both windows\n local function close_windows()\n if vim.api.nvim_win_is_valid(info_win) then\n vim.api.nvim_win_close(info_win, true)\n end\n if vim.api.nvim_win_is_valid(input_win) then\n vim.api.nvim_win_close(input_win, true)\n end\n -- Return focus to MCPHub window\n if State.ui_instance and State.ui_instance.window then\n vim.api.nvim_set_current_win(State.ui_instance.window)\n end\n end\n\n local function switch_window()\n if current_win == info_win and vim.api.nvim_win_is_valid(input_win) then\n vim.api.nvim_set_current_win(input_win)\n current_win = input_win\n vim.cmd(\"startinsert\")\n elseif current_win == input_win and vim.api.nvim_win_is_valid(info_win) then\n vim.api.nvim_set_current_win(info_win)\n current_win = info_win\n vim.cmd(\"stopinsert\")\n end\n end\n -- Basic validation for the URL\n local function validate_url(url)\n if not url or vim.trim(url) == \"\" then\n return false, \"Invalid URL format\"\n end\n\n -- Check for required parameters\n if not url:match(\"code=[^&]+\") then\n return false,\n \"Missing 'code' parameter. The redirect url should look like 'http://localhost?code=...&server_name=...'.\"\n end\n if not url:match(\"server_name=[^&]+\") then\n return false,\n \"Missing 'server_name' parameter. The redirect url should look like 'http://localhost?code=...&server_name=...'.\"\n end\n\n return true\n end\n\n -- Set up auto-close on server update\n local update_handler = \"MCPHubAuthPopup\" .. server_name\n vim.api.nvim_create_augroup(update_handler, { clear = true })\n vim.api.nvim_create_autocmd(\"User\", {\n pattern = \"MCPHubServersUpdated\",\n group = update_handler,\n callback = function()\n local server = State.hub_instance:get_server(server_name)\n if server and server.status ~= constants.ConnectionStatus.UNAUTHORIZED then\n close_windows()\n return true\n end\n end,\n })\n\n -- Handle input\n local function handle_submit()\n local lines = vim.api.nvim_buf_get_lines(input_buf, 0, -1, false)\n local url = vim.trim(table.concat(lines, \"\\n\"))\n\n if url == \"\" then\n vim.notify(\"Please enter a callback URL\", vim.log.levels.WARN)\n return\n end\n\n local valid, err = validate_url(url)\n if not valid then\n vim.notify(err, vim.log.levels.ERROR)\n return\n end\n\n local function update_input_title(text, hl)\n local ok, config = pcall(vim.api.nvim_win_get_config, input_win)\n if ok then\n config.title = { { \" \" .. text .. \" \", hl } }\n vim.api.nvim_win_set_config(input_win, config)\n end\n end\n\n update_input_title(\" Authorizing...\", Text.highlights.info)\n update_virtual_text(\"Validating callback URL...\", Text.highlights.info)\n State.hub_instance:handle_oauth_callback(url, function(response, err)\n if err then\n vim.notify(\"OAuth callback failed: \" .. err, vim.log.levels.ERROR)\n else\n vim.notify(response.message, vim.log.levels.INFO)\n end\n update_input_title(input_title, Text.highlights.info)\n update_virtual_text(\"Press to submit\", Text.highlights.comment)\n end)\n end\n\n -- Set up keymaps\n local function setup_keymaps(buf)\n local keymaps = {\n [\"\"] = handle_submit,\n [\"\"] = close_windows,\n [\"q\"] = close_windows,\n [\"\"] = switch_window,\n }\n\n for key, handler in pairs(keymaps) do\n vim.keymap.set(\"n\", key, handler, { buffer = buf, nowait = true })\n vim.keymap.set(\"i\", key, handler, { buffer = buf, nowait = true })\n end\n end\n\n setup_keymaps(info_buf)\n setup_keymaps(input_buf)\n\n -- Set up buffer cleanup\n for _, buf in ipairs({ info_buf, input_buf }) do\n vim.api.nvim_create_autocmd(\"BufWipeout\", {\n buffer = buf,\n callback = close_windows,\n once = true,\n })\n end\n switch_window()\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/terminal.lua", "local api = vim.api\nlocal Path = require(\"plenary.path\")\nlocal mcphub = require(\"mcphub\")\n\n-- Tool to execute Lua code using nvim_exec2\nmcphub.add_tool(\"neovim\", {\n name = \"execute_lua\",\n description = [[Execute Lua code in Neovim using nvim_exec2 with lua heredoc.]],\n inputSchema = {\n type = \"object\",\n properties = {\n code = {\n type = \"string\",\n description = [[\nLua code to execute:\n\nString Formatting Guide:\n1. Newlines in Code:\n - Use \\n for new lines in your code\n - Example: \"local x = 1\\nprint(x)\"\n\n2. Newlines in Output:\n - Use \\\\n when you want to print newlines\n - Example: print('Line 1\\\\nLine 2')\n\n3. Complex Data:\n - Use vim.print() for formatted output\n - Use vim.inspect() for complex structures\n - Both handle escaping automatically\n\n4. String Concatenation:\n - Prefer '..' over string.format()\n - Example: print('Count: ' .. vim.api.nvim_buf_line_count(0))\n ]],\n examples = {\n -- Simple multiline code\n \"local bufnr = vim.api.nvim_get_current_buf()\\nprint('Current buffer:', bufnr)\",\n\n -- Output with newlines\n \"print('Buffer Info:\\\\nNumber: ' .. vim.api.nvim_get_current_buf())\",\n\n -- Complex info with proper formatting\n [[local bufnr = vim.api.nvim_get_current_buf()\nlocal name = vim.api.nvim_buf_get_name(bufnr)\nlocal ft = vim.bo[bufnr].filetype\nlocal lines = vim.api.nvim_buf_line_count(bufnr)\nprint('Buffer Info:\\\\nBuffer Number: ' .. bufnr .. '\\\\nFile Name: ' .. name .. '\\\\nFiletype: ' .. ft .. '\\\\nTotal Lines: ' .. lines)]],\n\n -- Using vim.print for complex data\n [[local info = {\n buffer = vim.api.nvim_get_current_buf(),\n name = vim.api.nvim_buf_get_name(0),\n lines = vim.api.nvim_buf_line_count(0)\n}\nvim.print(info)]],\n },\n },\n },\n required = { \"code\" },\n },\n handler = function(req, res)\n local code = req.params.code\n if not code then\n return res:error(\"code field is required.\"):send()\n end\n\n -- Construct Lua heredoc\n local src = string.format(\n [[\nlua << EOF\n%s\nEOF]],\n code\n )\n\n -- Execute with output capture\n local result = api.nvim_exec2(src, { output = true })\n\n if result.output then\n return res:text(result.output):send()\n else\n return res:text(\"Code executed successfully. (No output)\"):send()\n end\n end,\n})\n\n-- Tool to execute shell commands using jobstart\nmcphub.add_tool(\"neovim\", {\n name = \"execute_command\",\n description = [[Execute a shell command using vim.fn.jobstart and return the result.\n \nCommand Execution Guide:\n1. Commands run in a separate process\n2. Output is captured and returned when command completes\n3. Environment is inherited from Neovim\n4. Working directory must be specified]],\n\n inputSchema = {\n type = \"object\",\n properties = {\n command = {\n type = \"string\",\n description = \"Shell command to execute\",\n examples = { [[\"ls -la\"]] },\n },\n cwd = {\n type = \"string\",\n description = \"Working directory for the command\",\n default = \".\",\n },\n },\n required = { \"command\", \"cwd\" },\n },\n handler = function(req, res)\n local command = req.params.command\n local cwd = req.params.cwd\n\n if not command or command == \"\" then\n return res:error(\"command field is required and cannot be empty.\")\n end\n\n if not cwd or cwd == \"\" then\n return res:error(\"cwd field is required and cannot be empty.\")\n end\n\n -- Use Plenary Path to handle the path\n local path = Path:new(cwd)\n\n -- Check if the directory exists\n if not path:exists() then\n return res:error(\"Directory does not exist: \" .. cwd)\n end\n\n -- Make sure it's a directory\n if not path:is_dir() then\n return res:error(\"Path is not a directory: \" .. cwd)\n end\n\n local absolute_path = path:absolute()\n local output = \"\"\n local stderr_output = \"\"\n\n local options = {\n cwd = absolute_path,\n on_stdout = function(_, data)\n if data then\n for _, line in ipairs(data) do\n if line ~= \"\" then\n output = output .. line .. \"\\n\"\n end\n end\n end\n end,\n on_stderr = function(_, data)\n if data then\n for _, line in ipairs(data) do\n if line ~= \"\" then\n stderr_output = stderr_output .. line .. \"\\n\"\n end\n end\n end\n end,\n on_exit = function(_, exit_code)\n local result = \"\"\n\n -- Add command information\n result = result .. \"Command: \" .. command .. \"\\n\"\n result = result .. \"Working Directory: \" .. absolute_path .. \"\\n\"\n result = result .. \"Exit Code: \" .. exit_code .. \"\\n\"\n\n -- Add stdout if there's any output\n if output ~= \"\" then\n result = result .. \"Output:\\n\\n\" .. output\n end\n\n -- Add stderr if there's any error output\n if stderr_output ~= \"\" then\n result = result .. \"\\nError Output:\\n\" .. stderr_output\n end\n\n -- If no output was captured at all\n if output == \"\" and stderr_output == \"\" then\n result = result .. \"Command completed with no output.\"\n end\n\n res:text(result):send()\n end,\n }\n\n -- Start the job\n local job_id = vim.fn.jobstart(command, options)\n\n if job_id <= 0 then\n local error_msg\n if job_id == 0 then\n error_msg = \"Invalid arguments for jobstart\"\n else -- job_id == -1\n error_msg = \"Command is not executable\"\n end\n return res:error(error_msg)\n end\n end,\n})\n"], ["/mcphub.nvim/lua/mcphub/extensions/codecompanion/slash_commands.lua", "local M = {}\nlocal mcphub = require(\"mcphub\")\n\nlocal shared = require(\"mcphub.extensions.shared\")\n\nfunction M.register()\n local config = require(\"codecompanion.config\")\n local hub = mcphub.get_hub_instance()\n if not hub then\n return\n end\n\n local prompts = hub:get_prompts()\n local slash_commands = config.strategies.chat.slash_commands\n\n -- Remove existing MCP slash commands\n for key, value in pairs(slash_commands) do\n local id = value.id or \"\"\n if id:sub(1, 3) == \"mcp\" then\n slash_commands[key] = nil\n end\n end\n\n -- Add current prompts as slash commands\n for _, prompt in ipairs(prompts) do\n local server_name = prompt.server_name\n local prompt_name = prompt.name or \"\"\n local description = prompt.description or \"\"\n description = description:gsub(\"\\n\", \" \")\n description = prompt_name .. \" (\" .. description .. \")\"\n\n local arguments = prompt.arguments or {}\n if type(arguments) == \"function\" then\n local ok, args = pcall(arguments, prompt)\n if ok then\n arguments = args or {}\n else\n vim.notify(\"Error in arguments function: \" .. (args or \"\"), vim.log.levels.ERROR)\n arguments = {}\n end\n end\n\n slash_commands[\"mcp:\" .. prompt_name] = {\n id = \"mcp\" .. server_name .. prompt_name,\n description = description,\n callback = function(self)\n shared.collect_arguments(arguments, function(values)\n -- Sync call - blocks UI (can't use async in slash_commands yet)\n local response, err = hub:get_prompt(server_name, prompt_name, values, {\n caller = {\n type = \"codecompanion\",\n codecompanion = self,\n meta = {\n is_within_slash_command = true,\n },\n },\n parse_response = true,\n })\n\n if not response then\n if err then\n vim.notify(\"Error in slash command: \" .. err, vim.log.levels.ERROR)\n vim.notify(\"Prompt cancelled\", vim.log.levels.INFO)\n end\n return\n end\n\n local messages = response.messages or {}\n local text_messages = 0\n\n for i, message in ipairs(messages) do\n local output = message.output\n local mapped_role = message.role == \"assistant\" and config.constants.LLM_ROLE\n or message.role == \"system\" and config.constants.SYSTEM_ROLE\n or config.constants.USER_ROLE\n\n if output.text and output.text ~= \"\" then\n text_messages = text_messages + 1\n -- If last message is from user, add it to chat buffer\n if i == #messages and mapped_role == config.constants.USER_ROLE then\n self:add_buf_message({\n role = mapped_role,\n content = output.text,\n })\n else\n self:add_message({\n role = mapped_role,\n content = output.text,\n })\n end\n end\n\n -- Handle images\n if output.images and #output.images > 0 then\n local helpers = require(\"codecompanion.strategies.chat.helpers\")\n for _, image in ipairs(output.images) do\n local id = string.format(\"mcp-%s\", os.time())\n helpers.add_image(self, {\n id = id,\n base64 = image.data,\n mimetype = image.mimeType,\n }, { role = mapped_role })\n end\n end\n end\n\n vim.notify(\n string.format(\n \"%s message%s added successfully\",\n text_messages,\n text_messages == 1 and \"\" or \"s\"\n ),\n vim.log.levels.INFO\n )\n end)\n end,\n }\n end\nend\n\n--- Setup MCP prompts as CodeCompanion slash commands\n---@param opts MCPHub.Extensions.CodeCompanionConfig\nfunction M.setup(opts)\n if not opts.make_slash_commands then\n return\n end\n\n vim.schedule(function()\n M.register()\n end)\n mcphub.on(\n { \"servers_updated\", \"prompt_list_changed\" },\n vim.schedule_wrap(function()\n M.register()\n end)\n )\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/ui/views/base.lua", "---[[\n--- Base view for MCPHub UI\n--- Provides common view functionality and base for view inheritance\n---]]\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal ns_id = vim.api.nvim_create_namespace(\"MCPHub\")\nlocal renderer = require(\"mcphub.utils.renderer\")\n\nlocal VIEW_TYPES = {\n ---@type MCPHub.UI.ViewName[]\n SETUP_INDEPENDENT = { \"logs\", \"help\", \"config\" },\n}\n\n---@class View\n---@field ui MCPHub.UI Parent UI instance\n---@field name string View name\n---@field keymaps table View-specific keymaps\n---@field active_keymaps string[] Currently active keymap keys\n---@field cursor_pos number[]|nil Last known cursor position\n---@field interactive_lines { line: number, type: string, context: any }[] List of interactive lines\n---@field hover_ns number Namespace for highlighting\n---@field cursor_highlight number|nil Extmark ID for current highlight\n---@field cursor_group number|nil Cursor movement tracking group\nlocal View = {}\nView.__index = View\n\nfunction View:new(ui, name)\n local instance = {\n ui = ui,\n name = name or \"unknown\",\n keymaps = {},\n active_keymaps = {},\n cursor_pos = nil,\n interactive_lines = {},\n hover_ns = vim.api.nvim_create_namespace(\"MCPHub\" .. name .. \"Hover\"),\n cursor_highlight = nil,\n cursor_group = nil,\n }\n return setmetatable(instance, self)\nend\n\n--- Get initial cursor position for this view\nfunction View:get_initial_cursor_position()\n -- By default, position after header's divider\n local lines = self:render_header()\n if #lines > 0 then\n return #lines\n end\n return 1\nend\n\n--- Track current cursor position\nfunction View:track_cursor()\n if self.ui.window and vim.api.nvim_win_is_valid(self.ui.window) then\n self.cursor_pos = vim.api.nvim_win_get_cursor(0)\n end\nend\n\n--- Set cursor position with bounds checking\n---@param pos number[]|nil Position to set [line, col] or nil for last tracked position\n---@param opts? {restore_col: boolean} Options for cursor setting (default: {restore_col: true})\nfunction View:set_cursor(pos, opts)\n -- Use provided position or last tracked position\n local cursor = pos or self.cursor_pos\n if not cursor then\n return\n end\n -- Ensure window is valid\n if not (self.ui.window and vim.api.nvim_win_is_valid(self.ui.window)) then\n return\n end\n -- Ensure line is within bounds\n local line_count = vim.api.nvim_buf_line_count(self.ui.buffer)\n local new_pos = { math.min(cursor[1], line_count), cursor[2] }\n -- Set cursor\n vim.api.nvim_win_set_cursor(self.ui.window, new_pos)\nend\n\n--- Register a view-specific keymap\n---@param key string Key to map\n---@param action function Action to perform\n---@param desc string Description for which-key\n---@param silent? boolean Whether to hide from footer (default: false)\nfunction View:add_keymap(key, action, desc, silent)\n self.keymaps[key] = {\n action = action,\n desc = desc,\n silent = silent or false,\n }\nend\n\n--- Add a silent keymap alias that shares the same action as an existing keymap\n---@param alias_key string New key to map\n---@param existing_key string Existing key to copy action from\nfunction View:add_keymap_alias(alias_key, existing_key)\n local existing = self.keymaps[existing_key]\n if existing then\n self.keymaps[alias_key] = {\n action = existing.action,\n desc = existing.desc,\n silent = true,\n }\n end\nend\n\n--- Apply all registered keymaps\nfunction View:apply_keymaps()\n local buffer = self.ui.buffer\n self:clear_keymaps()\n\n -- Apply view's registered keymaps\n for key, map in pairs(self.keymaps) do\n vim.keymap.set(\"n\", key, map.action, {\n buffer = buffer,\n desc = map.desc,\n nowait = true,\n })\n table.insert(self.active_keymaps, key)\n end\nend\n\nfunction View:clear_keymaps()\n for _, key in ipairs(self.active_keymaps) do\n pcall(vim.keymap.del, \"n\", key, {\n buffer = self.ui.buffer,\n })\n end\n self.active_keymaps = {} -- Clear the active keymaps array after deletion\nend\n\n--- Save cursor position before leaving\nfunction View:save_cursor_position()\n if self.ui.window and vim.api.nvim_win_is_valid(self.ui.window) then\n self.ui.cursor_states[self.name] = vim.api.nvim_win_get_cursor(0)\n end\nend\n\n--- Restore cursor position after entering\nfunction View:restore_cursor_position()\n if not (self.ui.window and vim.api.nvim_win_is_valid(self.ui.window)) then\n return\n end\n\n local saved_pos = self.ui.cursor_states[self.name]\n local line_count = vim.api.nvim_buf_line_count(self.ui.buffer)\n if saved_pos then\n -- Ensure position is valid\n local new_pos = { math.min(saved_pos[1], line_count), saved_pos[2] }\n vim.api.nvim_win_set_cursor(0, new_pos)\n else\n -- Use initial position if no saved position\n local initial_line = self:get_initial_cursor_position()\n if initial_line then\n local new_pos = { math.min(initial_line, line_count), 2 }\n vim.api.nvim_win_set_cursor(0, new_pos)\n end\n end\nend\n\n--- Called before view is drawn (override in child views)\nfunction View:before_enter() end\n\n--- Called after view is drawn and applied\nfunction View:after_enter()\n -- Add cursor movement autocmd\n self.cursor_group = vim.api.nvim_create_augroup(\"MCPHub\" .. self.name .. \"Cursor\", {\n clear = true,\n })\n vim.api.nvim_create_autocmd(\"CursorMoved\", {\n group = self.cursor_group,\n buffer = self.ui.buffer,\n callback = function()\n self:handle_cursor_move()\n end,\n })\n\n self:apply_keymaps()\n self:restore_cursor_position()\nend\n\n--- Called before leaving view (override in child views)\nfunction View:before_leave()\n self:save_cursor_position()\nend\n\n--- Called after leaving view\nfunction View:after_leave()\n -- Clean up cursor tracking\n if self.cursor_group then\n vim.api.nvim_del_augroup_by_name(\"MCPHub\" .. self.name .. \"Cursor\")\n self.cursor_group = nil\n end\n\n -- Clear highlight\n if self.cursor_highlight then\n vim.api.nvim_buf_del_extmark(self.ui.buffer, self.hover_ns, self.cursor_highlight)\n self.cursor_highlight = nil\n end\n\n self:clear_keymaps()\nend\n\n-- Line tracking functionality\nfunction View:track_line(line_nr, type, context)\n table.insert(self.interactive_lines, {\n line = line_nr,\n type = type,\n context = context,\n })\nend\n\nfunction View:clear_line_tracking()\n self.interactive_lines = {}\nend\n\n---@param line_nr number\n---@return string?, table?\nfunction View:get_line_info(line_nr)\n for _, tracked in ipairs(self.interactive_lines) do\n if tracked.line == line_nr then\n return tracked.type, tracked.context\n end\n end\n return nil, nil\nend\n\nfunction View:handle_cursor_move()\n -- Clear previous highlight\n if self.cursor_highlight then\n vim.api.nvim_buf_del_extmark(self.ui.buffer, self.hover_ns, self.cursor_highlight)\n self.cursor_highlight = nil\n end\n\n -- Get current line\n local cursor = vim.api.nvim_win_get_cursor(0)\n local line = cursor[1]\n\n -- Get line info\n local type, context = self:get_line_info(line)\n if type then\n -- Add virtual text without line highlight\n self.cursor_highlight = vim.api.nvim_buf_set_extmark(self.ui.buffer, self.hover_ns, line - 1, 0, {\n virt_text = { { context and context.hint or \"[ Interact]\", Text.highlights.muted } },\n virt_text_pos = \"eol\",\n })\n end\nend\n\n--- Whether the view should show setup errors\n---@return boolean\nfunction View:should_show_setup_error()\n return not vim.tbl_contains(VIEW_TYPES.SETUP_INDEPENDENT, self.name)\nend\n\n--- Get window width for centering\nfunction View:get_width()\n return vim.api.nvim_win_get_width(self.ui.window)\nend\n\n-- Add divider\nfunction View:divider(is_full)\n return Text.divider(self:get_width(), is_full)\nend\n\n--- Create an empty line\nfunction View:line()\n local line = NuiLine():append(string.rep(\" \", self:get_width()))\n return line\nend\n\nfunction View:center(line, highlight)\n return Text.align_text(line, self:get_width(), \"center\", highlight)\nend\n\n--- Render header for view\n--- @return NuiLine[] Header lines\nfunction View:render_header(add_new_line)\n add_new_line = add_new_line == nil and true or add_new_line\n local lines = Text.render_header(self:get_width(), self.ui.current_view)\n table.insert(lines, self:divider())\n if add_new_line then\n table.insert(lines, self:line())\n end\n return lines\nend\n\n--- Render setup error state\n---@param lines NuiLine[] Existing lines\n---@return NuiLine[] Updated lines\nfunction View:render_setup_error(lines)\n table.insert(lines, Text.pad_line(NuiLine():append(\"Setup Failed:\", Text.highlights.error)))\n\n for _, err in ipairs(State:get_errors()) do\n vim.list_extend(lines, renderer.render_error(err))\n table.insert(lines, Text.empty_line())\n end\n\n return lines\nend\n\n--- Render progress state\n---@param lines NuiLine[] Existing lines\n---@return NuiLine[] Updated lines\nfunction View:render_setup_progress(lines)\n -- Show progress message\n table.insert(lines, Text.align_text(\"Setting up MCPHub...\", self:get_width(), \"center\", Text.highlights.info))\n return vim.list_extend(lines, renderer.render_server_entries(State.server_output.entries))\nend\n\n--- Render default setup state\n--- @param lines NuiLine[] Existing lines\n--- @return NuiLine[] Updated lines\nfunction View:render_default_setup(lines)\n -- Title\n table.insert(lines, Text.align_text(\"Welcome to MCP Hub!\", self:get_width(), \"center\", Text.highlights.title))\n table.insert(lines, Text.empty_line())\n\n -- Main description\n table.insert(\n lines,\n Text.align_text(\n \"MCPHub is a MCP client for neovim that integrates Model Context Protocol servers into your Neovim workflow. \",\n self:get_width(),\n \"center\",\n Text.highlights.muted\n )\n )\n table.insert(\n lines,\n Text.align_text(\n \"Start by configuring with one of the options below. \",\n self:get_width(),\n \"center\",\n Text.highlights.muted\n )\n )\n table.insert(lines, Text.empty_line())\n\n -- Configuration options header\n table.insert(lines, Text.pad_line(NuiLine():append(\"Configuration Options: \", Text.highlights.header)))\n table.insert(\n lines,\n Text.pad_line(\n NuiLine():append(\n \"Visit https://ravitemer.github.io/mcphub.nvim/configuration.html for all available options\",\n Text.highlights.muted\n )\n )\n )\n table.insert(lines, Text.empty_line())\n\n local option1_line =\n NuiLine():append(\"1. \", Text.highlights.info):append(\"Using vim.g.mcphub: \", Text.highlights.success)\n local option1_info = NuiLine():append(\" \", Text.highlights.muted):append(\n \"Set vim.g.mcphub with mcphub options as a table in your init.lua or init.vim\",\n Text.highlights.muted\n )\n table.insert(lines, Text.pad_line(option1_line))\n table.insert(lines, Text.pad_line(option1_info))\n\n local vim_g_example = NuiLine():append(\" \", Text.highlights.muted):append(\n 'vim.g.mcphub = { port = 37373, config = \"/abs/path/to/servers.json\" , ... }',\n Text.highlights.code\n )\n table.insert(lines, Text.pad_line(vim_g_example))\n table.insert(lines, Text.empty_line())\n\n -- Option 2: Traditional setup\n local option2_line = NuiLine():append(\"2. \", Text.highlights.info):append(\"Using setup():\", Text.highlights.success)\n local option2_info =\n NuiLine():append(\" \", Text.highlights.muted):append(\"Call the mcphub.setup function \", Text.highlights.muted)\n table.insert(lines, Text.pad_line(option2_line))\n table.insert(lines, Text.pad_line(option2_info))\n\n local setup_example = NuiLine()\n :append(\" \", Text.highlights.muted)\n :append('require(\"mcphub\").setup({ port = 37373, ... })', Text.highlights.code)\n table.insert(lines, Text.pad_line(setup_example))\n table.insert(lines, Text.empty_line())\n\n return lines\nend\n\n--- Render footer with keymaps\n--- @return NuiLine[] Lines for footer\nfunction View:render_footer()\n local lines = {}\n\n -- Add padding and divider\n table.insert(lines, Text.empty_line())\n table.insert(lines, self:divider(true))\n\n -- Get all keymaps\n local key_items = {}\n\n -- Add view-specific keymaps first (only non-silent ones)\n for key, map in pairs(self.keymaps or {}) do\n if not map.silent then\n table.insert(key_items, {\n key = key,\n desc = map.desc,\n })\n end\n end\n\n table.insert(key_items, {\n key = \"r\",\n desc = \"Refresh\",\n })\n table.insert(key_items, {\n key = \"R\",\n desc = \"Restart\",\n })\n -- Add common close\n table.insert(key_items, {\n key = \"q\",\n desc = \"Close\",\n })\n\n -- Format in a single line\n local keys_line = NuiLine()\n for i, key in ipairs(key_items) do\n if i > 1 then\n keys_line:append(\" \", Text.highlights.muted)\n end\n keys_line\n :append(\" \" .. key.key .. \" \", Text.highlights.header_shortcut)\n :append(\" \", Text.highlights.muted)\n :append(key.desc, Text.highlights.muted)\n end\n\n table.insert(lines, Text.pad_line(keys_line))\n\n return lines\nend\n\n--- Render view content\n--- Should be overridden by child views\n--- @return NuiLine[] Lines to render\nfunction View:render()\n -- Get base header\n local lines = self:render_header()\n\n -- Handle special states\n if State.setup_state == \"failed\" then\n if self:should_show_setup_error() then\n return self:render_setup_error(lines)\n end\n elseif State.setup_state == \"in_progress\" then\n if self:should_show_setup_error() then\n return self:render_setup_progress(lines)\n end\n elseif State.setup_state == \"not_started\" then\n if self:should_show_setup_error() then\n return self:render_default_setup(lines)\n end\n end\n\n -- Views should override this to provide content\n table.insert(lines, Text.pad_line(NuiLine():append(\"No content implemented for this view\", Text.highlights.muted)))\n\n return lines\nend\n\nfunction View:lock()\n vim.api.nvim_buf_set_option(self.ui.buffer, \"modifiable\", false)\nend\n\nfunction View:unlock()\n vim.api.nvim_buf_set_option(self.ui.buffer, \"modifiable\", true)\nend\n\nfunction View:open()\n return self.ui.window and vim.api.nvim_win_is_valid(self.ui.window)\nend\n\n--- Draw view content to buffer\nfunction View:draw()\n if not self:open() then\n return\n end\n\n -- Track cursor position before drawing\n self:track_cursor()\n\n -- Get buffer\n local buf = self.ui.buffer\n\n -- Reset view state\n self:clear_line_tracking()\n if self.cursor_highlight then\n vim.api.nvim_buf_del_extmark(self.ui.buffer, self.hover_ns, self.cursor_highlight)\n self.cursor_highlight = nil\n end\n\n -- Make buffer modifiable\n vim.api.nvim_buf_set_option(buf, \"modifiable\", true)\n\n -- Clear buffer\n vim.api.nvim_buf_set_lines(buf, 0, -1, false, {})\n\n -- Get content and footer lines\n local lines = self:render()\n local footer_lines = self:render_footer()\n\n -- Calculate if we need padding\n local win_height = vim.api.nvim_win_get_height(self.ui.window)\n local content_height = #lines\n local total_needed = win_height - content_height - #footer_lines\n\n -- Add padding if needed\n if total_needed > 0 then\n for _ = 1, total_needed do\n table.insert(lines, Text.empty_line())\n end\n end\n\n -- Add footer at the end\n vim.list_extend(lines, footer_lines)\n\n -- Render each line with proper highlights\n local line_idx = 1\n for _, line in ipairs(lines) do\n if type(line) == \"string\" then\n -- Handle string lines with potential newlines\n for _, l in ipairs(Text.multiline(line)) do\n ---@diagnostic disable-next-line: undefined-field\n l:render(buf, ns_id, line_idx)\n line_idx = line_idx + 1\n end\n else\n ---@diagnostic disable-next-line: undefined-field\n line:render(buf, ns_id, line_idx)\n line_idx = line_idx + 1\n end\n end\n\n -- Make buffer unmodifiable\n vim.api.nvim_buf_set_option(buf, \"wrap\", true)\n vim.api.nvim_buf_set_option(buf, \"modifiable\", false)\n\n -- Restore cursor position after drawing\n self:set_cursor()\nend\n\nreturn View\n"], ["/mcphub.nvim/lua/mcphub/ui/capabilities/resourceTemplate.lua", "local Base = require(\"mcphub.ui.capabilities.base\")\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal highlights = require(\"mcphub.utils.highlights\").groups\n\n---@class ResourceTemplateHandler : CapabilityHandler\nlocal ResourceTemplateHandler = setmetatable({}, {\n __index = Base,\n})\nResourceTemplateHandler.__index = ResourceTemplateHandler\nResourceTemplateHandler.type = \"resourceTemplate\"\n\nfunction ResourceTemplateHandler:new(server_name, capability_info, view)\n local handler = Base.new(self, server_name, capability_info, view)\n handler.state = vim.tbl_extend(\"force\", handler.state, {\n input_value = \"\",\n })\n return handler\nend\n\nfunction ResourceTemplateHandler:execute()\n -- Check if already executing\n if self.state.is_executing then\n vim.notify(\"Resource template access is already in progress\", vim.log.levels.WARN)\n return\n end\n if not self.state.input_value or vim.trim(self.state.input_value or \"\") == \"\" then\n self.state.error = \"URI is required\"\n self.view:draw()\n return\n end\n\n -- Set executing state\n self.state.is_executing = true\n self.state.error = nil\n self.view:draw()\n\n -- Access resource with user provided URI\n if State.hub_instance then\n State.hub_instance:access_resource(self.server_name, self.state.input_value, {\n caller = {\n type = \"hubui\",\n hubui = State.ui_instance,\n },\n parse_response = true,\n callback = function(response, err)\n self:handle_response(response, err)\n self.view:draw()\n end,\n })\n end\nend\n\nfunction ResourceTemplateHandler:handle_input_update(input)\n -- Update value\n self.state.input_value = input\n self.view:draw()\nend\n\nfunction ResourceTemplateHandler:handle_input_action()\n self:handle_input(string.format(\"URI: \"), self.state.input_value, function(input)\n self:handle_input_update(input)\n end)\nend\n\nfunction ResourceTemplateHandler:handle_text_box(line)\n local type = self:get_line_info(line)\n if type == \"input\" then\n self:open_text_box(\"Resource Template URI\", self.state.input_value or \"\", function(input)\n self:handle_input_update(input)\n end)\n end\nend\n\nfunction ResourceTemplateHandler:handle_action(line)\n local type = self:get_line_info(line)\n if type == \"submit\" then\n self:execute()\n elseif type == \"input\" then\n self:handle_input_action()\n end\nend\n\nfunction ResourceTemplateHandler:render(line_offset)\n line_offset = line_offset or 0\n -- Clear previous line tracking\n self:clear_line_tracking()\n\n local lines = {}\n\n -- Resource template info section\n vim.list_extend(lines, self:render_section_start(\"Template Information\"))\n\n -- Template details\n local details = {\n NuiLine()\n :append(\"Name: \", highlights.muted)\n :append(self.def.name or \"N/A\", self.def.name and highlights.success or highlights.muted),\n NuiLine():append(\"Template: \", highlights.muted):append(self.def.uriTemplate, highlights.info),\n }\n\n if self.def.mimeType then\n table.insert(details, NuiLine():append(\"Type: \", highlights.muted):append(self.def.mimeType, highlights.info))\n end\n\n vim.list_extend(lines, self:render_section_content(details, 2))\n\n table.insert(lines, Text.pad_line(NuiLine():append(\"│\", highlights.muted)))\n vim.list_extend(lines, self:render_section_content(Text.multiline(self:get_description(), highlights.muted), 2))\n\n vim.list_extend(lines, self:render_section_end())\n\n -- Action section\n table.insert(lines, Text.pad_line(NuiLine()))\n vim.list_extend(lines, self:render_section_start(\"Access Resource\"))\n\n -- Input field\n local input_line = NuiLine():append(\"> \", highlights.success):append(self.state.input_value or \"\", highlights.info)\n vim.list_extend(lines, self:render_section_content({ input_line }, 2))\n\n -- Track input line\n self:track_line(line_offset + #lines, \"input\")\n\n -- Action button\n local button_line\n if self.state.is_executing then\n button_line = NuiLine()\n :append(\"[ \", highlights.muted)\n :append(\"Processing...\", highlights.muted)\n :append(\" ]\", highlights.muted)\n else\n button_line = NuiLine()\n :append(\"[ \", highlights.success_fill)\n :append(\"Access\", highlights.success_fill)\n :append(\" ]\", highlights.success_fill)\n end\n vim.list_extend(lines, self:render_section_content({ NuiLine():append(\" \"), button_line }, 2))\n\n -- Track submit line for interaction\n self:track_line(line_offset + #lines, \"submit\")\n\n -- Error message if any\n if self.state.error then\n table.insert(lines, Text.pad_line(NuiLine():append(\"│\", highlights.muted)))\n local error_lines = Text.multiline(self.state.error, highlights.error)\n vim.list_extend(lines, self:render_section_content(error_lines, 2))\n end\n\n vim.list_extend(lines, self:render_section_end())\n\n -- Result section if any\n vim.list_extend(lines, self:render_result())\n\n return lines\nend\n\nreturn ResourceTemplateHandler\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/edit_session.lua", "-- EditSession - Main orchestrator for the editing workflow\n-- Coordinates parsing, location, and UI components\n\n---@class EditSession\n---@field origin_winnr number Window number where the session started\n---@field file_path string Path to the file being edited\n---@field diff_content string Raw diff content from LLM\n---@field config EditSessionConfig Configuration options\n---@field parser DiffParser Parser instance\n---@field locator BlockLocator Block locator instance\n---@field located_blocks LocatedBlock[] Located blocks after parsing and locating\n---@field ui EditUI? UI instance (created when needed)\n---@field callbacks table Success/error callbacks\nlocal EditSession = {}\nEditSession.__index = EditSession\n\nlocal Path = require(\"plenary.path\")\nlocal DEFAULT_CONFIG = {\n parser = {\n track_issues = true,\n extract_inline_content = true,\n },\n locator = {\n fuzzy_threshold = 0.8,\n enable_fuzzy_matching = true,\n },\n ui = {\n go_to_origin_on_complete = true,\n keybindings = {\n accept = \".\", -- Accept current change\n reject = \",\", -- Reject current change\n next = \"n\", -- Next diff\n prev = \"p\", -- Previous diff\n accept_all = \"ga\", -- Accept all remaining changes\n reject_all = \"gr\", -- Reject all remaining changes\n },\n },\n feedback = {\n include_parser_feedback = true,\n include_locator_feedback = true,\n include_ui_summary = true,\n ui = {\n include_session_summary = true,\n include_final_diff = true,\n send_diagnostics = true,\n wait_for_diagnostics = 500,\n diagnostic_severity = vim.diagnostic.severity.WARN, -- Only show warnings and above by default\n },\n },\n}\n\n-- Create new edit session\n---@param file_path string Path to file to edit\n---@param diff_content string Raw diff content\n---@param config EditSessionConfig? Optional configuration\n---@return EditSession\nfunction EditSession.new(file_path, diff_content, config)\n local self = setmetatable({}, EditSession)\n\n self.file_path = file_path\n self.diff_content = diff_content\n self.config = vim.tbl_deep_extend(\"force\", DEFAULT_CONFIG, config or {})\n\n self.origin_winnr = vim.api.nvim_get_current_win()\n -- Load components\n local DiffParser = require(\"mcphub.native.neovim.files.edit_file.diff_parser\")\n local BlockLocator = require(\"mcphub.native.neovim.files.edit_file.block_locator\")\n\n self.parser = DiffParser.new(self.config.parser)\n self.locator = BlockLocator.new(self.config.locator)\n\n return self\nend\n\n--- Get the content of the buffer if available or read from file\n---@param path string Path to the file\n---@param bufnr number? Buffer number to read from (if available)\n---@return string content File content or nil if not found\nfunction EditSession:get_file_content(path, bufnr)\n --INFO: unloaded buffers return empty lines\n if bufnr and vim.api.nvim_buf_is_valid(bufnr) and vim.api.nvim_buf_is_loaded(bufnr) then\n return table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, false), \"\\n\")\n end\n\n local file_path = Path:new(path)\n if file_path:exists() and file_path:is_file() then\n return file_path:read()\n end\n return \"\"\nend\n\n--- Start the editing session\n---@param options table Options including on_success, on_error callbacks\nfunction EditSession:start(options)\n self.callbacks = {\n on_success = options.on_success or function() end,\n on_error = options.on_error or function() end,\n }\n local buf_utils = require(\"mcphub.native.neovim.utils.buffer\")\n local buf_info = buf_utils.find_buffer(self.file_path) or {}\n local file_content = self:get_file_content(self.file_path, buf_info.bufnr)\n local is_replacing_entire_file = options.replace_file_content ~= nil\n\n ---@type ParsedBlock[]\n local parsed_blocks = {}\n --- Needed to avoid parsing error when the file content has markers\n if is_replacing_entire_file then\n table.insert(parsed_blocks, {\n block_id = \"Block 1\",\n search_content = \"\",\n search_lines = {},\n replace_content = options.replace_file_content,\n replace_lines = vim.split(options.replace_file_content, \"\\n\", { plain = true, trimempty = true }),\n }--[[@as ParsedBlock]])\n else\n local _parsed_blocks, parse_error = self.parser:parse(self.diff_content)\n if not _parsed_blocks then\n return self:_handle_error(\"Failed to parse diff: \" .. parse_error)\n end\n parsed_blocks = _parsed_blocks\n end\n\n for _, block in ipairs(parsed_blocks) do\n if vim.trim(block.search_content) == \"\" then\n if #parsed_blocks > 1 then\n return self:_handle_error(\n string.format(\n \"A Block with empty search content found, but multiple blocks are present in the diff. %s will replace the entire file. If you want to write the entire file, please use a single SEARCH/REPLACE block with empty SEARCH content. If you want to replace a section of the file, please provide non-whitespace SEARCH content.\",\n block.block_id\n )\n )\n end\n is_replacing_entire_file = true\n break\n else\n -- If we are searching for something in a file that doesn't exist, we should not proceed\n if file_content == \"\" then\n return self:_handle_error(\n string.format(\n \"Editing `%s` failed. The file does not exist. If you are using relative paths make sure the path is relative to the cwd or use an absolute path.\",\n self.file_path\n )\n )\n end\n end\n end\n\n local located_blocks = self.locator:locate_all_blocks(parsed_blocks, file_content)\n self.located_blocks = located_blocks\n\n local failed_blocks = vim.tbl_filter(function(block)\n return not block.location_result.found\n end, located_blocks)\n if #failed_blocks > 0 then\n return self:_handle_error(\n string.format(\n \"## Editing `%s` failed. No changes were made to the file. Couldn't find %d of %d block(s). Please see the content provided in the SEARCHING feedback.\",\n self.file_path,\n #failed_blocks,\n #located_blocks\n )\n )\n end\n\n local EditUI = require(\"mcphub.native.neovim.files.edit_file.edit_ui\")\n self.ui = EditUI.new(self.config.ui)\n\n self.ui:start_interactive_editing({\n interactive = options.interactive ~= false,\n is_replacing_entire_file = is_replacing_entire_file,\n origin_winnr = self.origin_winnr,\n file_path = self.file_path,\n located_blocks = self.located_blocks,\n original_content = file_content,\n on_complete = function()\n self:_generate_final_report(false, function(report)\n self.callbacks.on_success(\"# EDIT SESSION\\n\\n\" .. report)\n self.ui:cleanup()\n end)\n end,\n on_cancel = function(reason)\n self:_generate_final_report(true, function(feedback_report)\n local final_report = string.format(\n \"# EDIT SESSION\\n\\n%s%s\",\n reason or \"User rejected the changes to the file\",\n feedback_report ~= \"\" and (\"\\n\\n\" .. feedback_report) or \"\"\n )\n self.callbacks.on_error(final_report)\n self.ui:cleanup()\n end)\n end,\n })\nend\n\n-- Handle errors with comprehensive feedback\n---@param error_msg string Error message\nfunction EditSession:_handle_error(error_msg)\n self:_generate_final_report(true, function(feedback_report)\n local final_report = string.format(\n \"# EDIT SESSION\\n\\n%s%s\",\n error_msg or \"User rejected the changes to the file\",\n feedback_report ~= \"\" and (\"\\n\\n\" .. feedback_report) or \"\"\n )\n self.callbacks.on_error(final_report)\n end)\nend\n\n-- Generate final report by orchestrating feedback from all components\n---@param is_cancelled boolean Whether the session was cancelled\n---@param on_report_ready function Callback to receive the final report\nfunction EditSession:_generate_final_report(is_cancelled, on_report_ready)\n local feedback_parts = {}\n local feedback_config = self.config.feedback\n\n -- Get Parser Feedback\n if feedback_config.include_parser_feedback then\n local parser_feedback = self.parser:get_feedback()\n if parser_feedback then\n table.insert(feedback_parts, parser_feedback)\n end\n end\n\n -- Get Locator Feedback\n if feedback_config.include_locator_feedback then\n local locator_feedback = self.locator:get_feedback(self.located_blocks)\n if locator_feedback then\n table.insert(feedback_parts, locator_feedback)\n end\n end\n\n -- Get UI Summary (Asynchronous due to waiting for diagnostics)\n if feedback_config.include_ui_summary and self.ui and not is_cancelled then\n self.ui:get_summary(feedback_config.ui, function(ui_summary)\n if ui_summary and ui_summary ~= \"\" then\n table.insert(feedback_parts, ui_summary)\n end\n on_report_ready(table.concat(feedback_parts, \"\\n\\n\"))\n end)\n else\n on_report_ready(table.concat(feedback_parts, \"\\n\\n\"))\n end\nend\n\nreturn EditSession\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/search.lua", "local Path = require(\"plenary.path\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal scan = require(\"plenary.scandir\")\n\n-- Get file info utility\nlocal function get_file_info(path)\n local fullpath = vim.fn.expand(path)\n local stat = vim.loop.fs_stat(fullpath)\n if not stat then\n return nil, \"File not found: \" .. path\n end\n\n return {\n name = vim.fn.fnamemodify(fullpath, \":t\"),\n path = fullpath,\n size = stat.size,\n type = stat.type,\n modified = stat.mtime.sec,\n permissions = stat.mode,\n is_readonly = not vim.loop.fs_access(fullpath, \"W\"),\n }\nend\n\n---@type MCPTool[]\nlocal search_tools = {\n {\n name = \"find_files\",\n description = \"Search for files by pattern\",\n inputSchema = {\n type = \"object\",\n properties = {\n pattern = {\n type = \"string\",\n description = \"Search pattern (e.g. *.lua)\",\n },\n path = {\n type = \"string\",\n description = \"Directory to search in\",\n default = \".\",\n },\n recursive = {\n type = \"boolean\",\n description = \"Search recursively\",\n default = true,\n },\n },\n required = { \"pattern\" },\n },\n handler = function(req, res)\n local params = req.params\n if not params.pattern or params.pattern == \"\" then\n return res:error(\"Pattern is required for file search\")\n end\n -- local path = vim.fn.expand(params.path or \".\")\n local path = Path:new(params.path or \".\"):absolute()\n local pattern = params.pattern\n\n -- Build glob pattern\n local glob = vim.fn.fnamemodify(path, \":p\")\n if params.recursive then\n glob = glob .. \"**/\"\n end\n glob = glob .. pattern\n\n -- Find files\n local files = vim.fn.glob(glob, true, true)\n if #files == 0 then\n return res:text(\"No files found matching: \" .. pattern):send()\n end\n\n -- Get file info\n local results = {}\n for _, file in ipairs(files) do\n local ok, info = pcall(get_file_info, file)\n if ok and info then\n table.insert(results, info)\n end\n end\n\n -- Format results\n local text = string.format(\"%s Search Results: %s\\n%s\\n\", Text.icons.search, pattern, string.rep(\"-\", 40))\n\n for _, info in ipairs(results) do\n local icon = info.type == \"directory\" and Text.icons.folder or Text.icons.file\n text = text .. string.format(\"%s %s\\n\", icon, info.path)\n end\n\n text = text .. string.format(\"\\nFound %d matches\", #results)\n return res:text(text):send()\n end,\n },\n {\n name = \"list_directory\",\n description = \"List files and directories in a path\",\n inputSchema = {\n type = \"object\",\n properties = {\n path = {\n type = \"string\",\n description = \"Directory path to list\",\n default = \".\",\n },\n },\n },\n handler = function(req, res)\n local params = req.params\n local path = Path:new(params.path or \".\"):absolute()\n local depth = nil\n local hidden = false\n local respect_gitignore = true\n local include_dirs = false\n local scan_opts = {\n hidden = hidden,\n depth = depth,\n respect_gitignore = respect_gitignore,\n add_dirs = include_dirs,\n }\n\n local results = scan.scan_dir(path, scan_opts)\n\n if #results == 0 then\n return res:text(\"No files found in: \" .. path):send()\n end\n\n -- Get file info for each result\n local file_results = {}\n for _, file in ipairs(results) do\n local ok, info = pcall(get_file_info, file)\n if ok and info then\n table.insert(file_results, info)\n end\n end\n\n -- Format results\n local text = string.format(\"%s Directory Listing: %s\\n%s\\n\", Text.icons.folder, path, string.rep(\"-\", 40))\n\n for _, info in ipairs(file_results) do\n local icon = info.type == \"directory\" and Text.icons.folder or Text.icons.file\n local relative_path = info.path:sub(#path + 2)\n text = text .. string.format(\"%s %s\\n\", icon, relative_path)\n end\n\n text = text .. string.format(\"\\nFound %d items\", #file_results)\n return res:text(text):send()\n end,\n },\n}\n\nreturn search_tools\n"], ["/mcphub.nvim/lua/mcphub/types.lua", "---@meta\n---@class MarketplaceItem\n---@field id string\n---@field name string\n---@field author string\n---@field description string\n---@field url string\n---@field license? string\n---@field category string\n---@field tags string[]\n---@field installations MarketplaceInstallation[]\n---@field featured? boolean\n---@field verified? boolean\n---@field stars? integer\n---@field lastCommit? integer\n---@field updatedAt? integer\n\n---@class MarketplaceInstallation\n---@field name string\n---@field description? string\n---@field config string\n---@field prerequisites? string[]\n---@field parameters? MarketplaceParameter[]\n---@field transports? string[]\n\n---@class MarketplaceParameter\n---@field name string\n---@field key string\n---@field description? string\n---@field placeholder? string\n---@field required? boolean\n\n---@class CustomMCPServerConfig.CustomInstructions\n---@field text string\n---@field disabled? string\n\n---@class CustomMCPServerConfig\n---@field disabled? boolean\n---@field disabled_tools? string[]\n---@field disabled_prompts? string[]\n---@field disabled_resources? string[]\n---@field disabled_resourceTemplates? string[]\n---@field custom_instructions? CustomMCPServerConfig.CustomInstructions\n---@field autoApprove? boolean|string[] -- true for all tools, array of tool names for specific tools\n\n---@class MCPServerConfig: CustomMCPServerConfig\n---@field command? string\n---@field args? table\n---@field env? table\n---@field cwd? string\n---@field headers? table\n---@field url? string\n\n---@class NativeMCPServerConfig : CustomMCPServerConfig\n\n---@class MCPServer\n---@field name string\n---@field displayName string\n---@field description string\n---@field transportType string\n---@field status MCPHub.Constants.ConnectionStatus\n---@field error string\n---@field capabilities MCPCapabilities\n---@field uptime number\n---@field lastStarted string\n---@field authorizationUrl string\n---@field config_source string Include which config file this server came from\n\n---@class LogEntry\n---@field type string\n---@field message string\n---@field timestamp number\n---@field data table\n---@field code number\n\n---@class MCPResponseOutput\n---@field text string\n---@field images table[]\n---@field blobs table[]\n---@field audios table[]\n---@field error? string\n\n---@class EnhancedMCPPrompt : MCPPrompt\n---@field server_name string\n\n---@class EnhancedMCPResourceTemplate : MCPResourceTemplate\n---@field server_name string\n\n---@class EnhancedMCPResource : MCPResource\n---@field server_name string\n\n---@class EnhancedMCPTool : MCPTool\n---@field server_name string\n\n---@class MCPRequestOptions\n---@field timeout? number\n---@field resetTimeoutOnProgress? boolean\n---@field maxTotalTimeout? number\n\n---@class MCPHub.JobContext\n---@field cwd string -- Current working directory for the job\n---@field port number -- Port to connect to the MCP server\n---@field config_files string[] -- List of configuration files used to start the Hub including the project config and global\n---@field is_workspace_mode boolean -- Whether the job is running in workspace mode\n---@field workspace_root string? -- Root directory of the workspace if in workspace mode\n---@field existing_hub MCPHub.WorkspaceDetails? -- Details of an existing hub if applicable\n\n---@class MCPHub.Workspaces\n---@field current string? -- Name of the current workspace\n---@field allActive table? -- Map of workspace names to their details\n\n---@class MCPHub.WorkspaceDetails\n---@field pid number -- Process ID of the mcp-hub server\n---@field port number -- Port the mcp-hub server is running on\n---@field config_files string[] -- List of configuration files used to start the Hub including the project config and global\n---@field startTime string -- ISO 8601 formatted start time of the workspace\n---@field cwd string -- Current working directory of the mcp-hub\n---@field shutdownDelay number? -- Optional delay before the workspace is shut down after inactivity\n---@field state \"active\" | \"shutting_down\" -- Current state of the workspace\n---@field activeConnections number -- Number of active connections to the workspace\n"], ["/mcphub.nvim/lua/mcphub/extensions/codecompanion/xml_tool.lua", "--[[\n*MCP Servers Tool*\nThis tool can be used to call tools and resources from the MCP Servers.\n--]]\nlocal M = {}\n\nlocal tool_schemas = {\n use_mcp_tool = {\n tool = {\n _attr = {\n name = \"use_mcp_tool\",\n },\n action = {\n server_name = \"\",\n tool_name = \"\",\n tool_input = '',\n },\n },\n },\n access_mcp_resource = {\n tool = {\n _attr = {\n name = \"access_mcp_resource\",\n },\n action = {\n server_name = \"\",\n uri = \"\",\n },\n },\n },\n}\n\n---@param hub MCPHub.Hub\n---@return string\nfunction M.system_prompt(hub)\n local xmlok, xml2lua = pcall(require, \"codecompanion.utils.xml.xml2lua\")\n local prompts = hub:generate_prompts(xmlok and {\n use_mcp_tool_example = xml2lua.toXml({ tools = { tool_schemas.use_mcp_tool } }),\n access_mcp_resource_example = xml2lua.toXml({ tools = { tool_schemas.access_mcp_resource } }),\n } or {})\n return string.format(\n [[### `use_mcp_tool` Tool and `access_mcp_resource` Tool\n\n⚠️ **CRITICAL INSTRUCTIONS - READ CAREFULLY** ⚠️\n\nThe Model Context Protocol (MCP) enables communication with locally running MCP servers that provide additional tools and resources to extend your capabilities.\n\n1. **ONE TOOL CALL PER RESPONSE**:\n - YOU MUST MAKE ONLY ONE TOOL CALL PER RESPONSE\n - NEVER chain multiple tool calls in a single response\n - For tasks requiring multiple tools, you MUST wait for the result of each tool before proceeding\n\n2. **ONLY USE AVAILABLE SERVERS AND TOOLS**:\n - ONLY use the servers and tools listed in the \"Connected MCP Servers\" section below\n - DO NOT invent or hallucinate server names, tool names, or resource URIs\n - If a requested server or tool is not listed in \"Connected MCP Servers\", inform the user it's not available\n\n3. **GATHER REQUIRED INFORMATION FIRST**:\n - NEVER use placeholder values for parameters e.g {\"id\": \"YOUR_ID_HERE\"}\n - NEVER guess or make assumptions about parameters like IDs, or file paths etc\n - Before making tool calls:\n * CALL other tools to get the required information first e.g listing available files or database pages before writing to them.\n * ASK the user for needed information if not provided\n\n4. **Dependent Operations Workflow**:\n - Step 1: Make ONE tool call\n - Step 2: WAIT for the user to show you the result\n - Step 3: Only THEN, in a NEW response, make the next tool call\n\n5. **Forbidden Pattern Examples**:\n ❌ DO NOT DO THIS: Multiple blocks in one response\n ❌ DO NOT DO THIS: Using placeholder values or made-up while calling tools e.g {\"id\": \"YOUR_ID_HERE\"}\n\n6. **Correct Pattern Examples**:\n ✅ DO THIS: List available resources first → Wait for result → Use correct parameters\n ✅ DO THIS: Verify parameters are correct before making tool calls\n ✅ DO THIS: Ask for clarification when user requests are unclear\n\n7. **XML Structure Requirements**:\n - Format: ```xml```\n - Must always enclose tag inside ```xml``` codeblock\n - When using the tool: The following are a MUST\n * The server_name child tag must be provided with a valid server name\n * The tool_name child tag must be provided with a valid tool name of the server_name\n * The tool_input child tag must be always be a JSON object with the required parameters from the tool_name's inputSchema\n e.g: %s\n - When using the tool: The following are a MUST\n * The server_name child tag must be provided with a valid server name\n * The uri attribute child tag be provided with a valid resource URI in the server_name\n\n\n8. **Examples**:\n\n%s\n\n%s\n\n\n]],\n '',\n prompts.use_mcp_tool,\n prompts.access_mcp_resource\n )\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/utils/log.lua", "local M = {}\n\n--- @class LogConfig\n--- @field level number Default log level\n--- @field to_file boolean Whether to log to file\n--- @field file_path? string Path to log file\n--- @field prefix string Prefix for log messages\nlocal config = {\n level = vim.log.levels.ERROR,\n to_file = false,\n file_path = nil,\n prefix = \"MCPHub\",\n}\n\n--- Setup logger configuration\n--- @param opts LogConfig\nfunction M.setup(opts)\n config = vim.tbl_deep_extend(\"force\", config, opts or {})\n\n -- Create log directory if logging to file\n if config.to_file and config.file_path then\n local path = vim.fn.fnamemodify(config.file_path, \":h\")\n vim.fn.mkdir(path, \"p\")\n end\nend\n\n--- Format structured message\n--- @param msg string|table Message or structured data\n--- @param level_str string Level string for log prefix\n--- @return string formatted_message\nlocal function format_message(msg, level_str)\n local str = \"\"\n if type(msg) == \"table\" then\n -- Handle structured logs (from server)\n if msg.code and msg.message then\n local base = string.format(\"[%s] %s\", msg.code, msg.message)\n if msg.data then\n str = string.format(\"%s\\nData: %s\", base, vim.inspect(msg.data))\n else\n str = base\n end\n end\n -- Regular table data\n str = vim.inspect(msg)\n else\n str = msg\n end\n return str\nend\n\n--- Write to log file\n--- @param formatted string Formatted message\n--- @param level_str string Level string\n--- @param level number Log level\n--- @return boolean success Whether the write was successful\nlocal function write_to_file(formatted, level_str, level)\n -- Only write if:\n -- 1. File logging is enabled and path is set\n -- 2. Level meets minimum configured level\n if not (config.to_file and config.file_path) or level < config.level then\n return false\n end\n\n local timestamp = os.date(\"%H:%M:%S\")\n local log_line = string.format(\"(%s) %s [%s] %s\\n\", vim.fn.getpid(), timestamp, level_str, formatted)\n\n local f = io.open(config.file_path, \"a\")\n if f then\n f:write(log_line)\n f:close()\n return true\n end\n return false\nend\n\n--- Internal logging function\n--- @param msg string|table Message or structured data\n--- @param level number Log level\nlocal function log_internal(msg, level)\n -- Early return if below configured level and not an error\n if level < config.level and level < vim.log.levels.ERROR then\n return\n end\n\n local level_str = ({\n [vim.log.levels.DEBUG] = \"debug\",\n [vim.log.levels.INFO] = \"info\",\n [vim.log.levels.WARN] = \"warn\",\n [vim.log.levels.ERROR] = \"error\",\n [vim.log.levels.TRACE] = \"trace\",\n })[level] or \"unknown\"\n\n local formatted = format_message(msg, level_str:upper())\n local wrote_to_file = write_to_file(formatted, level_str:upper(), level)\n\n -- Only notify if:\n -- 1. It's an error (always show errors) OR\n -- 2. Level meets minimum AND we didn't write to file\n if level >= vim.log.levels.ERROR or (level >= config.level and not wrote_to_file) then\n vim.schedule(function()\n vim.notify(formatted, level)\n end)\n end\nend\n\n--- Log a debug message\n--- @param msg string|table\nfunction M.debug(msg)\n log_internal(msg, vim.log.levels.DEBUG)\nend\n\n--- Log an info message\n--- @param msg string|table\nfunction M.info(msg)\n log_internal(msg, vim.log.levels.INFO)\nend\n\n--- Log a warning message\n--- @param msg string|table\nfunction M.warn(msg)\n log_internal(msg, vim.log.levels.WARN)\nend\n\n--- Log an error message\n--- @param msg string|table\nfunction M.error(msg)\n log_internal(msg, vim.log.levels.ERROR)\nend\n\nfunction M.trace(msg)\n log_internal(msg, vim.log.levels.TRACE)\nend\n\n--- Log with call stack information\n--- @param msg string|table Message to log\n--- @param level? number Log level (default: DEBUG)\nfunction M.stack(msg, level)\n level = level or vim.log.levels.DEBUG\n\n -- Get call stack starting from level 3 to skip this function and log_internal\n local stack = {}\n local stack_level = 3\n\n while true do\n local info = debug.getinfo(stack_level, \"Snl\")\n if not info then\n break\n end\n\n local location = info.short_src .. \":\" .. (info.currentline or \"?\")\n local func_name = info.name or \"\"\n\n table.insert(stack, string.format(\" %s in %s\", location, func_name))\n stack_level = stack_level + 1\n\n -- Limit stack depth to prevent spam\n if #stack >= 10 then\n table.insert(stack, \" ...\")\n break\n end\n end\n\n local formatted_msg = msg\n if #stack > 0 then\n formatted_msg = msg .. \"\\nCall stack:\\n\" .. table.concat(stack, \"\\n\")\n end\n\n log_internal(formatted_msg, level)\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/ui/init.lua", "---[[\n--- UI Core for MCPHub\n--- Handles window/buffer management and view system\n---]]\nlocal State = require(\"mcphub.state\")\nlocal hl = require(\"mcphub.utils.highlights\")\nlocal utils = require(\"mcphub.utils\")\n\n---@class MCPHub.UI\n---@field window number Window handle\n---@field buffer number Buffer handle\n---@field current_view MCPHub.UI.ViewName Current view name\n---@field views table Table of view instances\n---@field is_shown boolean Whether the UI is currently visible\n---@field cursor_states table Store cursor positions by view name\n---@field context table Context from which the UI was opened\n---@field opts MCPHub.UIConfig Configuration options for UI\nlocal UI = {}\nUI.__index = UI\n\n---@enum MCPHub.UI.ViewName\nlocal ViewName = {\n MAIN = \"main\",\n LOGS = \"logs\",\n HELP = \"help\",\n CONFIG = \"config\",\n MARKETPLACE = \"marketplace\",\n}\n\n-- Default window settings\n---@class MCPHub.UIConfig\nlocal defaults = {\n window = {\n width = 0.8, -- 0-1 (ratio); \"50%\" (percentage); 50 (raw number)\n height = 0.8, -- 0-1 (ratio); \"50%\" (percentage); 50 (raw number)\n align = \"center\", -- \"center\", \"top-left\", \"top-right\", \"bottom-left\", \"bottom-right\", \"top\", \"bottom\", \"left\", \"right\"\n border = \"rounded\", -- \"none\", \"single\", \"double\", \"rounded\", \"solid\", \"shadow\"\n relative = \"editor\",\n zindex = 50,\n },\n ---@type table?\n wo = { -- window-scoped options (vim.wo)\n },\n}\n\n-- Parse size value into actual numbers\n---@param value any Size value (number, float, or percentage string)\n---@param total number Total available size\n---@return number Calculated size\nlocal function parse_size(value, total)\n if type(value) == \"number\" then\n if value <= 1 then -- Ratio\n return math.floor(total * value)\n end\n return math.floor(value) -- Raw number\n elseif type(value) == \"string\" then\n -- Parse percentage (e.g., \"80%\")\n local percent = tonumber(value:match(\"(%d+)%%\"))\n if percent then\n return math.floor((total * percent) / 100)\n end\n end\n return math.floor(total * 0.8) -- Default fallback\nend\n\n--- Create a new UI instance\n---@param opts? MCPHub.UIConfig Configuration options for UI\n---@return MCPHub.UI\nfunction UI:new(opts)\n local instance = {\n window = nil, -- Window handle\n buffer = nil, -- Buffer handle\n current_view = nil, -- Current view name\n views = {}, -- View instances\n is_shown = false, -- Whether the UI is currently visible\n cursor_states = {}, -- Store cursor positions by view name\n context = {}, -- Context from which the UI was opened\n }\n setmetatable(instance, self)\n\n self.opts = vim.tbl_deep_extend(\"force\", defaults, opts or {})\n\n -- Initialize views\n instance:init_views()\n\n -- Subscribe to state changes\n State:subscribe(function(_, changes)\n if instance.window and vim.api.nvim_win_is_valid(instance.window) then\n -- Check if we need to update\n local should_update = false\n local keys = {\n \"server_output\",\n \"setup_state\",\n \"server_state\",\n \"marketplace_state\",\n \"config_files_cache\",\n \"logs\",\n \"errors\",\n }\n for k, _ in pairs(changes) do\n if vim.tbl_contains(keys, k) then\n --if connected then only update the logs view for logs updates\n if k == \"logs\" and State:is_connected() then\n if instance.current_view == \"logs\" then\n should_update = true\n else\n should_update = false\n end\n else\n should_update = true\n end\n break\n end\n end\n if should_update then\n instance:render()\n end\n end\n end, { \"ui\", \"server\", \"logs\", \"setup\", \"errors\", \"marketplace\" })\n\n -- Create cleanup autocommands\n local group = vim.api.nvim_create_augroup(\"mcphub_ui\", { clear = true })\n\n -- Handle VimLeave\n vim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = group,\n callback = function()\n instance:cleanup()\n end,\n })\n\n -- Handle window resize\n vim.api.nvim_create_autocmd(\"VimResized\", {\n group = group,\n callback = function()\n if instance.window and vim.api.nvim_win_is_valid(instance.window) then\n instance:resize_window()\n end\n end,\n })\n\n -- Handle window close\n vim.api.nvim_create_autocmd(\"WinClosed\", {\n group = group,\n callback = function(args)\n if instance.window and tonumber(args.match) == instance.window then\n instance:cleanup()\n end\n end,\n })\n\n return instance\nend\n\n--- Initialize views\n---@private\nfunction UI:init_views()\n local MainView = require(\"mcphub.ui.views.main\")\n\n -- Create view instances\n self.views = {\n main = MainView:new(self),\n logs = require(\"mcphub.ui.views.logs\"):new(self),\n help = require(\"mcphub.ui.views.help\"):new(self),\n config = require(\"mcphub.ui.views.config\"):new(self),\n marketplace = require(\"mcphub.ui.views.marketplace\"):new(self),\n }\n\n -- Set initial view\n self.current_view = \"main\"\nend\n\n--- Create a new buffer for the UI\n---@private\nfunction UI:create_buffer()\n self.buffer = vim.api.nvim_create_buf(false, true)\n\n -- Set buffer options\n vim.api.nvim_buf_set_option(self.buffer, \"modifiable\", false)\n vim.api.nvim_buf_set_option(self.buffer, \"bufhidden\", \"wipe\")\n vim.api.nvim_buf_set_option(self.buffer, \"filetype\", \"mcphub\")\n vim.api.nvim_buf_set_option(self.buffer, \"wrap\", true)\n\n -- Set buffer mappings\n self:setup_keymaps()\n\n return self.buffer\nend\n\n--- Calculate window dimensions and position\n---@private\nfunction UI:calculate_window_dimensions()\n local min_width = 50\n local min_height = 10\n local win_opts = self.opts.window\n\n -- Calculate dimensions\n local width = parse_size(win_opts.width, vim.o.columns)\n width = math.max(min_width, width)\n\n local height = parse_size(win_opts.height, vim.o.lines)\n height = math.max(min_height, height)\n\n -- Calculate position based on alignment\n local row, col\n local align = win_opts.align or \"center\"\n\n if align == \"center\" then\n row = math.floor((vim.o.lines - height) / 2)\n col = math.floor((vim.o.columns - width) / 2)\n elseif align == \"top-left\" then\n row = 1\n col = 1\n elseif align == \"top-right\" then\n row = 1\n col = vim.o.columns - width\n elseif align == \"bottom-left\" then\n row = vim.o.lines - height\n col = 1\n elseif align == \"bottom-right\" then\n row = vim.o.lines - height\n col = vim.o.columns - width\n elseif align == \"top\" then\n row = 1\n col = math.floor((vim.o.columns - width) / 2)\n elseif align == \"bottom\" then\n row = vim.o.lines - height\n col = math.floor((vim.o.columns - width) / 2)\n elseif align == \"left\" then\n row = math.floor((vim.o.lines - height) / 2)\n col = 1\n elseif align == \"right\" then\n row = math.floor((vim.o.lines - height) / 2)\n col = vim.o.columns - width\n else\n -- Default to center for unknown alignment\n row = math.floor((vim.o.lines - height) / 2)\n col = math.floor((vim.o.columns - width) / 2)\n end\n\n return {\n width = width,\n height = height,\n row = row,\n col = col,\n }\nend\n\n--- Resize the window when editor is resized\n---@private\nfunction UI:resize_window()\n if not self.window or not vim.api.nvim_win_is_valid(self.window) then\n return\n end\n vim.api.nvim_win_set_config(self.window, self:get_window_config())\n -- Force a re-render of the current view\n self:render()\nend\n\nfunction UI:get_window_config()\n local dims = self:calculate_window_dimensions()\n local win_opts = self.opts.window\n\n return {\n relative = win_opts.relative,\n width = dims.width,\n height = dims.height,\n row = dims.row,\n col = dims.col,\n style = \"minimal\",\n border = win_opts.border,\n zindex = win_opts.zindex,\n }\nend\n\n--- Create a floating window\n---@private\n---@return number Window handle\nfunction UI:create_window()\n if not self.buffer or not vim.api.nvim_buf_is_valid(self.buffer) then\n self:create_buffer()\n end\n\n -- Create floating window\n self.window = vim.api.nvim_open_win(self.buffer, true, self:get_window_config())\n\n for k, v in pairs(self.opts.wo or {}) do\n vim.api.nvim_set_option_value(k, v, { scope = \"local\", win = self.window })\n end\n\n return self.window\nend\n\n--- Set up view-specific keymaps\nfunction UI:setup_keymaps()\n local function map(key, action, desc)\n vim.keymap.set(\"n\", key, action, {\n buffer = self.buffer,\n desc = desc,\n nowait = true,\n })\n end\n\n -- Global navigation\n map(\"H\", function()\n self:switch_view(\"main\")\n end, \"Switch to Home view\")\n map(\"M\", function()\n self:switch_view(\"marketplace\")\n end, \"Switch to Marketplace\")\n\n map(\"C\", function()\n self:switch_view(\"config\")\n end, \"Switch to Config view\")\n\n map(\"L\", function()\n self:switch_view(\"logs\")\n end, \"Switch to Logs view\")\n\n map(\"?\", function()\n self:switch_view(\"help\")\n end, \"Switch to Help view\")\n\n -- Close window\n map(\"q\", function()\n self:cleanup()\n end, \"Close\")\n\n map(\"r\", function()\n self:hard_refresh()\n end, \"Refresh\")\n map(\"R\", function()\n self:restart()\n end, \"Restart\")\nend\n\nfunction UI:refresh()\n if State.hub_instance then\n vim.notify(\"Refreshing\")\n if State.hub_instance:refresh() then\n vim.notify(\"Refreshed\")\n else\n vim.notify(\"Failed to refresh\")\n end\n else\n vim.notify(\"No hub instance available\")\n end\nend\n\nfunction UI:restart()\n if State.hub_instance then\n State.hub_instance:restart(function(success)\n if success then\n vim.notify(\"Restarting...\")\n else\n vim.notify(\"Failed to restart\")\n end\n end)\n vim.schedule(function()\n self:switch_view(\"main\")\n end)\n else\n vim.notify(\"No hub instance available\")\n end\nend\n\nfunction UI:hard_refresh()\n if State.hub_instance then\n vim.notify(\"Updating all server capabilities\")\n State.hub_instance:hard_refresh(function(success)\n if success then\n vim.notify(\"Refreshed\")\n else\n vim.notify(\"Failed to refresh\")\n end\n end)\n else\n vim.notify(\"No hub instance available\")\n end\nend\n\n--- Clean up resources\nfunction UI:cleanup()\n if not (self.window and vim.api.nvim_win_is_valid(self.window)) then\n return\n end\n\n -- Clean up buffer if it exists\n if self.buffer and vim.api.nvim_buf_is_valid(self.buffer) then\n vim.api.nvim_buf_delete(self.buffer, { force = true })\n end\n\n -- Close window if it exists\n if self.window and vim.api.nvim_win_is_valid(self.window) then\n vim.api.nvim_win_close(self.window, true)\n end\n self.buffer = nil\n self.window = nil\n self.is_shown = false\nend\n\n--- Toggle UI visibility\n--- @param args? table\nfunction UI:toggle(args)\n if self.window and vim.api.nvim_win_is_valid(self.window) then\n self:cleanup()\n else\n self:show(args)\n end\nend\n\n--- Switch to a different view\n---@param view_name MCPHub.UI.ViewName Name of view to switch to\nfunction UI:switch_view(view_name)\n -- Leave current view if any\n if self.current_view and self.views[self.current_view] and self.is_shown then\n self.views[self.current_view]:before_leave()\n self.views[self.current_view]:after_leave()\n end\n\n -- Switch view\n self.current_view = view_name\n\n -- Enter new view\n if self.views[view_name] then\n self.views[view_name]:before_enter()\n self.views[view_name]:draw()\n self.views[view_name]:after_enter()\n end\nend\n\n--- Show the UI window\n--- @param args? table\nfunction UI:show(args)\n self.context = utils.get_buf_info(vim.api.nvim_get_current_buf(), args)\n -- Create/show window if needed\n if not self.window or not vim.api.nvim_win_is_valid(self.window) then\n self:create_window()\n end\n -- Focus window\n vim.api.nvim_set_current_win(self.window)\n\n -- Draw current view\n self:render()\n self.is_shown = true\nend\n\n--- Render current view\n---@private\nfunction UI:render()\n self:switch_view(self.current_view)\nend\n\nreturn UI\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/issue_tracker.lua", "-- Issue Tracker for Editor Operations\n-- Tracks parsing and processing issues and provides feedback to LLMs\n\nlocal M = {}\n\n-- Issue types that can be tracked and reported back to LLM\nM.ISSUE_TYPES = {\n EXTRA_SPACES_IN_MARKERS = {\n description = \"Extra spaces found in search/replace markers\",\n fix = \"Normalized marker spacing\",\n llm_guidance = \"Use exactly one space: '<<<<<<< SEARCH' not '<<<<<<< SEARCH'\",\n severity = \"warning\",\n },\n\n CASE_MISMATCH_MARKERS = {\n description = \"Inconsistent case in SEARCH/REPLACE keywords\",\n fix = \"Converted to uppercase\",\n llm_guidance = \"Always use uppercase: 'SEARCH' and 'REPLACE'\",\n severity = \"warning\",\n },\n\n MISSING_SPACES_IN_MARKERS = {\n description = \"No space between markers and keywords\",\n fix = \"Added missing space\",\n llm_guidance = \"Use space: '<<<<<<< SEARCH' not '<<<<<<`\"\n .. (\n inline_content ~= \"\" and \" and content on that line is used as first line in the SEARCH block.\"\n or \"\"\n ),\n llm_guidance = \"`<<<<<<< SEARCH` marker line should be EXACT without any other characters like `>` or other content on the marker lines\",\n severity = \"warning\",\n }\n end,\n}\n\n---@class IssueTracker\n---@field issues_found ParsingIssue[] List of tracked issues\nlocal IssueTracker = {}\nIssueTracker.__index = IssueTracker\n\n-- Create a new issue tracker instance\n---@return IssueTracker\nfunction M.new()\n local self = setmetatable({}, IssueTracker)\n self.issues_found = {}\n return self\nend\n\n-- Track a new issue\n---@param issue_type string Issue type from ISSUE_TYPES\n---@param details table? Issue-specific details\nfunction IssueTracker:track_issue(issue_type, details)\n if not M.ISSUE_TYPES[issue_type] then\n error(\"Unknown issue type: \" .. tostring(issue_type))\n end\n local issue_info = M.ISSUE_TYPES[issue_type]\n if type(issue_info) == \"function\" then\n issue_info = issue_info(details)\n end\n if issue_info then\n table.insert(self.issues_found, {\n type = issue_type,\n details = details or {},\n timestamp = os.time(),\n severity = issue_info.severity,\n description = issue_info.description,\n fix = issue_info.fix,\n llm_guidance = issue_info.llm_guidance,\n })\n end\nend\n\n-- Check if any issues were found\n---@return boolean has_issues\nfunction IssueTracker:has_issues()\n return #self.issues_found > 0\nend\n\n-- Generate LLM feedback with categorized issues\n---@return string? feedback Formatted feedback for LLM (nil if no issues)\nfunction IssueTracker:get_llm_feedback()\n if #self.issues_found == 0 then\n return nil\n end\n\n local parts = {}\n\n for _, issue in ipairs(self.issues_found) do\n local str = string.format(\n \"### %s\\nIssue Encountered: %s\\nResolved By Editor: %s\\nFuture Guidance: %s\",\n issue.severity:upper(),\n issue.description,\n issue.fix,\n issue.llm_guidance\n )\n table.insert(parts, str)\n end\n return #parts > 0 and table.concat(parts, \"\\n\\n\") or nil\nend\n\n-- Clear all tracked issues\nfunction IssueTracker:clear()\n self.issues_found = {}\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/utils/text.lua", "---@brief [[\n--- Text utilities for MCPHub\n--- Provides text formatting, layout, and rendering utilities\n---@brief ]]\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal hl = require(\"mcphub.utils.highlights\")\n\nlocal M = {}\n\n-- Constants\nM.HORIZONTAL_PADDING = 2\n\n-- Export highlight groups for easy access\nM.highlights = hl.groups\n\nM.icons = {\n\n hourglass = \"\",\n person = \"\",\n clock = \"\",\n server = \"\",\n antenna = \"\",\n antenna_off = \"\",\n sse = \"\",\n auto = \"\",\n tower = \"\",\n tool = \"\",\n resourceTemplate = \"\",\n resource = \"\",\n circle = \"○\",\n circleFilled = \"●\",\n bug = \"\",\n event = \"\",\n param = \"\",\n favorite = \"\",\n loaded = \"●\",\n vertical_bar = \"│\",\n not_loaded = \"○\",\n arrowRight = \"➜\",\n triangleDown = \"▼\",\n triangleRight = \"▶\",\n search = \"\",\n tag = \"\",\n sort = \"\",\n octoface = \"\",\n check = \"✔\",\n gear = \"\",\n loading = \"\",\n downArrow = \"\",\n uninstall = \"\",\n sparkles = \"✨\",\n download = \"\",\n install = \"\",\n link = \"\",\n pencil = \"\",\n edit = \"\",\n plus = \"\",\n instructions = \"\",\n unauthorized = \"\",\n\n file = \"\",\n folder = \"\",\n globe = \"\",\n prompt = \"\",\n -- Error type icons\n setup_error = \"\",\n server_error = \"\",\n runtime_error = \"\",\n general_error = \"\",\n\n error = \"\",\n warn = \"\",\n info = \"\",\n question = \"\",\n hint = \"\",\n debug = \"\",\n trace = \"✎\",\n}\n\n--- Split text into multiple NuiLines while preserving newlines\n---@param content string Text that might contain newlines\n---@param highlight? string Optional highlight group\n---@return NuiLine[]\nfunction M.multiline(content, highlight)\n if type(content) ~= \"string\" then\n content = tostring(content)\n end\n local lines = {}\n for _, line in\n ipairs(vim.split(content, \"\\n\", {\n plain = true,\n }))\n do\n table.insert(lines, NuiLine():append(line, highlight))\n end\n return lines\nend\n\n--- Add horizontal padding to a line\n---@param line NuiLine|string The line to pad\n---@param highlight? string Optional highlight for string input\n---@param padding? number Override default padding\n---@return NuiLine\nfunction M.pad_line(line, highlight, padding)\n local nui_line = NuiLine():append(string.rep(\" \", padding or M.HORIZONTAL_PADDING))\n\n if type(line) == \"string\" then\n nui_line:append(line, highlight)\n else\n nui_line:append(line)\n end\n\n return nui_line:append(string.rep(\" \", padding or M.HORIZONTAL_PADDING))\nend\n\n--- Create empty line with consistent padding\n---@return NuiLine\nfunction M.empty_line()\n return M.pad_line(\"\")\nend\n\n--- Create a divider line\n---@param width number Total width\n---@param is_full? boolean Whether to ignore padding\n---@return NuiLine\nfunction M.divider(width, is_full)\n if is_full then\n return NuiLine():append(string.rep(\"-\", width), M.highlights.muted)\n end\n return M.pad_line(string.rep(\"-\", width - (M.HORIZONTAL_PADDING * 2)), M.highlights.muted)\nend\n\n--- Align text with proper padding\n---@param text string|NuiLine Text to align\n---@param width number Available width\n---@param align \"left\"|\"center\"|\"right\" Alignment direction\n---@param highlight? string Optional highlight for text\n---@return NuiLine\nfunction M.align_text(text, width, align, highlight)\n local inner_width = width - (M.HORIZONTAL_PADDING * 2)\n\n -- Convert string to NuiLine if needed\n local line = type(text) == \"string\" and NuiLine():append(text, highlight) or text --[[@as NuiLine]]\n local line_width = line:width()\n\n -- Calculate padding\n local padding = math.max(0, inner_width - line_width)\n local left_pad = align == \"center\" and math.floor(padding / 2) or align == \"right\" and padding or 0\n -- local right_pad = align == \"center\" and math.ceil(padding / 2) or align == \"left\" and padding or 0\n\n -- Create padded line\n return NuiLine():append(string.rep(\" \", M.HORIZONTAL_PADDING + left_pad)):append(line)\n -- :append(string.rep(\" \", right_pad + M.HORIZONTAL_PADDING))\nend\n\n---@param label string\n---@param shortcut string\n---@param selected boolean\n---@return NuiLine\nfunction M.create_button(label, shortcut, selected)\n local line = NuiLine()\n -- Start button group\n if selected then\n -- Selected button has full background\n line:append(\" \" .. shortcut, M.highlights.header_btn_shortcut)\n line:append(\" \" .. label .. \" \", M.highlights.header_btn)\n else\n -- Unselected shows just shortcut highlighted\n line:append(\" \" .. shortcut, M.highlights.header_shortcut)\n line:append(\" \" .. label .. \" \", M.highlights.header)\n end\n return line\nend\n\n--- Create centered tab bar with selected state\n---@param tabs {text: string, selected: boolean}[] Array of tab objects\n---@param width number Total width available\n---@return NuiLine\nfunction M.create_tab_bar(tabs, width)\n -- Create tab group first\n local tab_group = NuiLine()\n for i, tab in ipairs(tabs) do\n if i > 1 then\n tab_group:append(\" \")\n end\n tab_group:append(\n \" \" .. tab.text .. \" \",\n tab.selected and M.highlights.button_active or M.highlights.button_inactive\n )\n end\n\n -- Create the entire line with centered tab group\n return M.align_text(tab_group, width, \"center\")\nend\n\n--- The MCP Hub logo\n---@param width number Window width for centering\n---@return NuiLine[]\nfunction M.render_logo(width)\n local logo_lines = {\n \"╔╦╗╔═╗╔═╗ ╦ ╦╦ ╦╔╗ \",\n \"║║║║ ╠═╝ ╠═╣║ ║╠╩╗\",\n \"╩ ╩╚═╝╩ ╩ ╩╚═╝╚═╝\",\n }\n local lines = {}\n for _, line in ipairs(logo_lines) do\n table.insert(lines, M.align_text(line, width, \"center\", M.highlights.title))\n end\n return lines\nend\n\n--- Create header with buttons\n---@param width number Window width\n---@param current_view string Currently selected view\n---@return NuiLine[]\nfunction M.render_header(width, current_view)\n local lines = M.render_logo(width)\n\n -- Create buttons line\n local buttons = NuiLine()\n\n -- Add buttons with proper padding\n local btn_list = {\n {\n key = \"H\",\n label = \"Hub\",\n view = \"main\",\n },\n {\n key = \"M\",\n label = \"Marketplace\",\n view = \"marketplace\",\n },\n {\n key = \"C\",\n label = \"Config\",\n view = \"config\",\n },\n {\n key = \"L\",\n label = \"Logs\",\n view = \"logs\",\n },\n {\n key = \"?\",\n label = \"Help\",\n view = \"help\",\n },\n }\n\n for i, btn in ipairs(btn_list) do\n if i > 1 then\n buttons:append(\" \") -- Add spacing between buttons\n end\n buttons:append(M.create_button(btn.label, btn.key, current_view == btn.view))\n end\n\n -- Center the buttons line\n local padding = math.floor((width - buttons:width()) / 2)\n if padding > 0 then\n table.insert(lines, NuiLine():append(string.rep(\" \", padding)):append(buttons))\n else\n table.insert(lines, buttons)\n end\n\n return lines\nend\n\n--- Render markdown text with proper syntax highlighting\n---@param text string The markdown text to render\n---@return NuiLine[]\nfunction M.render_markdown(text)\n if not text then\n return {}\n end\n\n local lines = {}\n local in_code_block = false\n\n for _, line in ipairs(vim.split(text, \"\\n\", { plain = true })) do\n local nui_line = NuiLine()\n\n -- Handle code blocks\n if line:match(\"^```\") then\n in_code_block = not in_code_block\n nui_line:append(line, M.highlights.muted)\n\n -- Inside code block\n elseif in_code_block then\n nui_line:append(line, M.highlights.code)\n\n -- Headers\n elseif line:match(\"^#+ \") then\n local level = #line:match(\"^(#+)\")\n local header_text = line:match(\"^#+%s+(.+)\")\n nui_line:append(string.rep(\"#\", level) .. \" \", M.highlights.muted):append(header_text, M.highlights.title)\n\n -- Lists\n elseif line:match(\"^%s*[-*] \") then\n local indent = #(line:match(\"^%s*\") or \"\")\n local list_text = line:match(\"^%s*[-*]%s+(.+)\")\n nui_line\n :append(string.rep(\" \", indent))\n :append(\"• \", M.highlights.muted)\n :append(list_text, M.highlights.text)\n\n -- Normal text\n else\n nui_line:append(line, M.highlights.text)\n end\n\n table.insert(lines, M.pad_line(nui_line))\n end\n\n return lines\nend\n\n--- Render JSON with syntax highlighting using the existing pretty_json formatter\n---@param text string|table? The JSON text or table to render\n---@param opts table Optional options\n---@return NuiLine[]\nfunction M.render_json(text, opts)\n local utils = require(\"mcphub.utils\")\n\n -- Convert table to JSON if needed\n if type(text) == \"table\" then\n text = vim.json.encode(text)\n end\n\n -- Use the existing pretty printer\n local formatted = utils.pretty_json(text or \"\", opts)\n local lines = {}\n\n -- Process each line and add highlighting\n for _, line in ipairs(vim.split(formatted, \"\\n\", { plain = true })) do\n local nui_line = NuiLine()\n local pos = 1\n\n -- Add indentation\n local indent = line:match(\"^(%s*)\")\n if indent then\n nui_line:append(indent)\n pos = #indent + 1\n end\n\n -- Handle property names (with quotes) first\n local property = line:match('^%s*\"([^\"]+)\"%s*:', pos)\n if property then\n nui_line:append('\"' .. property .. '\"', M.highlights.json_property)\n pos = pos + #property + 2 -- +2 for quotes\n -- Skip past the colon\n local colon_pos = line:find(\":\", pos)\n if colon_pos then\n nui_line:append(line:sub(pos, colon_pos), M.highlights.json_punctuation)\n pos = colon_pos + 1\n end\n end\n\n -- Process the rest of the line\n while pos <= #line do\n local char = line:sub(pos, pos)\n\n -- Handle structural characters\n if char:match(\"[{%[%]}:,]\") then\n nui_line:append(char, M.highlights.json_punctuation)\n -- Handle string values (must be in quotes)\n elseif char == '\"' then\n local str_end = pos + 1\n while str_end <= #line do\n if line:sub(str_end, str_end) == '\"' and line:sub(str_end - 1, str_end - 1) ~= \"\\\\\" then\n break\n end\n str_end = str_end + 1\n end\n nui_line:append(line:sub(pos, str_end), M.highlights.json_string)\n pos = str_end\n -- Handle numbers\n elseif char:match(\"%d\") then\n local num = line:match(\"%d+%.?%d*\", pos)\n if num then\n nui_line:append(num, M.highlights.json_number)\n pos = pos + #num - 1\n end\n -- Handle boolean and null\n elseif line:match(\"^true\", pos) then\n nui_line:append(\"true\", M.highlights.json_boolean)\n pos = pos + 3\n elseif line:match(\"^false\", pos) then\n nui_line:append(\"false\", M.highlights.json_boolean)\n pos = pos + 4\n elseif line:match(\"^null\", pos) then\n nui_line:append(\"null\", M.highlights.json_null)\n pos = pos + 3\n -- Handle whitespace\n elseif char:match(\"%s\") then\n nui_line:append(char)\n end\n pos = pos + 1\n end\n\n table.insert(lines, M.pad_line(nui_line))\n end\n\n return lines\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/config.lua", "local M = {}\n\nlocal SHUTDOWN_DELAY = 5 * 60 * 1000 -- 5 minutes\n\n---@class MCPHub.WorkspaceConfig\n---@field enabled boolean Master switch for workspace-specific hubs\n---@field look_for string[] Files to search for (in order)\n---@field port_range { min: number, max: number } Port range for workspace hubs\n---@field reload_on_dir_changed boolean Whether to listen to DirChanged events to reload workspace config\n---@field get_port fun(): number | nil Function that determines that returns the port\n\n---@class MCPHub.Config\nlocal defaults = {\n port = 37373, -- Default port for MCP Hub\n server_url = nil, -- In cases where mcp-hub is hosted somewhere, set this to the server URL e.g `http://mydomain.com:customport` or `https://url_without_need_for_port.com`\n config = vim.fn.expand(\"~/.config/mcphub/servers.json\"), -- Default config location\n shutdown_delay = SHUTDOWN_DELAY, -- Delay before shutting down the mcp-hub\n mcp_request_timeout = 60000, --Timeout for MCP requests in milliseconds, useful for long running tasks\n ---@type table\n native_servers = {},\n builtin_tools = {\n ---@type EditSessionConfig\n edit_file = {\n parser = {\n track_issues = true,\n extract_inline_content = true,\n },\n locator = {\n fuzzy_threshold = 0.8,\n enable_fuzzy_matching = true,\n },\n ui = {\n go_to_origin_on_complete = true,\n keybindings = {\n accept = \".\", -- Accept current change\n reject = \",\", -- Reject current change\n next = \"n\", -- Next diff\n prev = \"p\", -- Previous diff\n accept_all = \"ga\", -- Accept all remaining changes\n reject_all = \"gr\", -- Reject all remaining changes\n },\n },\n feedback = {\n include_parser_feedback = true,\n include_locator_feedback = true,\n include_ui_summary = true,\n ui = {\n include_session_summary = true,\n include_final_diff = true,\n send_diagnostics = true,\n wait_for_diagnostics = 500,\n diagnostic_severity = vim.diagnostic.severity.WARN, -- Only show warnings and above by default\n },\n },\n },\n },\n --- Custom function to parse json file (e.g `require'json5'.parse` from `https://github.com/Joakker/lua-json5 to parse json5 syntax for .vscode/mcp.json like files)\n ---@type function | nil\n json_decode = nil,\n ---@type boolean | fun(parsed_params: MCPHub.ParsedParams): boolean | nil | string Function to determine if a call should be auto-approved\n auto_approve = false,\n auto_toggle_mcp_servers = true, -- Let LLMs start and stop MCP servers automatically\n use_bundled_binary = false, -- Whether to use bundled mcp-hub binary\n ---@type table | fun(context: MCPHub.JobContext): table Global environment variables available to all MCP servers\n global_env = {}, -- Environment variables that will be available to all MCP servers\n ---@type string?\n cmd = nil, -- will be set based on system if not provided\n ---@type table?\n cmdArgs = nil, -- will be set based on system if not provided\n ---@type LogConfig\n log = {\n level = vim.log.levels.ERROR,\n to_file = false,\n file_path = nil,\n prefix = \"MCPHub\",\n },\n ---@type MCPHub.UIConfig\n ui = {\n window = {},\n wo = {},\n },\n ---@type MCPHub.Extensions.Config\n extensions = {\n avante = {\n enabled = true,\n make_slash_commands = true,\n },\n },\n ---@type MCPHub.WorkspaceConfig\n workspace = {\n enabled = true, -- Enables workspace-specific hubs\n look_for = { \".mcphub/servers.json\", \".vscode/mcp.json\", \".cursor/mcp.json\" }, -- Files to search for (in order)\n reload_on_dir_changed = true, -- Whether to listen to DirChanged events to reload workspace config\n port_range = { min = 40000, max = 41000 }, -- Port range for workspace hubs\n -- function that determines that returns the port\n --- @type fun(): number | nil\n get_port = nil,\n },\n on_ready = function() end,\n ---@param msg string\n on_error = function(msg) end,\n}\n\n---@param opts MCPHub.Config?\n---@return MCPHub.Config\nfunction M.setup(opts)\n M.config = vim.tbl_deep_extend(\"force\", defaults, opts or {})\n return M.config\nend\n\nreturn setmetatable(M, {\n __index = function(_, key)\n if key == \"setup\" then\n return M.setup\n end\n return rawget(M.config, key)\n end,\n})\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/utils/buffer.lua", "local M = {}\n\n---@class FileInfo\n---@field name string # File name or path\n---@field type string # File type (file/directory/etc)\n---@field size number # File size in bytes\n---@field modified number # Last modification timestamp\n\n---@class DirectoryInfo\n---@field path string # Current directory path\n---@field is_git boolean # Whether the directory is a git repository\n---@field files FileInfo[] # List of files in the directory\n\n---@param path? string # Directory path to scan (defaults to current working directory)\n---@return DirectoryInfo\nfunction M.get_directory_info(path)\n path = path or vim.loop.cwd()\n -- Check if git repo\n local is_git = vim.fn.system(\"git rev-parse --is-inside-work-tree 2>/dev/null\"):match(\"true\")\n local files = {}\n\n if is_git then\n -- Use git ls-files for git-aware listing\n local git_files = vim.fn.systemlist(\"git ls-files --cached --others --exclude-standard\")\n for _, file in ipairs(git_files) do\n local stat = vim.loop.fs_stat(file)\n if stat then\n table.insert(files, {\n name = file,\n type = stat.type,\n size = stat.size,\n modified = stat.mtime.sec,\n })\n end\n end\n else\n -- Fallback to regular directory listing\n local handle = vim.loop.fs_scandir(path)\n if handle then\n while true do\n local name, type = vim.loop.fs_scandir_next(handle)\n if not name then\n break\n end\n\n local stat = vim.loop.fs_stat(name)\n if stat then\n table.insert(files, {\n name = name,\n type = type or stat.type,\n size = stat.size,\n modified = stat.mtime.sec,\n })\n end\n end\n end\n end\n\n return {\n path = path,\n is_git = is_git,\n files = files,\n }\nend\n---@class BufferInfo\n---@field name string\n---@field filename string\n---@field windows number[]\n---@field winnr number\n---@field cursor_pos number[]\n---@field filetype string\n---@field line_count number\n---@field is_visible boolean\n---@field is_modified boolean\n---@field is_loaded boolean\n---@field lastused number\n---@field bufnr number\n\n---@class EditorInfo\n---@field last_active BufferInfo\n---@field buffers BufferInfo[]\n\n---@return EditorInfo\nfunction M.get_editor_info()\n local buffers = vim.fn.getbufinfo({ buflisted = 1 })\n local valid_buffers = {}\n local last_active = nil\n local max_lastused = 0\n\n for _, buf in ipairs(buffers) do\n -- Only include valid files (non-empty name and empty buftype)\n local buftype = vim.api.nvim_buf_get_option(buf.bufnr, \"buftype\")\n if buf.name ~= \"\" and buftype == \"\" then\n local buffer_info = {\n bufnr = buf.bufnr,\n name = buf.name,\n filename = buf.name,\n is_visible = #buf.windows > 0,\n is_modified = buf.changed == 1,\n is_loaded = buf.loaded == 1,\n lastused = buf.lastused,\n windows = buf.windows,\n winnr = buf.windows[1], -- Primary window showing this buffer\n }\n\n -- Add cursor info for currently visible buffers\n if buffer_info.is_visible then\n local win = buffer_info.winnr\n local cursor = vim.api.nvim_win_get_cursor(win)\n buffer_info.cursor_pos = cursor\n end\n\n -- Add additional buffer info\n buffer_info.filetype = vim.api.nvim_buf_get_option(buf.bufnr, \"filetype\")\n buffer_info.line_count = vim.api.nvim_buf_line_count(buf.bufnr)\n\n table.insert(valid_buffers, buffer_info)\n\n -- Track the most recently used buffer\n if buf.lastused > max_lastused then\n max_lastused = buf.lastused\n last_active = buffer_info\n end\n end\n end\n\n -- If no valid buffers found, provide default last_active\n if not last_active and #valid_buffers > 0 then\n last_active = valid_buffers[1]\n end\n\n return {\n last_active = last_active,\n buffers = valid_buffers,\n }\nend\n\n---@param file_path string The path to the file to find\n---@return BufferInfo|nil The buffer info if found, nil otherwise\nfunction M.find_buffer(file_path)\n local bufs = M.get_editor_info().buffers\n for _, buf in ipairs(bufs) do\n if buf.filename == file_path then\n return buf\n end\n end\n return nil\nend\n\n---Open file in editor and get target window\n---@param file_path string The path to the file to open\n---@return number|nil The buffer number of the opened file, or nil if not found\nfunction M.open_file_in_editor(file_path)\n local abs_path = vim.fn.fnamemodify(file_path, \":p\")\n\n local function safe_edit(file)\n local ok = pcall(vim.cmd.edit, vim.fn.fnameescape(file))\n if not ok then\n vim.cmd.enew()\n vim.cmd.file(file)\n end\n end\n\n -- Try to find existing window with the file\n for _, winid in ipairs(vim.api.nvim_list_wins()) do\n local bufnr = vim.api.nvim_win_get_buf(winid)\n local buf_name = vim.api.nvim_buf_get_name(bufnr)\n if buf_name == abs_path then\n vim.api.nvim_set_current_win(winid)\n return vim.api.nvim_get_current_buf()\n end\n end\n\n local editor_info = M.get_editor_info()\n -- Try to use last active buffer's window if available\n if editor_info and editor_info.last_active then\n local last_active = editor_info.last_active\n if last_active.winnr and vim.api.nvim_win_is_valid(last_active.winnr) then\n vim.api.nvim_set_current_win(last_active.winnr)\n safe_edit(abs_path)\n return vim.api.nvim_get_current_buf()\n end\n end\n\n -- Create new window for the file\n local chat_win = vim.api.nvim_get_current_win()\n local chat_col = vim.api.nvim_win_get_position(chat_win)[2]\n local total_width = vim.o.columns\n\n -- Determine where to place new window based on chat position\n if chat_col > total_width / 2 then\n vim.cmd(\"topleft vnew\") -- New window on the left\n else\n vim.cmd(\"botright vnew\") -- New window on the right\n end\n\n safe_edit(abs_path)\n local bufnr = vim.api.nvim_get_current_buf()\n vim.api.nvim_buf_set_option(bufnr, \"buflisted\", true)\n\n return bufnr\nend\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/buffer.lua", "local utils = require(\"mcphub.utils\")\n\nlocal function get_buffer_lines(buf_info)\n local cursor_line = buf_info.cursor_pos[1]\n local ok, lines = pcall(vim.api.nvim_buf_get_lines, buf_info.bufnr, 0, -1, false)\n if not ok or not lines then\n return { \"Failed to get buffer lines\" }\n end\n\n local formatted = {}\n for i, line in ipairs(lines) do\n local prefix = i == cursor_line and \">\" or \" \"\n -- Escape any format strings in the line content\n line = line:gsub(\"%%\", \"%%%%\")\n table.insert(formatted, string.format(\"%s %4d │ %s\", prefix, i, line))\n end\n return formatted\nend\n\nlocal function get_marks(buf_info)\n local marks = vim.fn.getmarklist(buf_info.bufnr)\n local result = {}\n for _, mark in ipairs(marks) do\n if mark.mark:match(\"[a-zA-Z]$\") then\n local ok, line = pcall(vim.api.nvim_buf_get_lines, buf_info.bufnr, mark.pos[2] - 1, mark.pos[2], false)\n local context = ok and line[1] or \"\"\n if context then\n context = context:gsub(\"%%\", \"%%%%\")\n table.insert(\n result,\n string.format(\"%s: line %d, col %d: %s\", mark.mark:sub(-1), mark.pos[2], mark.pos[3], context)\n )\n end\n end\n end\n return result\nend\n\nlocal function get_qf_entries(buf_info)\n local qf_list = vim.fn.getqflist()\n local result = {}\n for _, item in ipairs(qf_list) do\n if item.bufnr == buf_info.bufnr then\n local ok, line = pcall(vim.api.nvim_buf_get_lines, buf_info.bufnr, item.lnum - 1, item.lnum, false)\n local content = ok and line[1] or \"\"\n if content then\n content = content:gsub(\"%%\", \"%%%%\")\n table.insert(result, string.format(\"%4d │ %s\\n └─ %s\", item.lnum, content, item.text))\n end\n end\n end\n return result\nend\n\n---@type MCPResource\nreturn {\n name = \"Buffer\",\n description = \"Get detailed information about the currently active buffer including content, cursor position, and buffer metadata\",\n uri = \"neovim://buffer\",\n mimeType = \"text/plain\",\n handler = function(req, res)\n local buf_info = req.editor_info.last_active\n if not buf_info then\n return res:error(\"No active buffer found\")\n end\n if buf_info.bufnr == 0 then\n return res:error(\"No valid buffer found\")\n end\n\n local lines = get_buffer_lines(buf_info)\n local marks = get_marks(buf_info)\n local qf_entries = get_qf_entries(buf_info)\n\n local sep = string.rep(\"─\", 80)\n\n local text = string.format(\n [[\n## Buffer Information\nName: %s\nBufnr: %d\nLines: %d\nCursor: line %d\n\n%s\n## Buffer Content\n%s%s%s\n]],\n buf_info.filename,\n buf_info.bufnr,\n buf_info.line_count,\n buf_info.cursor_pos[1],\n sep,\n table.concat(lines, \"\\n\"),\n #marks > 0 and string.format(\"\\n\\n%s\\n# Marks\\n%s\", sep, table.concat(marks, \"\\n\")) or \"\",\n #qf_entries > 0 and string.format(\"\\n\\n%s\\n# Quickfix Entries\\n%s\", sep, table.concat(qf_entries, \"\\n\"))\n or \"\"\n )\n\n return res:text(text):send()\n end,\n}\n"], ["/mcphub.nvim/lua/mcphub/init.lua", "local Error = require(\"mcphub.utils.errors\")\nlocal ImageCache = require(\"mcphub.utils.image_cache\")\nlocal Job = require(\"plenary.job\")\nlocal MCPHub = require(\"mcphub.hub\")\nlocal State = require(\"mcphub.state\")\nlocal log = require(\"mcphub.utils.log\")\nlocal native = require(\"mcphub.native\")\nlocal utils = require(\"mcphub.utils\")\nlocal validation = require(\"mcphub.utils.validation\")\n\n-- Initialize global variables for lualine integration\nvim.g.mcphub_status = \"stopped\"\nvim.g.mcphub_servers_count = 0\nvim.g.mcphub_executing = false\n\n---@class MCPHub\nlocal M = {\n is_native_server = native.is_native_server,\n add_server = native.add_server,\n add_tool = native.add_tool,\n add_resource = native.add_resource,\n add_resource_template = native.add_resource_template,\n add_prompt = native.add_prompt,\n}\n\n---Get the current MCPHub instance\n---@return MCPHub.Hub | nil\nfunction M.get_hub_instance()\n if State.setup_state ~= \"completed\" then\n return nil\n end\n return State.hub_instance\nend\n\n---Get the current state of the MCPHub\n---@return MCPHub.State\nfunction M.get_state()\n return State\nend\n\n---@param event string | table\n---@param callback fun(data: table)\nfunction M.on(event, callback)\n --if event is an array then add each event\n if type(event) == \"table\" then\n for _, e in ipairs(event) do\n State:add_event_listener(e, callback)\n end\n return\n end\n State:add_event_listener(event, callback)\nend\n\n---@param event string | table\n---@param callback fun(data: table)\nfunction M.off(event, callback)\n --if event is an array then remove each event\n if type(event) == \"table\" then\n for _, e in ipairs(event) do\n State:remove_event_listener(e, callback)\n end\n return\n end\n State:remove_event_listener(event, callback)\nend\n\n--- Setup MCPHub plugin with error handling and validation\n--- @param opts MCPHub.Config?\n---@return MCPHub.Hub | nil\nfunction M.setup(opts)\n ---@param err MCPError\n local function _on_setup_failed(err)\n if err then\n State:add_error(err)\n State:update({\n setup_state = \"failed\",\n }, \"setup\")\n State.config.on_error(tostring(err))\n end\n end\n\n ---Version check handler\n ---@param job Job\n ---@param code number\n ---@param config MCPHub.Config\n local function _handle_version_check(job, code, config)\n if code ~= 0 then\n return _on_setup_failed(\n Error(\n \"SETUP\",\n Error.Types.SETUP.MISSING_DEPENDENCY,\n \"mcp-hub exited with non-zero code. Please verify your installation.\"\n )\n )\n end\n\n -- Validate version\n local version_result = validation.validate_version(job:result()[1])\n if not version_result.ok then\n return _on_setup_failed(version_result.error)\n end\n\n -- Create hub instance\n local hub = MCPHub:new(config)\n if not hub then\n return _on_setup_failed(Error(\"SETUP\", Error.Types.SETUP.SERVER_START, \"Failed to create MCPHub instance\"))\n end\n\n State.hub_instance = hub\n State:update({\n setup_state = \"completed\",\n }, \"setup\")\n\n -- Initialize image cache\n ImageCache.setup()\n\n -- Setup Extensions\n require(\"mcphub.extensions\").setup(config.extensions)\n -- Start hub\n hub:start()\n end\n -- Return if already setup or in progress\n if State.setup_state ~= \"not_started\" then\n return State.hub_instance\n end\n -- Update state to in_progress\n State:update({\n setup_state = \"in_progress\",\n }, \"setup\")\n local config = require(\"mcphub.config\").setup(opts)\n local cmds = utils.get_default_cmds(config)\n config.cmd = cmds.cmd\n config.cmdArgs = cmds.cmdArgs\n if type(config.auto_approve) == \"boolean\" and config.auto_approve == true then\n vim.g.mcphub_auto_approve = vim.g.mcphub_auto_approve == nil and true or vim.g.mcphub_auto_approve\n end\n log.setup(config.log)\n State.ui_instance = require(\"mcphub.ui\"):new(config.ui)\n State.config = config\n\n -- Validate options\n local validation_result = validation.validate_setup_opts(config)\n if not validation_result.ok then\n return _on_setup_failed(validation_result.error)\n end\n\n -- Setup cleanup and directory change handling\n local group = vim.api.nvim_create_augroup(\"mcphub_cleanup\", {\n clear = true,\n })\n vim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = group,\n callback = function()\n if State.hub_instance then\n State.hub_instance:stop()\n end\n -- UI cleanup is handled by its own autocmd\n end,\n })\n\n -- Handle directory changes for workspace-aware mode\n if config.workspace.enabled and config.workspace.reload_on_dir_changed then\n vim.api.nvim_create_autocmd(\"DirChanged\", {\n group = group,\n callback = vim.schedule_wrap(function()\n if State.hub_instance then\n -- Small delay to ensure directory change is complete\n vim.defer_fn(function()\n State.hub_instance:handle_directory_change()\n end, 100)\n end\n end),\n })\n end\n\n -- Start version check\n local ok, job = pcall(function()\n ---@diagnostic disable-next-line: missing-fields\n return Job:new({\n command = config.cmd,\n args = utils.clean_args({ config.cmdArgs, \"--version\" }),\n on_exit = vim.schedule_wrap(function(j, code)\n _handle_version_check(j, code, config)\n end),\n })\n end)\n\n local help_msg = [[mcp-hub executable not found. Please ensure:\n1. For global install: Run 'npm install -g mcp-hub@latest'\n2. For bundled install: Set build = 'bundled_build.lua' in lazy spec and use_bundled_binary = true in config.\n3. For custom install: Verify cmd/cmdArgs point to valid mcp-hub executable\n]]\n if not ok then\n -- Handle executable not found error\n return _on_setup_failed(Error(\"SETUP\", Error.Types.SETUP.MISSING_DEPENDENCY, help_msg, { stack = job }))\n end\n\n -- Start the job (uv.spawn might fail)\n local spawn_ok, err = pcall(job.start, job)\n if not spawn_ok then\n -- Handle spawn error\n return _on_setup_failed(\n Error(\n \"SETUP\",\n Error.Types.SETUP.MISSING_DEPENDENCY,\n \"Failed to spawn mcp-hub process: \" .. tostring(err) .. \"\\n\\n\" .. help_msg\n )\n )\n end\n\n return State.hub_instance\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/utils/errors.lua", "---@brief [[\n--- Error management for MCPHub\n--- Provides error types, creation, and formatting\n---@brief ]]\n---@class MCPError\n---@field type string The error category (SETUP/SERVER/RUNTIME)\n---@field code string Specific error code\n---@field message string Human-readable error message\n---@field details? table Additional error context\n---@field timestamp number Unix timestamp of error creation\n---@field TYPES table Error types and codes\nlocal Error = {}\nError.__index = Error\n\n-- Error type constants\nError.Types = {\n SETUP = {\n INVALID_CONFIG = \"INVALID_CONFIG\",\n INVALID_PORT = \"INVALID_PORT\",\n MISSING_DEPENDENCY = \"MISSING_DEPENDENCY\",\n VERSION_MISMATCH = \"VERSION_MISMATCH\",\n SERVER_START = \"SERVER_START\",\n INVALID_CMD = \"INVALID_CMD\",\n INVALID_CMD_ARGS = \"INVALID_CMD_ARGS\",\n },\n NATIVE = {\n INVALID_TOOL = \"INVALID_TOOL\", -- Invalid tool definition\n INVALID_RESOURCE = \"INVALID_RESOURCE\", -- Invalid resource definition\n INVALID_TEMPLATE = \"INVALID_TEMPLATE\", -- Invalid resource template\n INVALID_SCHEMA = \"INVALID_SCHEMA\", -- Invalid input schema\n INVALID_HANDLER = \"INVALID_HANDLER\", -- Invalid handler function\n INVALID_NAME = \"INVALID_NAME\", -- Invalid name field\n INVALID_URI = \"INVALID_URI\", -- Invalid URI format\n INVALID_PROPS = \"INVALID_PROPS\", -- Invalid properties\n },\n MARKETPLACE = {\n FETCH_ERROR = \"FETCH_ERROR\", -- Failed to fetch marketplace data\n SERVER_NOT_FOUND = \"SERVER_NOT_FOUND\", -- Server not found in catalog\n INVALID_RESPONSE = \"INVALID_RESPONSE\", -- Invalid response from marketplace API\n CACHE_ERROR = \"CACHE_ERROR\", -- Error with marketplace cache\n },\n SERVER = {\n AUTHORIZATION = \"AUTHORIZATION\", -- Authorization error\n RESTART = \"RESTART\", -- Server restart error\n CONNECTION = \"CONNECTION\",\n HEALTH_CHECK = \"HEALTH_CHECK\",\n API_ERROR = \"API_ERROR\",\n CURL_ERROR = \"CURL_ERROR\",\n TIMEOUT = \"TIMEOUT\",\n SERVER_START = \"SERVER_START\",\n SSL_ERROR = \"SSL_ERROR\",\n },\n RUNTIME = {\n INVALID_STATE = \"INVALID_STATE\",\n RESOURCE_ERROR = \"RESOURCE_ERROR\",\n OPERATION_FAILED = \"OPERATION_FAILED\",\n },\n}\n\n--- Create a new error instance\n--- @param type string The error category (SETUP/SERVER/RUNTIME)\n--- @param code string Specific error code from Error.Types\n--- @param message string Human-readable error message\n--- @param details? table Additional error context\n--- @return MCPError\nfunction Error.init(type, code, message, details)\n return setmetatable({\n type = type,\n code = code,\n message = message,\n details = details or {},\n timestamp = vim.loop.now(),\n }, Error)\nend\n\n--- Convert error to string representation\n---@return string\nfunction Error:__tostring()\n local str = string.format(\"[%s.%s] %s\", self.type, self.code, self.message)\n if not vim.tbl_isempty(self.details) then\n str = str .. \"\\nDetails: \" .. vim.inspect(self.details)\n end\n return str\nend\n\n--- Constructor using __call metamethod\nsetmetatable(Error, {\n __call = function(_, ...)\n return Error.init(...)\n end,\n})\n\nreturn Error\n"], ["/mcphub.nvim/lua/mcphub/ui/capabilities/createServer.lua", "local Base = require(\"mcphub.ui.capabilities.base\")\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal highlights = require(\"mcphub.utils.highlights\").groups\nlocal Installers = require(\"mcphub.utils.installers\")\nlocal prompt_utils = require(\"mcphub.utils.prompt\")\n\n---@class CreateServerHandler : CapabilityHandler\nlocal CreateServerHandler = setmetatable({}, { __index = Base })\nCreateServerHandler.__index = CreateServerHandler\nCreateServerHandler.type = \"create_server\"\n\nfunction CreateServerHandler:new(server_name, capability_info, view)\n local handler = Base.new(self, server_name, capability_info, view)\n return handler\nend\n\nfunction CreateServerHandler:handle_action(line)\n local type = self:get_line_info(line)\n if type == \"install\" then\n -- Get available installers\n local available = {}\n for id, installer in pairs(Installers) do\n if installer.check() then\n table.insert(available, {\n id = id,\n name = installer.name,\n })\n end\n end\n\n if #available > 0 then\n vim.ui.select(available, {\n prompt = \"Choose installer:\",\n format_item = function(item)\n return item.name\n end,\n }, function(choice)\n if choice then\n local installer = Installers[choice.id]\n if installer then\n self.view.ui:cleanup()\n installer:create_native_server()\n end\n end\n end)\n else\n vim.notify(\"No installers available. Please install CodeCompanion or Avante.\", vim.log.levels.ERROR)\n end\n end\nend\n\nfunction CreateServerHandler:render(line_offset)\n line_offset = line_offset or 0\n self:clear_line_tracking()\n\n local lines = {}\n\n -- Description text\n local description = {\n \"Native Lua servers allow you to create custom MCP-compatible servers directly in Lua.\",\n \"These servers can provide tools and resources that integrate seamlessly with mcphub.nvim.\",\n \"Perfect for plugin-specific functionality, file operations, or any custom Neovim integration.\",\n \"Create your own server to extend mcphub with your unique tools and resources.\",\n }\n\n for _, line in ipairs(description) do\n table.insert(lines, Text.pad_line(line, highlights.muted))\n end\n\n table.insert(lines, Text.empty_line())\n\n local install_line = NuiLine()\n :append(\" \" .. Text.icons.pencil .. \" \", highlights.header_btn)\n :append(\"Create \", highlights.header_btn)\n :append(\" with: \", highlights.muted)\n\n -- Check each installer\n for id, installer in pairs(Installers) do\n if installer.check() then\n install_line\n :append(\"[\" .. installer.name .. \"]\", highlights.success)\n :append(\" \", highlights.muted)\n :append(Text.icons.check, highlights.success)\n :append(\" \", highlights.muted)\n else\n install_line\n :append(\"[\" .. installer.name .. \"]\", highlights.error)\n :append(\" \", highlights.muted)\n :append(Text.icons.uninstall, highlights.error)\n :append(\" \", highlights.muted)\n end\n end\n\n table.insert(lines, Text.pad_line(install_line))\n -- Track install line for interaction\n self:track_line(#lines + line_offset, \"install\", {\n hint = \"[ Select Installer]\",\n })\n\n table.insert(lines, Text.empty_line())\n table.insert(lines, self.view:divider())\n table.insert(lines, Text.empty_line())\n\n -- Show the LLM prompt content\n local guide = prompt_utils.get_native_server_prompt()\n if guide then\n vim.list_extend(lines, Text.render_markdown(guide))\n else\n table.insert(lines, Text.pad_line(\"Native server guide not found\", highlights.error))\n end\n return lines\nend\n\nreturn CreateServerHandler\n"], ["/mcphub.nvim/lua/mcphub/extensions/avante/slash_commands.lua", "local mcphub = require(\"mcphub\")\nlocal shared = require(\"mcphub.extensions.shared\")\n\nlocal M = {}\n\n---Update avante slash commands with the current MCP prompts.\nfunction M.register()\n local ok, avante_config = pcall(require, \"avante.config\")\n if not ok then\n return\n end\n\n local hub = mcphub.get_hub_instance()\n if not hub then\n return\n end\n local prompts = hub:get_prompts()\n local avante_slash_commands = avante_config.slash_commands or {}\n -- remove existing mcp slash commands that start with mcp so that when user disables a server, those prompts are removed\n for i, value in ipairs(avante_slash_commands) do\n local id = value.name or \"\"\n if id:sub(1, 3) == \"mcp\" then\n avante_slash_commands[i] = nil\n end\n end\n --add all prompts from MCP servers\n for _, prompt in ipairs(prompts) do\n local server_name = prompt.server_name\n local prompt_name = prompt.name or \"\"\n local description = prompt.description or \"\"\n local arguments = prompt.arguments or {}\n if type(description) == \"function\" then\n local desc_ok, desc = pcall(description, prompt)\n if desc_ok then\n description = desc or \"\"\n else\n description = \"Error in description function: \" .. (desc or \"\")\n end\n end\n if type(arguments) == \"function\" then\n local args_ok, args = pcall(arguments, prompt)\n if args_ok then\n arguments = args or {}\n else\n vim.notify(\"Error in arguments function: \" .. (args or \"\"), vim.log.levels.ERROR)\n arguments = {}\n end\n end\n --remove new lines\n description = description:gsub(\"\\n\", \" \")\n\n description = prompt_name .. \" (\" .. description .. \")\"\n local slash_command = {\n name = \"mcp:\" .. server_name .. \":\" .. prompt_name,\n description = description,\n callback = function(sidebar, args, cb)\n shared.collect_arguments(arguments, function(values)\n local response, err = hub:get_prompt(server_name, prompt_name, values, {\n caller = {\n type = \"avante\",\n avante = sidebar,\n meta = {\n is_within_slash_command = true,\n },\n },\n parse_response = true,\n })\n if not response then\n if err then\n vim.notify(\"Error in slash command: \" .. err, vim.log.levels.ERROR)\n vim.notify(\"Prompt cancelled\", vim.log.levels.INFO)\n end\n return\n end\n local messages = response.messages or {}\n local text_messages = {}\n for i, message in ipairs(messages) do\n local output = message.output\n if output.text and output.text ~= \"\" then\n if i == #messages and message.role == \"user\" then\n sidebar:set_input_value(output.text)\n else\n table.insert(text_messages, {\n role = message.role,\n content = output.text,\n })\n end\n end\n end\n sidebar:add_chat_history(text_messages, { visible = true })\n vim.notify(\n string.format(\n \"%s message%s added successfully\",\n #text_messages,\n #text_messages == 1 and \"\" or \"s\"\n ),\n vim.log.levels.INFO\n )\n if cb then\n cb()\n end\n end)\n end,\n }\n table.insert(avante_slash_commands, slash_command)\n end\nend\n\n---Add slash commands to Avante for all active MCP servers\nfunction M.setup()\n ---Immediately register slash commands if enabled\n M.register()\n --setup event listeners to update slash commands\n mcphub.on({ \"servers_updated\", \"prompt_list_changed\" }, M.register)\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/mcphub/init.lua", "local mcphub = require(\"mcphub\")\nlocal prompt_utils = require(\"mcphub.utils.prompt\")\n\n-- Create base mcphub server\nmcphub.add_server(\"mcphub\", {\n displayName = \"MCPHub\",\n description = \"MCPHub server provides tools and resources to manage the mcphub.nvim neovim plugin. It has tools to toggle any MCP Server along with resources like docs, guides.\",\n})\nrequire(\"mcphub.native.mcphub.guide\")\n\nmcphub.add_prompt(\"mcphub\", {\n name = \"create_native_server\",\n description = \"Create a native MCP server for mcphub.nvim\",\n arguments = {\n {\n name = \"mcphub_setup_file\",\n description = \"Path to file where mcphub.setup({}) is called.\",\n default = vim.fn.stdpath(\"config\") .. \"/\",\n required = true,\n },\n },\n handler = function(req, res)\n local guide = prompt_utils.get_native_server_prompt()\n local setup_file_path = req.params.mcphub_setup_file\n local is_codecompanion = req.caller.type == \"codecompanion\"\n local prompt = string.format(\n [[%s I have provided you a guide to create Lua native MCP servers for mcphub.nvim plugin. My Neovim config directory is `%s`. I have called mcphub.setup({}) in this file `%s`.\n\nI want to create a native MCP server for mcphub.nvim plugin. The server should have the following capabilities:\n\n]],\n is_codecompanion and \"@mcp\" or \"\",\n vim.fn.stdpath(\"config\"),\n setup_file_path\n )\n res:user():text(guide or \"Failed to load guide\"):text(prompt)\n res:send()\n end,\n})\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/environment.lua", "local buf_utils = require(\"mcphub.native.neovim.utils.buffer\")\nlocal os_utils = require(\"mcphub.native.neovim.utils.os\")\n\n---@type MCPResource\nreturn {\n name = \"Workspace\",\n description = \"This resource gives comprehensive information about the workspace, editor and OS. Includes directory structure, visible and loaded buffers along with the OS information.\",\n uri = \"neovim://workspace\",\n mimeType = \"text/plain\",\n handler = function(req, res)\n local editor_info = req.editor_info\n local os_info = os_utils.get_os_info()\n local dir_info = buf_utils.get_directory_info(vim.fn.getcwd())\n\n -- Format visible and loaded buffers\n local visible = vim.tbl_map(\n function(buf)\n return string.format(\"%s%s\", buf.name, buf.bufnr == editor_info.last_active.bufnr and \" (active)\" or \"\")\n end,\n vim.tbl_filter(function(buf)\n return buf.is_visible\n end, editor_info.buffers)\n )\n\n local loaded = vim.tbl_map(\n function(buf)\n return string.format(\"%s%s\", buf.name, buf.bufnr == editor_info.last_active.bufnr and \" (active)\" or \"\")\n end,\n vim.tbl_filter(function(buf)\n return (not buf.is_visible) and buf.is_loaded\n end, editor_info.buffers)\n )\n\n -- Format workspace files\n local workspace_files = vim.tbl_map(function(file)\n return string.format(\"%s (%s, %.2fKB)\", file.name, file.type, file.size / 1024)\n end, dir_info.files)\n\n local text = string.format(\n [[\n\n## System Information\nOS: %s (%s)\nHostname: %s\nUser: %s\nShell: %s\nMemory: %.2f GB total, %.2f GB free\n\n## Workspace\nCurrent Directory: %s\nGit Repository: %s\nFiles: %d\n\n## Workspace Files\n%s\n\n## Neovim Visible Files\n%s\n\n## Neovim Loaded Files\n%s\n\n## Current Time\n%s\n\n ]],\n os_info.os_name,\n os_info.arch,\n os_info.hostname,\n os_info.env.user,\n os_info.env.shell,\n os_info.memory.total / (1024 * 1024 * 1024),\n os_info.memory.free / (1024 * 1024 * 1024),\n os_info.cwd,\n dir_info.is_git and \"Yes\" or \"No\",\n #dir_info.files,\n table.concat(workspace_files, \"\\n\"),\n table.concat(visible, \"\\n\"),\n table.concat(loaded, \"\\n\"),\n os.date(\"%Y-%m-%d %H:%M:%S\")\n )\n return res:text(text):send()\n end,\n}\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/diff_parser.lua", "local issue_tracker = require(\"mcphub.native.neovim.files.edit_file.issue_tracker\")\n\n---@class DiffParser\n---@field config ParserConfig Configuration options\n---@field tracker IssueTracker Issue tracking instance\nlocal DiffParser = {}\nDiffParser.__index = DiffParser\n\n-- Default parser configuration\nlocal DEFAULT_CONFIG = {\n track_issues = true, -- Track parsing issues for LLM feedback\n extract_inline_content = true, -- Handle content on marker lines\n}\n\n-- Create new diff parser instance\n---@param config ParserConfig? Optional configuration\n---@return DiffParser\nfunction DiffParser.new(config)\n local self = setmetatable({}, DiffParser)\n self.config = vim.tbl_deep_extend(\"force\", DEFAULT_CONFIG, config or {})\n self.tracker = issue_tracker.new()\n return self\nend\n\n-- Parse diff string into structured blocks\n---@param diff_content string Raw diff content from LLM\n---@return ParsedBlock[]? blocks Parsed blocks (nil on error)\n---@return string? error_message Error message if parsing failed\nfunction DiffParser:parse(diff_content)\n if not diff_content or diff_content == \"\" then\n return nil, \"Empty diff content\"\n end\n\n -- Clear previous issues\n self.tracker:clear()\n\n -- Normalize and fix malformed content\n local normalized_diff = self:_normalize_content(diff_content)\n local fixed_diff = self:_fix_malformed_diff(normalized_diff)\n\n -- Parse the diff into blocks\n local blocks, error = self:_parse_blocks(fixed_diff)\n if error then\n return nil, error\n end\n\n return blocks, nil\nend\n\n-- Check if any issues were found\n---@return boolean has_issues\nfunction DiffParser:has_issues()\n return self.tracker:has_issues()\nend\n\n-- Clear tracked issues\nfunction DiffParser:clear_issues()\n self.tracker:clear()\nend\n\n-- Normalize line endings and basic cleanup\n---@param diff_content string Raw diff content\n---@return string normalized_content\nfunction DiffParser:_normalize_content(diff_content)\n -- Normalize line endings\n local text = diff_content:gsub(\"\\r\\n\", \"\\n\"):gsub(\"\\r\", \"\\n\")\n return text\nend\n\n-- Fix common malformed diff patterns from LLMs\n---@param diff_content string Normalized diff content\n---@return string fixed_content\nfunction DiffParser:_fix_malformed_diff(diff_content)\n local lines = vim.split(diff_content, \"\\n\")\n\n -- Check if we have any search marker at all\n local has_search_marker = false\n for _, line in ipairs(lines) do\n if self:_detect_marker_type(line) == \"search\" then\n has_search_marker = true\n break\n end\n end\n\n if has_search_marker then\n return diff_content\n end\n\n self.tracker:track_issue(\"MALFORMED_SEARCH_MARKER\")\n\n -- Handle markdown code blocks\n local first_line = lines[1]\n if first_line and first_line:match(\"^%s*```\") then\n table.insert(lines, 2, \"<<<<<<< SEARCH\")\n if self.config.track_issues then\n self.tracker:track_issue(\"MARKDOWN_NOISE\")\n end\n else\n table.insert(lines, 1, \"<<<<<<< SEARCH\")\n end\n\n return table.concat(lines, \"\\n\")\nend\n\n-- Parse fixed diff content into blocks\n---@param diff_content string Fixed diff content\n---@return ParsedBlock[]? blocks Parsed blocks (nil on error)\n---@return string? error_message Error message if parsing failed\nfunction DiffParser:_parse_blocks(diff_content)\n local lines = vim.split(diff_content, \"\\n\")\n local blocks = {}\n local current_search = {}\n local current_replace = {}\n local state = \"waiting\" -- \"waiting\", \"searching\", \"replacing\"\n local block_counter = 1\n\n for line_num, line in ipairs(lines) do\n local marker_type, inline_content = self:_detect_marker_type(line, true)\n\n if marker_type == \"search\" then\n if state ~= \"waiting\" then\n return nil,\n \"Unexpected SEARCH marker at line \"\n .. line_num\n .. \" - expected SEPARATOR or REPLACE marker. If content to search or replace for contains <<<<<<< SEARCH, please escape it with a backslash like \\\\<<<<<<< SEARCH. SEARCH marker must be the first line of a block.\"\n end\n -- Start of search block\n state = \"searching\"\n current_search = {}\n\n -- Handle inline content on search marker line\n if inline_content and self.config.extract_inline_content then\n table.insert(current_search, inline_content)\n end\n elseif marker_type == \"separator\" then\n if state ~= \"searching\" then\n return nil,\n \"Unexpected separator at line \"\n .. line_num\n .. \" - expected SEARCH marker. If content to search or replace for contains ======, please escape it with a backslash like \\\\======. Separator must be between SEARCH and REPLACE markers.\"\n end\n -- Transition from search to replace\n state = \"replacing\"\n current_replace = {}\n elseif marker_type == \"replace\" then\n if state ~= \"replacing\" then\n return nil,\n \"Unexpected REPLACE marker at line \"\n .. line_num\n .. \" - expected REPLACE marker. If content to search or replace for contains >>>>>>> REPLACE, please escape it with a backslash like \\\\>>>>>> REPLACE. REPLACE marker must follow a SEARCH marker and a SEPARATOR.\"\n end\n -- End of replace block - create block\n state = \"waiting\"\n\n -- Handle inline content on replace marker line\n if inline_content and self.config.extract_inline_content then\n table.insert(current_replace, inline_content)\n end\n\n -- Create the block\n local search_content = table.concat(current_search, \"\\n\")\n local replace_content = table.concat(current_replace, \"\\n\")\n\n -- Skip empty blocks (unless it's intentional deletion)\n if search_content ~= \"\" or replace_content ~= \"\" then\n local block = {\n search_content = search_content,\n replace_content = replace_content,\n block_id = \"Block \" .. block_counter,\n search_lines = vim.deepcopy(current_search),\n replace_lines = vim.deepcopy(current_replace),\n }\n table.insert(blocks, block)\n block_counter = block_counter + 1\n end\n elseif state == \"searching\" then\n -- Collect search content\n table.insert(current_search, self:unescape_markers(line))\n elseif state == \"replacing\" then\n -- Collect replace content\n table.insert(current_replace, self:unescape_markers(line))\n end\n end\n\n -- Handle incomplete blocks\n if state == \"searching\" and #current_search > 0 then\n return nil, \"Incomplete search block - missing separator or replace section\"\n end\n\n if state == \"replacing\" then\n return nil, \"Incomplete replace block - missing replace marker\"\n end\n\n if #blocks == 0 then\n return nil, \"No valid SEARCH/REPLACE blocks found\"\n end\n\n return blocks, nil\nend\n\n-- Detect marker type and extract inline content\n---@param line string Line to analyze\n---@param track boolean Track issues if true\n---@return string? marker_type \"search\", \"separator\", \"replace\", or nil\n---@return string? inline_content Content found on marker line\nfunction DiffParser:_detect_marker_type(line, track)\n -- Search marker: minimum 5 < chars, optional spaces, case-insensitive SEARCH\n local search_arrows, search_spaces, search_keyword, search_content =\n line:match(\"^%s*(<<<<<+)(%s*)([Ss][Ee][Aa][Rr][Cc][Hh])(.*)$\")\n\n if search_arrows then\n local inline_content = nil\n\n if self.config.extract_inline_content and search_content and search_content:match(\"%S\") then\n -- Handle claude-4 case: \"<<<<<<< SEARCH> content\", use .- to handle cases with just >. If not the inline content becomes `>` and the first file line will be matched with >\n local claude_content = search_content:match(\"^>%s*(.-)$\")\n if claude_content then\n if claude_content ~= \"\" then\n inline_content = claude_content\n end\n if track then\n self.tracker:track_issue(\"CLAUDE_MARKER_ISSUE\", { inline_content = claude_content, line = line })\n end\n else\n -- Regular content after marker\n local regular_content = search_content:match(\"^%s*(.+)$\")\n if regular_content and regular_content ~= \"\" then\n inline_content = regular_content\n end\n if track then\n self.tracker:track_issue(\"CONTENT_ON_MARKER_LINE\", { inline_content = inline_content, line = line })\n end\n end\n end\n\n -- Track spacing issues\n if track then\n if search_spaces == \"\" then\n self.tracker:track_issue(\"MISSING_SPACES_IN_MARKERS\")\n elseif #search_spaces > 1 then\n self.tracker:track_issue(\"EXTRA_SPACES_IN_MARKERS\")\n end\n -- Track case issues\n if search_keyword ~= \"SEARCH\" then\n self.tracker:track_issue(\"CASE_MISMATCH_MARKERS\")\n end\n end\n\n return \"search\", inline_content\n end\n\n -- Replace marker: minimum 5 > chars\n local replace_arrows, replace_spaces, replace_keyword, replace_trailing =\n line:match(\"^%s*(>>>>>+)(%s*)([Rr][Ee][Pp][Ll][Aa][Cc][Ee])(.*)$\")\n\n if replace_arrows then\n local inline_content = nil\n\n -- Check for content AFTER the marker (trailing content)\n if self.config.extract_inline_content and replace_trailing and replace_trailing:match(\"%S\") then\n inline_content = replace_trailing:match(\"^%s*(.-)%s*$\") -- trim spaces\n end\n\n -- Track spacing and case issues\n if track then\n if replace_spaces == \"\" then\n self.tracker:track_issue(\"MISSING_SPACES_IN_MARKERS\")\n elseif #replace_spaces > 1 then\n self.tracker:track_issue(\"EXTRA_SPACES_IN_MARKERS\")\n end\n\n if replace_keyword ~= \"REPLACE\" then\n self.tracker:track_issue(\"CASE_MISMATCH_MARKERS\")\n end\n end\n\n return \"replace\", inline_content\n end\n\n if line:match(\"^=======%s*$\") then\n return \"separator\", nil\n end\n\n return nil, nil\nend\n\n-- Get comprehensive feedback including statistics\n---@return string? feedback Complete feedback for LLM\nfunction DiffParser:get_feedback()\n local parsing_feedback = self.tracker:get_llm_feedback()\n if parsing_feedback then\n return \"## ISSUES WHILE PARSING DIFF\\n\" .. parsing_feedback\n end\nend\n\nfunction DiffParser:unescape_markers(line)\n local newline = line:gsub(\"^%s*\\\\<<<<<\", \"<<<<<<\"):gsub(\"^%s*\\\\=====\", \"=====\"):gsub(\"^%s*\\\\>>>>>\", \">>>>>\")\n newline = newline:gsub(\"^%s*\\\\\\\\<<<<<\", \"<<<<<<\"):gsub(\"^%s*\\\\\\\\=====\", \"=====\"):gsub(\"^%s*\\\\\\\\>>>>>\", \">>>>>\")\n return newline\nend\n\nreturn DiffParser\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/search_engine.lua", "-- Search Engine for Block Location\n\nlocal string_utils = require(\"mcphub.native.neovim.files.edit_file.string_utils\")\nlocal types = require(\"mcphub.native.neovim.files.edit_file.types\")\n\n---@class UsedRange\n---@field start_line integer Start of used range\n---@field end_line integer End of used range\n\n---@class SearchResult\n---@field score number Overall match score (0.0-1.0)\n---@field start_line integer Starting line position\n---@field line_details LineMatchDetail[] Per-line match details\n---@field match_type OverallMatchType Type of match found\n\n---@class SearchEngine\n---@field config table Configuration options\n---@field used_ranges UsedRange[] Track used line ranges to handle duplicate blocks\nlocal SearchEngine = {}\nSearchEngine.__index = SearchEngine\n\n-- Default configuration\nlocal DEFAULT_CONFIG = {\n fuzzy_threshold = 0.8, -- Minimum similarity score for fuzzy matches\n enable_fuzzy_matching = true, -- Allow fuzzy matching when exact fails\n early_termination_score = 1, -- Stop searching when match is this good\n max_search_iterations = 10000, -- Prevent runaway searches\n}\n\n-- Create new search engine instance\n---@param config table? Optional configuration\n---@return SearchEngine\nfunction SearchEngine.new(config)\n local self = setmetatable({}, SearchEngine)\n self.config = vim.tbl_deep_extend(\"force\", DEFAULT_CONFIG, config or {})\n self.used_ranges = {} -- Track used line ranges for duplicate handling\n return self\nend\n\n-- Reset used ranges (call this when starting a new file)\nfunction SearchEngine:reset_used_ranges()\n self.used_ranges = {}\nend\n\n-- Main search function - top-to-bottom linear approach\n---@param search_lines string[] Lines to search for\n---@param file_lines string[] All file lines\n---@return BlockLocationResult\nfunction SearchEngine:locate_block_in_file(search_lines, file_lines)\n if #search_lines == 0 then\n return {\n found = true,\n start_line = 1,\n end_line = 1,\n overall_score = 1,\n overall_match_type = types.OVERALL_MATCH_TYPE.exact,\n confidence = 100,\n found_content = table.concat(file_lines, \"\\n\"),\n found_lines = file_lines,\n line_details = {},\n search_metadata = {},\n }\n end\n -- Perform top-to-bottom linear search\n return self:_linear_search(search_lines, file_lines)\nend\n\n-- Linear top-to-bottom search that handles exact, whitespace, and fuzzy matches\n---@param search_lines string[] Lines to search for\n---@param file_lines string[] All file lines\n---@return BlockLocationResult\nfunction SearchEngine:_linear_search(search_lines, file_lines)\n local search_len = #search_lines\n local total_lines = #file_lines\n\n -- Validate bounds\n if total_lines < search_len then\n return {\n found = false,\n error = \"SEARCH block lines more than file lines. If you are rewriting the file, make sure the SEARCH block is empty\",\n }\n end\n\n ---@type SearchResult\n local best_result = {\n score = 0,\n start_line = -1,\n line_details = {},\n match_type = types.OVERALL_MATCH_TYPE.fuzzy_low, -- Default to lowest type\n }\n\n local iterations = 0\n local early_termination = false\n\n -- Search from top to bottom\n for start_pos = 1, total_lines - search_len + 1 do\n iterations = iterations + 1\n\n -- Check if this position is available (not used by previous blocks)\n if self:_is_position_available(start_pos, search_len) then\n local result = self:_evaluate_position(search_lines, file_lines, start_pos)\n\n -- For exact matches, take the first one found (top-to-bottom priority)\n if result.match_type == types.OVERALL_MATCH_TYPE.exact then\n best_result = result\n break\n end\n\n -- For fuzzy matches, keep track of the best one so far\n if self:_is_better_result(result, best_result) then\n best_result = result\n end\n end\n\n -- Prevent runaway searches\n if iterations >= self.config.max_search_iterations then\n break\n end\n end\n\n -- Check if we found a suitable match\n local min_score = self.config.enable_fuzzy_matching and self.config.fuzzy_threshold or 0.99\n if\n best_result.score >= min_score\n or best_result.match_type == types.OVERALL_MATCH_TYPE.exact\n or best_result.match_type == types.OVERALL_MATCH_TYPE.exact_whitespace\n then\n -- Mark this range as used\n self:_mark_range_used(best_result.start_line, best_result.start_line + search_len - 1)\n\n return self:_create_success_result(best_result, search_lines, file_lines)\n else\n return {\n found = false,\n error = \"No suitable match found\",\n overall_score = best_result.score,\n confidence = math.floor(best_result.score * 100),\n start_line = best_result.start_line,\n end_line = best_result.start_line + search_len - 1,\n found_content = table.concat(\n vim.tbl_map(function(\n line --[[@as LineMatchDetail]]\n )\n return line.found_line\n end, best_result.line_details),\n \"\\n\"\n ),\n }\n end\nend\n\n-- Check if a position is available (not already used)\n---@param start_line integer Starting position to check\n---@param search_len integer Length of the search block\n---@return boolean available True if position is available\nfunction SearchEngine:_is_position_available(start_line, search_len)\n local end_line = start_line + search_len - 1\n\n -- Early exit if no used ranges\n if #self.used_ranges == 0 then\n return true\n end\n\n for _, used_range in ipairs(self.used_ranges) do\n -- Check for overlap: ranges overlap if NOT (a.end < b.start OR a.start > b.end)\n if not (end_line < used_range.start_line or start_line > used_range.end_line) then\n return false -- Overlaps with used range\n end\n end\n\n return true\nend\n\n-- Mark a range as used\n---@param start_line integer Start of used range\n---@param end_line integer End of used range\nfunction SearchEngine:_mark_range_used(start_line, end_line)\n ---@type UsedRange\n local new_range = {\n start_line = start_line,\n end_line = end_line,\n }\n table.insert(self.used_ranges, new_range)\nend\n\n-- Evaluate a specific position for match quality\n---@param search_lines string[] Lines to search for\n---@param file_lines string[] All file lines\n---@param start_pos integer Starting position to evaluate\n---@return SearchResult result Match evaluation result\nfunction SearchEngine:_evaluate_position(search_lines, file_lines, start_pos)\n local search_len = #search_lines\n\n -- Bounds check\n if start_pos + search_len - 1 > #file_lines then\n return {\n score = 0,\n start_line = start_pos,\n line_details = {},\n match_type = types.OVERALL_MATCH_TYPE.fuzzy_low,\n }\n end\n\n ---@type LineMatchDetail[]\n local line_details = {}\n local total_score = 0\n local all_exact = true\n local all_whitespace_or_better = true\n\n -- Analyze each line\n for i = 1, search_len do\n local search_line = search_lines[i]\n local file_line = file_lines[start_pos + i - 1]\n local absolute_line_num = start_pos + i - 1\n\n local match_type, line_score, differences = string_utils.compare_lines(search_line, file_line)\n total_score = total_score + line_score\n\n ---@type LineMatchDetail\n local line_detail = {\n line_number = absolute_line_num,\n expected_line = search_line,\n found_line = file_line,\n line_score = line_score,\n line_match_type = match_type,\n differences = differences or {},\n }\n table.insert(line_details, line_detail)\n\n -- Track overall match quality (early exit for performance)\n if match_type ~= types.LINE_MATCH_TYPE.exact then\n all_exact = false\n end\n if match_type ~= types.LINE_MATCH_TYPE.exact and match_type ~= types.LINE_MATCH_TYPE.exact_whitespace then\n all_whitespace_or_better = false\n end\n end\n\n local avg_score = total_score / search_len\n\n -- Determine overall match type with clear thresholds\n local overall_match_type\n if all_exact then\n overall_match_type = types.OVERALL_MATCH_TYPE.exact\n elseif all_whitespace_or_better then\n overall_match_type = types.OVERALL_MATCH_TYPE.exact_whitespace\n elseif avg_score >= 0.85 then\n overall_match_type = types.OVERALL_MATCH_TYPE.fuzzy_high\n elseif avg_score >= 0.70 then\n overall_match_type = types.OVERALL_MATCH_TYPE.fuzzy_medium\n else\n overall_match_type = types.OVERALL_MATCH_TYPE.fuzzy_low\n end\n\n return {\n score = avg_score,\n start_line = start_pos,\n line_details = line_details,\n match_type = overall_match_type,\n }\nend\n\n-- Check if one result is better than another\n---@param new_result SearchResult New result to compare\n---@param current_best SearchResult Current best result\n---@return boolean is_better\nfunction SearchEngine:_is_better_result(new_result, current_best)\n -- Define priority order for match types\n local type_priority = {\n [types.OVERALL_MATCH_TYPE.exact] = 4,\n [types.OVERALL_MATCH_TYPE.exact_whitespace] = 3,\n [types.OVERALL_MATCH_TYPE.fuzzy_high] = 2,\n [types.OVERALL_MATCH_TYPE.fuzzy_medium] = 1,\n [types.OVERALL_MATCH_TYPE.fuzzy_low] = 0,\n }\n\n local new_priority = type_priority[new_result.match_type] or 0\n local current_priority = type_priority[current_best.match_type] or 0\n\n -- First compare by match type priority\n if new_priority ~= current_priority then\n return new_priority > current_priority\n end\n\n -- If same priority, compare by score\n return new_result.score >= current_best.score\nend\n\n-- Create successful search result\n---@param best_result table Best match found\n---@param search_lines string[] Original search lines\n---@param file_lines string[] All file lines\n---@return BlockLocationResult\nfunction SearchEngine:_create_success_result(best_result, search_lines, file_lines)\n local end_line = best_result.start_line + #search_lines - 1\n local found_lines = vim.list_slice(file_lines, best_result.start_line, end_line)\n\n return {\n found = true,\n start_line = best_result.start_line,\n end_line = end_line,\n overall_score = best_result.score,\n overall_match_type = best_result.match_type,\n confidence = math.floor(best_result.score * 100),\n found_content = table.concat(found_lines, \"\\n\"),\n found_lines = found_lines,\n line_details = best_result.line_details,\n }\nend\n\nreturn SearchEngine\n"], ["/mcphub.nvim/lua/mcphub/ui/capabilities/resource.lua", "local Base = require(\"mcphub.ui.capabilities.base\")\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal highlights = require(\"mcphub.utils.highlights\").groups\n\n---@class ResourceHandler : CapabilityHandler\nlocal ResourceHandler = setmetatable({}, {\n __index = Base,\n})\nResourceHandler.__index = ResourceHandler\nResourceHandler.type = \"resource\"\n\nfunction ResourceHandler:new(server_name, capability_info, view)\n local handler = Base.new(self, server_name, capability_info, view)\n return handler\nend\n\nfunction ResourceHandler:execute()\n -- Check if already executing\n if self.state.is_executing then\n vim.notify(\"Resource access is already in progress\", vim.log.levels.WARN)\n return\n end\n\n -- Set executing state\n self.state.is_executing = true\n self.state.error = nil\n self.view:draw()\n\n -- Access resource\n if State.hub_instance then\n State.hub_instance:access_resource(self.server_name, self.def.uri, {\n caller = {\n type = \"hubui\",\n hubui = State.ui_instance,\n },\n parse_response = true,\n callback = function(response, err)\n self:handle_response(response, err)\n self.view:draw()\n end,\n })\n end\nend\n\nfunction ResourceHandler:handle_action(line)\n local type = self:get_line_info(line)\n if type == \"submit\" then\n self:execute()\n end\nend\n\nfunction ResourceHandler:render(line_offset)\n line_offset = line_offset or 0\n -- Clear previous line tracking\n self:clear_line_tracking()\n\n local lines = {}\n\n -- Resource info section\n vim.list_extend(lines, self:render_section_start(\"Resource Information\"))\n\n -- Resource details\n local details = {\n NuiLine()\n :append(\"Name: \", highlights.muted)\n :append(self.def.name or \"N/A\", self.def.name and highlights.success or highlights.muted),\n NuiLine():append(\"Type: \", highlights.muted):append(self.def.mimeType or \"unknown\", highlights.info),\n NuiLine():append(\"URI: \", highlights.muted):append(self.def.uri, highlights.link),\n }\n\n vim.list_extend(lines, self:render_section_content(details, 2))\n table.insert(lines, Text.pad_line(NuiLine():append(\"│\", highlights.muted)))\n vim.list_extend(lines, self:render_section_content(Text.multiline(self:get_description(), highlights.muted), 2))\n vim.list_extend(lines, self:render_section_end())\n\n -- Action section\n table.insert(lines, Text.pad_line(NuiLine()))\n vim.list_extend(lines, self:render_section_start(\"Access Resource\"))\n\n -- Action button\n local button_line\n if self.state.is_executing then\n button_line = NuiLine()\n :append(\"[ \", highlights.muted)\n :append(\"Processing...\", highlights.muted)\n :append(\" ]\", highlights.muted)\n else\n button_line = NuiLine()\n :append(\"[ \", highlights.success_fill)\n :append(\"Access\", highlights.success_fill)\n :append(\" ]\", highlights.success_fill)\n end\n vim.list_extend(lines, self:render_section_content({ NuiLine():append(\" \"), button_line }, 2))\n\n -- Track submit line for interaction\n self:track_line(line_offset + #lines, \"submit\")\n\n -- Error message if any\n if self.state.error then\n table.insert(lines, Text.pad_line(NuiLine():append(\"│\", highlights.muted)))\n local error_lines = Text.multiline(self.state.error, highlights.error)\n vim.list_extend(lines, self:render_section_content(error_lines, 2))\n end\n\n vim.list_extend(lines, self:render_section_end())\n\n -- Result section if any\n vim.list_extend(lines, self:render_result())\n\n return lines\nend\n\nreturn ResourceHandler\n"], ["/mcphub.nvim/lua/mcphub/utils/image_cache.lua", "--[[ MCPHub image cache utilities ]]\nlocal M = {}\n\n-- Cache directory\nM.cache_dir = vim.fn.stdpath(\"cache\") .. \"/mcphub/images\"\n\nlocal counter = 0\n--- Get unique filename based on content hash\n---@param data string Base64 encoded image data\n---@param mime_type string MIME type of the image\n---@return string filename\nlocal function get_unique_filename(data, mime_type)\n -- local hash = vim.fn.sha256(data)\n local time = os.time() + counter\n counter = counter + 1\n local ext = mime_type:match(\"image/(%w+)\") or \"bin\"\n return string.format(\"%s.%s\", time, ext)\nend\n--- Save image to temp file and return file path\n---@param data string Base64 encoded image data\n---@param mime_type string MIME type of the image\n---@return string|nil filepath Path to saved file\nfunction M.save_image(data, mime_type)\n local filename = get_unique_filename(data, mime_type)\n local filepath = M.cache_dir .. \"/\" .. filename\n\n -- Open file with proper error handling\n local file, err = io.open(filepath, \"wb\")\n if not file then\n error(string.format(\"Failed to open file for writing: %s\", err))\n return nil\n end\n\n local success, result = pcall(function()\n -- Try base64 decode if it looks like base64\n if type(data) == \"string\" and data:match(\"^[A-Za-z0-9+/]+=*$\") then\n local ok, decoded = pcall(vim.base64.decode, data)\n if ok then\n file:write(decoded)\n return\n end\n end\n\n -- Handle binary/blob data\n if type(data) == \"string\" then\n file:write(data)\n else\n error(\"Unsupported data type: \" .. type(data))\n end\n end)\n\n file:close()\n\n if not success then\n vim.fn.delete(filepath)\n error(string.format(\"Failed to write image data: %s\", result))\n return nil\n end\n\n return filepath\nend\n--- Clean all cached images\nfunction M.cleanup()\n -- Get all files in the cache directory\n local files = vim.fn.glob(M.cache_dir .. \"/*\", true, true)\n for _, file in ipairs(files) do\n vim.fn.delete(file)\n end\nend\n\n--- Initialize image cache\nfunction M.setup()\n -- Create cache directory if it doesn't exist\n vim.fn.mkdir(M.cache_dir, \"p\")\n\n -- Setup cleanup on exit\n vim.api.nvim_create_autocmd(\"VimLeavePre\", {\n group = vim.api.nvim_create_augroup(\"mcphub_image_cache\", { clear = true }),\n callback = function()\n M.cleanup()\n end,\n })\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/ui/views/help.lua", "---@brief [[\n--- Help view for MCPHub UI\n--- Shows plugin documentation and keybindings\n---@brief ]]\nlocal Text = require(\"mcphub.utils.text\")\nlocal View = require(\"mcphub.ui.views.base\")\n\n---@class HelpView:View\n---@field active_tab string Currently active tab\nlocal HelpView = setmetatable({}, {\n __index = View,\n})\nHelpView.__index = HelpView\n\nfunction HelpView:new(ui)\n ---@class View\n local instance = View:new(ui, \"help\")\n instance.tabs = {\n { id = \"welcome\", text = \"Welcome\" },\n { id = \"troubleshooting\", text = \"Troubleshooting\" },\n { id = \"native\", text = \"Native Servers\" },\n { id = \"changelog\", text = \"Changelog\" },\n }\n instance.active_tab = instance.tabs[1].id\n instance = setmetatable(instance, HelpView)\n return instance\nend\n\nfunction HelpView:cycle_tab()\n for i, tab in ipairs(self.tabs) do\n if tab.id == self.active_tab then\n -- Move to next tab or wrap around to first\n self.active_tab = (self.tabs[i + 1] or self.tabs[1]).id\n break\n end\n end\nend\n\nfunction HelpView:cycle_tab_reverse()\n for i, tab in ipairs(self.tabs) do\n if tab.id == self.active_tab then\n -- Move to previous tab or wrap around to last\n self.active_tab = (self.tabs[i - 1] or self.tabs[#self.tabs]).id\n break\n end\n end\nend\n\nfunction HelpView:render_tabs()\n local tabs = vim.tbl_map(function(tab)\n return {\n text = tab.text,\n selected = self.active_tab == tab.id,\n }\n end, self.tabs)\n return Text.create_tab_bar(tabs, self:get_width())\nend\n\nfunction HelpView:get_initial_cursor_position()\n -- Position after header\n local lines = self:render_header()\n return #lines + 2\nend\n\nfunction HelpView:before_enter()\n View.before_enter(self)\n\n -- Set up keymaps\n self.keymaps = {\n [\"\"] = {\n action = function()\n self:cycle_tab()\n self:draw()\n end,\n desc = \"Next tab\",\n },\n [\"\"] = {\n action = function()\n self:cycle_tab_reverse()\n self:draw()\n end,\n desc = \"Previous tab\",\n },\n }\nend\n\nfunction HelpView:render()\n -- Get base header\n local lines = self:render_header(false)\n\n -- Add tab bar\n table.insert(lines, self:render_tabs())\n table.insert(lines, Text.empty_line())\n\n -- Get prompt utils for accessing documentation\n local prompt_utils = require(\"mcphub.utils.prompt\")\n\n -- Render content based on active tab\n if self.active_tab == \"welcome\" then\n -- Welcome message\n local welcome_content = [[\n# Welcome to MCPHub!\n\nMCP Hub is a MCP client for neovim that seamlessly integrates [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) servers into your editing workflow. It provides an intuitive interface for managing, testing, and using MCP servers with your favorite chat plugins.\n\n> Visit [Documentation](https://ravitemer.github.io/mcphub.nvim/) site for detailed instructions on how to use MCPHub.\n\n## Support Development\n\nMCPHub is an open-source project that relies on community support. Your support helps maintain and enhance the plugin.\n\n- [GitHub Sponsors](https://github.com/sponsors/ravitemer)\n- [Buy me a coffee](https://www.buymeacoffee.com/ravitemer)\n- [⭐ Star us on GitHub](https://github.com/ravitemer/mcphub.nvim)\n\n### Get Help & Contribute\n- [View Documentation](https://ravitemer.github.io/mcphub.nvim/) - Learn more about MCPHub\n- [Discord Community](https://discord.gg/NTqfxXsNuN) - Get help and discuss features\n- [Open a Discussion](https://github.com/ravitemer/mcphub.nvim/discussions) - Ask questions and share ideas\n- [Create an Issue](https://github.com/ravitemer/mcphub.nvim/issues) - Report bugs\n- [Report Security Issues](https://github.com/ravitemer/mcphub.nvim/blob/main/SECURITY.md)\n\n### Share with the Community\n- Create your own Native MCP Servers and share them in [Show and Tell](https://github.com/ravitemer/mcphub.nvim/discussions/categories/show-and-tell)\n- Share your custom workflows and setups in [Native Servers](https://github.com/ravitemer/mcphub.nvim/discussions/categories/native-servers)\n- Help others by sharing your configuration tips and tricks\n- Showcase your innovative uses of MCPHub\n\n### Join & Connect\n- [Discord Community](https://discord.gg/NTqfxXsNuN) - Get help and discuss features\n- [Follow on Twitter](https://x.com/ravitemer) - Stay updated on new releases\n- Star the repository to show your support!\n\n### Stay Updated\n- Check the **Changelog** tab for latest features\n- Watch **Discussions** for announcements and community showcases\n- Browse **Marketplace** for new MCP servers\n]]\n vim.list_extend(lines, Text.render_markdown(welcome_content))\n elseif self.active_tab == \"troubleshooting\" then\n local troubleshooting_content = prompt_utils.get_troubleshooting_guide()\n vim.list_extend(lines, Text.render_markdown(troubleshooting_content))\n elseif self.active_tab == \"native\" then\n -- Native server documentation\n local native_guide = prompt_utils.get_native_server_prompt()\n if native_guide then\n vim.list_extend(lines, Text.render_markdown(native_guide))\n else\n table.insert(lines, Text.pad_line(\"Native server guide not found\", Text.highlights.error))\n end\n else -- changelog\n local changelog = prompt_utils.get_plugin_changelog()\n if changelog then\n vim.list_extend(lines, Text.render_markdown(changelog))\n else\n table.insert(lines, Text.pad_line(\"Changelog not found\", Text.highlights.error))\n end\n end\n\n return lines\nend\n\nreturn HelpView\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/lsp.lua", "local lsp_utils = require(\"mcphub.native.neovim.utils.lsp\")\nlocal mcphub = require(\"mcphub\")\n\nmcphub.add_resource(\"neovim\", {\n name = \"Diagnostics: Buffer\",\n description = \"Get diagnostics for the current file\",\n uri = \"neovim://diagnostics/buffer\",\n mimeType = \"text/plain\",\n handler = function(req, res)\n -- local context = utils.parse_context(req.caller)\n local buf_info = req.editor_info.last_active\n if not buf_info then\n return res:error(\"No active buffer found\")\n end\n local bufnr = buf_info.bufnr\n local filepath = buf_info.filename\n local diagnostics = vim.diagnostic.get(bufnr)\n local text = string.format(\"Diagnostics for: %s\\n%s\\n\", filepath, string.rep(\"-\", 40))\n for _, diag in ipairs(diagnostics) do\n local severity = vim.diagnostic.severity[diag.severity] or \"UNKNOWN\"\n local line_str = string.format(\"Line %d, Col %d\", diag.lnum + 1, diag.col + 1)\n local source = diag.source and string.format(\"[%s]\", diag.source) or \"\"\n local code = diag.code and string.format(\" (%s)\", diag.code) or \"\"\n\n -- Get range information if available\n local range_info = \"\"\n if diag.end_lnum and diag.end_col then\n range_info = string.format(\" to Line %d, Col %d\", diag.end_lnum + 1, diag.end_col + 1)\n end\n\n text = text\n .. string.format(\n \"\\n%s: %s\\n Location: %s%s\\n Message: %s%s\\n\",\n severity,\n source,\n line_str,\n range_info,\n diag.message,\n code\n )\n\n text = text .. string.rep(\"-\", 40) .. \"\\n\"\n end\n return res:text(text ~= \"\" and text or \"No diagnostics found\"):send()\n end,\n})\n\nmcphub.add_resource(\"neovim\", {\n name = \"Diagnostics: Workspace\",\n description = \"Get diagnostics for all open buffers\",\n uri = \"neovim://diagnostics/workspace\",\n mimeType = \"text/plain\",\n handler = function(req, res)\n local diagnostics = lsp_utils.get_all_diagnostics()\n local text = \"Workspace Diagnostics\\n\" .. string.rep(\"=\", 40) .. \"\\n\\n\"\n\n -- Group diagnostics by buffer\n local by_buffer = {}\n for _, diag in ipairs(diagnostics) do\n by_buffer[diag.bufnr] = by_buffer[diag.bufnr] or {}\n table.insert(by_buffer[diag.bufnr], diag)\n end\n\n -- Format diagnostics for each buffer\n for bufnr, diags in pairs(by_buffer) do\n local filename = vim.api.nvim_buf_get_name(bufnr)\n text = text .. string.format(\"File: %s\\n%s\\n\", filename, string.rep(\"-\", 40))\n\n for _, diag in ipairs(diags) do\n local severity = vim.diagnostic.severity[diag.severity] or \"UNKNOWN\"\n local line_str = string.format(\"Line %d, Col %d\", diag.lnum + 1, diag.col + 1)\n local source = diag.source and string.format(\"[%s]\", diag.source) or \"\"\n local code = diag.code and string.format(\" (%s)\", diag.code) or \"\"\n\n -- Get range information if available\n local range_info = \"\"\n if diag.end_lnum and diag.end_col then\n range_info = string.format(\" to Line %d, Col %d\", diag.end_lnum + 1, diag.end_col + 1)\n end\n\n text = text\n .. string.format(\n \"\\n%s: %s\\n Location: %s%s\\n Message: %s%s\\n\",\n severity,\n source,\n line_str,\n range_info,\n diag.message,\n code\n )\n end\n text = text .. string.rep(\"-\", 40) .. \"\\n\\n\"\n end\n\n return res:text(text ~= \"\" and text or \"No diagnostics found\"):send()\n end,\n})\n"], ["/mcphub.nvim/lua/mcphub/utils/workspace.lua", "local M = {}\n\nlocal uv = (vim.loop or vim.uv)\nlocal path = require(\"plenary.path\")\nlocal utils = require(\"mcphub.utils\")\n\n---Search upward from current directory for any of the look_for files\n---@param look_for_patterns string[] Array of file patterns to look for\n---@param start_dir? string Starting directory (defaults to current working directory)\n---@return table|nil { root_dir = \"/path\", config_file = \"/path/.vscode/mcp.json\" } or nil\nfunction M.find_workspace_config(look_for_patterns, start_dir)\n start_dir = start_dir or vim.fn.getcwd()\n\n local current_dir = path:new(start_dir)\n local parent_dir = current_dir:parent()\n -- Search upward until we hit the root\n while current_dir and tostring(current_dir) ~= tostring(parent_dir) do\n -- Check each pattern in order\n for _, pattern in ipairs(look_for_patterns) do\n local config_file = current_dir / pattern\n if config_file:exists() then\n return {\n root_dir = tostring(current_dir),\n config_file = tostring(config_file),\n }\n end\n end\n\n -- Move up one directory\n current_dir = parent_dir\n parent_dir = current_dir:parent()\n end\n\n return nil\nend\n\n---Hash workspace path to generate a consistent port\n---@param workspace_path string Absolute path to workspace root\n---@param port_range table {min: number, max: number}\n---@return number Generated port number\nfunction M.generate_workspace_port(workspace_path, port_range)\n -- Simple hash function using string bytes\n local hash = 0\n for i = 1, #workspace_path do\n hash = (hash * 31 + string.byte(workspace_path, i)) % 2147483647\n end\n\n -- Map hash to port range\n local range_size = port_range.max - port_range.min + 1\n return port_range.min + (hash % range_size)\nend\n\n---Check if a port is available\n---@param port number Port number to check\n---@return boolean True if port is available\nfunction M.is_port_available(port)\n local handle = uv.new_tcp()\n if not handle then\n return false\n end\n\n local success = handle:bind(\"127.0.0.1\", port)\n handle:close()\n\n return success\nend\n\n---Find next available port starting from generated port\n---@param workspace_path string Workspace root path\n---@param port_range table {min: number, max: number}\n---@param max_attempts? number Maximum attempts to find a port (default: 100)\n---@return number|nil Available port number or nil if none found\nfunction M.find_available_port(workspace_path, port_range, max_attempts)\n max_attempts = max_attempts or 100\n\n local base_port = M.generate_workspace_port(workspace_path, port_range)\n\n for i = 0, max_attempts - 1 do\n local port = base_port + i\n\n -- Wrap around if we exceed max port\n if port > port_range.max then\n port = port_range.min + (port - port_range.max - 1)\n end\n\n if M.is_port_available(port) then\n return port\n end\n end\n\n return nil\nend\n\n---Get the path to the global workspace cache file\n---@return string Absolute path to workspace cache file\nfunction M.get_workspace_cache_path()\n -- Get home directory using Neovim's cross-platform approach\n local home = vim.fn.expand(\"~\")\n\n if not home or home == \"~\" then\n -- Fallback to environment variables if expand fails\n home = os.getenv(\"HOME\")\n or os.getenv(\"USERPROFILE\")\n or (os.getenv(\"HOMEDRIVE\") and os.getenv(\"HOMEPATH\") and (os.getenv(\"HOMEDRIVE\") .. os.getenv(\"HOMEPATH\")))\n end\n\n if not home then\n error(\"Unable to determine user home directory\")\n end\n\n -- Check for legacy path first (same logic as backend)\n local legacy_path = vim.fs.joinpath(home, \".mcp-hub\", \"workspaces.json\")\n\n -- Use legacy path if it exists (matching backend behavior)\n if vim.fn.filereadable(legacy_path) == 1 then\n return legacy_path\n end\n\n -- Otherwise use XDG-compliant path\n local state_home = os.getenv(\"XDG_STATE_HOME\") or vim.fs.joinpath(home, \".local\", \"state\")\n local cache_dir = vim.fs.joinpath(state_home, \"mcp-hub\")\n return vim.fs.joinpath(cache_dir, \"workspaces.json\")\nend\n\n---Read the global workspace cache from mcp-hub's state directory\n---@return table Table of workspace_path -> {pid, port, startTime}\nfunction M.read_workspace_cache()\n local cache_path = M.get_workspace_cache_path()\n local cache_file = path:new(cache_path)\n\n if not cache_file:exists() then\n return {}\n end\n\n local content = cache_file:read()\n if not content or content == \"\" then\n return {}\n end\n\n local success, cache = utils.json_decode(content)\n if not success then\n vim.notify(\"Failed to parse workspace cache: \" .. cache_path, vim.log.levels.WARN)\n return {}\n end\n\n return cache or {}\nend\n\n---Check if a process is still running\n---@param pid number Process ID to check\n---@return boolean True if process is running\nfunction M.is_process_running(pid)\n if not pid or type(pid) ~= \"number\" then\n return false\n end\n\n -- Use kill with signal 0 to check if process exists\n local success = pcall(function()\n uv.kill(pid, 0)\n end)\n\n return success\nend\n\n---Get active hub info for a workspace\n---@param port string current port of the hub\n---@return table|nil {port, pid, startTime, config_files} or nil if no active hub\nfunction M.get_workspace_hub_info(port)\n port = tostring(port) -- Ensure port is a string\n local cache = M.read_workspace_cache()\n local entry = cache[port]\n\n if not entry then\n return nil\n end\n\n -- Check if the process is still running\n if not M.is_process_running(entry.pid) then\n return nil\n end\n\n return entry\nend\n\n-- Enhanced function to find matching hub by workspace + config\nfunction M.find_matching_workspace_hub(workspace_path, config_files)\n local cache = M.read_workspace_cache()\n\n -- Search through ALL cache entries (keyed by port now)\n for port_str, entry in pairs(cache) do\n -- Check if workspace matches\n if entry.cwd == workspace_path then\n -- Check if config files match\n if vim.deep_equal(entry.config_files or {}, config_files) then\n -- Check if process is still running\n if M.is_process_running(entry.pid) then\n return {\n port = entry.port,\n pid = entry.pid,\n startTime = entry.startTime,\n config_files = entry.config_files,\n workspace_path = entry.cwd,\n }\n end\n end\n end\n end\n\n return nil\nend\n\n---Check if workspace mode is enabled\n---@return boolean True if workspace mode is enabled\nfunction M.is_workspace_enabled()\n local State = require(\"mcphub.state\")\n return State.config and State.config.workspace and State.config.workspace.enabled == true\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/ui/views/config.lua", "---@brief [[\n--- Config view for MCPHub UI\n--- Shows MCP server configurations\n---@brief ]]\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal View = require(\"mcphub.ui.views.base\")\n\n---@class ConfigView:View\n---@field current_tab_index number Currently selected tab index\n---@field config_files string[] List of config file paths\nlocal ConfigView = setmetatable({}, {\n __index = View,\n})\nConfigView.__index = ConfigView\n\nfunction ConfigView:new(ui)\n local instance = View:new(ui, \"config\") -- Create base view with name\n instance.current_tab_index = 1\n instance.config_files = {}\n return setmetatable(instance, ConfigView)\nend\n\nfunction ConfigView:before_enter()\n View.before_enter(self)\n\n -- Get active config files from ConfigManager\n local ConfigManager = require(\"mcphub.utils.config_manager\")\n self.config_files = ConfigManager.get_active_config_files()\n\n -- Reverse the order of config files for tab display\n local reversed_files = {}\n for i = #self.config_files, 1, -1 do\n table.insert(reversed_files, self.config_files[i])\n end\n self.config_files = reversed_files\n\n -- Ensure we have a valid tab index\n if #self.config_files == 0 then\n self.current_tab_index = 1\n else\n self.current_tab_index = math.min(self.current_tab_index, #self.config_files)\n end\n\n -- Build keymaps based on available files\n self.keymaps = {\n [\"e\"] = {\n action = function()\n if #self.config_files > 0 then\n local current_file = self.config_files[self.current_tab_index]\n self.ui:toggle()\n vim.cmd(\"edit \" .. current_file)\n else\n vim.notify(\"No configuration file available\", vim.log.levels.ERROR)\n end\n end,\n desc = \"Edit config\",\n },\n }\n\n -- Add tab navigation keymaps only if multiple files exist\n if #self.config_files > 1 then\n self.keymaps[\"\"] = {\n action = function()\n self.current_tab_index = (self.current_tab_index % #self.config_files) + 1\n self:draw()\n end,\n desc = \"Next tab\",\n }\n self.keymaps[\"\"] = {\n action = function()\n self.current_tab_index = ((self.current_tab_index - 2) % #self.config_files) + 1\n self:draw()\n end,\n desc = \"Previous tab\",\n }\n end\nend\n\nfunction ConfigView:get_initial_cursor_position()\n -- Position at start of server configurations\n local lines = self:render_header()\n\n -- Add tab bar height if we have multiple files\n if #self.config_files > 0 then\n return #lines + 4 -- header + tab bar + separator\n else\n return #lines + 3 -- header + file info\n end\nend\n\nfunction ConfigView:render()\n -- Get base header\n local lines = self:render_header(false)\n\n if #self.config_files == 0 then\n -- No config files available\n table.insert(lines, Text.pad_line(NuiLine():append(\"No configuration files available\", Text.highlights.warn)))\n return lines\n end\n\n -- Render tab bar if multiple files\n if #self.config_files > 0 then\n local tabs = {}\n for i, file_path in ipairs(self.config_files) do\n local file_name = vim.fn.fnamemodify(file_path, \":t\") -- Get just filename\n local icon = Text.icons.folder -- Default to workspace/project icon\n\n -- Last file is treated as global\n if i == #self.config_files then\n icon = Text.icons.globe\n end\n\n table.insert(tabs, {\n text = icon .. \" \" .. file_name,\n selected = i == self.current_tab_index,\n })\n end\n\n table.insert(lines, Text.create_tab_bar(tabs, self:get_width()))\n table.insert(lines, Text.empty_line())\n end\n\n -- Show current file path\n local current_file = self.config_files[self.current_tab_index]\n if current_file then\n local file_line = NuiLine():append(Text.icons.file .. \" \" .. current_file, Text.highlights.muted)\n table.insert(lines, Text.pad_line(file_line))\n end\n\n table.insert(lines, Text.empty_line())\n\n -- Get and validate current file content\n local ConfigManager = require(\"mcphub.utils.config_manager\")\n local file_content, file_read_error = ConfigManager.get_file_content_json(current_file)\n\n if not file_content then\n -- table.insert(lines, self:center(NuiLine():append(\"Failed to load configuration file\", Text.highlights.error)))\n vim.list_extend(lines, vim.tbl_map(Text.pad_line, Text.multiline(file_read_error or \"\", Text.highlights.error)))\n table.insert(lines, Text.empty_line())\n else\n -- Show file content with JSON highlighting\n vim.list_extend(lines, Text.render_json(file_content, { use_jq = true }))\n end\n\n return lines\nend\n\nreturn ConfigView\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/block_locator.lua", "local types = require(\"mcphub.native.neovim.files.edit_file.types\")\n\n---@class BlockLocator\n---@field config LocatorConfig Configuration options\n---@field search_engine SearchEngine Search engine instance\nlocal BlockLocator = {}\nBlockLocator.__index = BlockLocator\n\n-- Default locator configuration\nlocal DEFAULT_CONFIG = {\n fuzzy_threshold = 0.8, -- Minimum similarity score for fuzzy matches\n enable_fuzzy_matching = true, -- Allow fuzzy matching when exact fails\n}\n\n-- Create new block locator instance\n---@param config LocatorConfig? Optional configuration\n---@return BlockLocator\nfunction BlockLocator.new(config)\n local self = setmetatable({}, BlockLocator)\n self.config = vim.tbl_deep_extend(\"force\", DEFAULT_CONFIG, config or {})\n local SearchEngine = require(\"mcphub.native.neovim.files.edit_file.search_engine\")\n self.search_engine = SearchEngine.new(self.config)\n return self\nend\n\n-- Locate all blocks in file content\n---@param parsed_blocks ParsedBlock[] Blocks from DiffParser\n---@param file_content string Content of the target file\n---@return LocatedBlock[] located_blocks Blocks with location information\nfunction BlockLocator:locate_all_blocks(parsed_blocks, file_content)\n local file_lines = vim.split(file_content, \"\\n\", { plain = true, trimempty = true })\n local located_blocks = {}\n for _, parsed_block in ipairs(parsed_blocks) do\n if vim.trim(parsed_block.search_content) == \"\" then\n parsed_block.search_content = file_content\n parsed_block.search_lines = file_lines\n end\n\n local location_result = self.search_engine:locate_block_in_file(parsed_block.search_lines, file_lines)\n\n ---@type LocatedBlock\n local located_block = {\n search_content = parsed_block.search_content,\n replace_content = parsed_block.replace_content,\n block_id = parsed_block.block_id,\n search_lines = parsed_block.search_lines,\n replace_lines = parsed_block.replace_lines,\n location_result = location_result,\n }\n table.insert(located_blocks, located_block)\n end\n\n return located_blocks\nend\n\n-- Get comprehensive feedback including location statistics\n---@param located_blocks? LocatedBlock[] Processed blocks for statistics\n---@return string? feedback Complete feedback for LLM\nfunction BlockLocator:get_feedback(located_blocks)\n local search_logs = {}\n if located_blocks then\n for _, block in ipairs(located_blocks) do\n if not block.location_result.found then\n local found_content = block.location_result.found_content\n local best_match = \"\"\n local best_score = block.location_result.confidence\n if found_content then\n best_match = string.format(\n \"\\nThe following is the BEST MATCH found from Line `%s` to `%s` with `%s%%` confidence:\\n\",\n block.location_result.start_line or \"N/A\",\n block.location_result.end_line or \"N/A\",\n best_score\n )\n best_match = best_match\n .. string.format(\n -- '\\n%s\\n\\n\\n%s\\n',\n '\\n%s\\n',\n -- block.search_content,\n best_score,\n block.location_result.start_line or \"N/A\",\n block.location_result.end_line or \"N/A\",\n found_content\n )\n else\n best_match = \"\"\n end\n table.insert(\n search_logs,\n string.format(\n [[\n### `%s` (ERROR) \nFinding SEARCH content from `%s` failed with error: `%s`%s]],\n block.block_id,\n block.block_id,\n block.location_result.error,\n best_match\n )\n )\n end\n local is_fuzzy = block.location_result.found\n and (\n block.location_result.overall_match_type ~= types.OVERALL_MATCH_TYPE.exact\n and block.location_result.overall_match_type ~= types.OVERALL_MATCH_TYPE.exact_whitespace\n )\n if is_fuzzy then\n local diff = vim.diff(block.location_result.found_content, block.search_content, {\n result_type = \"unified\",\n }) --[[@as string?]]\n table.insert(\n search_logs,\n string.format(\n [[\n### `%s` (WARNING)\nSEARCH content from `%s` is fuzzily matched and applied at LINES `%s` to `%s` with `%.2f%%` confidence:\nThe following is a diff for `%s` SEARCH content vs Fuzzily matched content:\n```diff\n%s\n```]],\n block.block_id,\n block.block_id,\n block.location_result.start_line,\n block.location_result.end_line,\n block.location_result.confidence,\n block.block_id,\n vim.trim(diff or \"\")\n )\n )\n end\n end\n end\n if #search_logs > 0 then\n return \"## ISSUES WHILE SEARCHING\\n\" .. table.concat(search_logs, \"\\n\\n\")\n end\nend\n\nreturn BlockLocator\n"], ["/mcphub.nvim/lua/mcphub/ui/views/logs.lua", "---@brief [[\n--- Logs view for MCPHub UI\n--- Shows server output and errors\n---@brief ]]\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal View = require(\"mcphub.ui.views.base\")\nlocal renderer = require(\"mcphub.utils.renderer\")\n\n---@class LogsView:View\n---@field active_tab \"logs\"|\"issues\" Currently active tab\nlocal LogsView = setmetatable({}, {\n __index = View,\n})\nLogsView.__index = LogsView\n\nfunction LogsView:new(ui)\n ---@class View\n local instance = View:new(ui, \"logs\") -- Create base view with name\n instance.active_tab = \"logs\"\n return setmetatable(instance, LogsView)\nend\n\nfunction LogsView:render_tabs()\n local tabs = {\n {\n text = \"Server Logs\",\n selected = self.active_tab == \"logs\",\n },\n {\n text = \"Issues\",\n selected = self.active_tab == \"issues\",\n },\n }\n return Text.create_tab_bar(tabs, self:get_width())\nend\n\nfunction LogsView:before_enter()\n View.before_enter(self)\n\n -- Set up keymaps\n self.keymaps = {\n [\"\"] = {\n action = function()\n self.active_tab = self.active_tab == \"logs\" and \"issues\" or \"logs\"\n self:draw()\n end,\n desc = \"Next tab\",\n },\n [\"\"] = {\n action = function()\n -- Since we only have 2 tabs, reverse is the same as forward\n self.active_tab = self.active_tab == \"logs\" and \"issues\" or \"logs\"\n self:draw()\n end,\n desc = \"Previous tab\",\n },\n [\"x\"] = {\n action = function()\n if self.active_tab == \"logs\" then\n State.server_output.entries = {}\n else\n State:clear_errors()\n end\n self:draw()\n end,\n desc = \"Clear current tab\",\n },\n }\nend\n\nfunction LogsView:render()\n -- Get base header\n local lines = self:render_header(false)\n\n -- Add tab bar\n table.insert(lines, self:render_tabs())\n -- table.insert(lines, self:divider())\n table.insert(lines, Text.empty_line())\n\n -- Show empty state placeholders when no content\n if self.active_tab == \"logs\" and #State.server_output.entries == 0 then\n table.insert(lines, Text.pad_line(\"No server logs yet\", Text.highlights.muted))\n elseif self.active_tab == \"issues\" and #State.errors.items == 0 then\n table.insert(lines, Text.pad_line(\"No issues found - All systems running smoothly\", Text.highlights.muted))\n else\n -- Render content based on active tab\n if self.active_tab == \"logs\" then\n -- Show server output entries\n vim.list_extend(lines, renderer.render_server_entries(State.server_output.entries))\n else\n -- Show all errors with details\n vim.list_extend(lines, renderer.render_hub_errors(nil, true))\n end\n end\n\n return lines\nend\n\nreturn LogsView\n"], ["/mcphub.nvim/lua/mcphub/utils/nuiline.lua", "---@diagnostic disable: undefined-doc-name, return-type-mismatch, undefined-field\n--[[ Adapted from nui.line by Munif Tanjim\nSource: https://github.com/MunifTanjim/nui.nvim/blob/main/lua/nui/line/init.lua\nLicense: MIT ]]\nlocal NuiText = require(\"mcphub.utils.nuitext\")\n\n---@class NuiLine\nlocal Line = {}\nLine.__index = Line\n\n---@class NuiLine\n---@field _texts NuiText[]\n\n---@param texts? NuiText[]\nfunction Line:init(texts)\n self._texts = texts or {}\nend\n\n---@param content string|NuiText|NuiLine\n---@param highlight? string|nui_text_extmark highlight info\n---@return NuiText|NuiLine\nfunction Line:append(content, highlight)\n local block = content\n if block == nil then\n return self\n end\n if type(block) == \"string\" then\n block = NuiText(block, highlight)\n end\n if block._texts then\n ---@cast block NuiLine\n for _, text in ipairs(block._texts) do\n table.insert(self._texts, text)\n end\n else\n ---@cast block NuiText\n table.insert(self._texts, block)\n end\n return self\nend\n\n---@return string\nfunction Line:content()\n return table.concat(vim.tbl_map(function(text)\n return text:content()\n end, self._texts))\nend\n\n---@return number\nfunction Line:width()\n local width = 0\n for _, text in ipairs(self._texts) do\n width = width + text:width()\n end\n return width\nend\n\n---@param bufnr number buffer number\n---@param ns_id number namespace id\n---@param linenr number line number (1-indexed)\n---@param char_start? number start character position (0-indexed)\nfunction Line:highlight(bufnr, ns_id, linenr, char_start)\n local current_byte_start = char_start or 0\n for _, text in ipairs(self._texts) do\n text:highlight(bufnr, ns_id, linenr, current_byte_start)\n current_byte_start = current_byte_start + text:length()\n end\nend\n\n---@param bufnr number buffer number\n---@param ns_id number namespace id\n---@param linenr_start number start line number (1-indexed)\n---@param linenr_end? number end line number (1-indexed)\nfunction Line:render(bufnr, ns_id, linenr_start, linenr_end)\n local row_start = linenr_start - 1\n local row_end = linenr_end and linenr_end - 1 or row_start + 1\n local content = self:content()\n --handle newlines\n content = content:gsub(\"\\n\", \"\\\\n\")\n\n -- if vim.bo[bufnr].modifiable == false then\n -- vim.api.nvim_set_option_value(\"modifiable\", true, { buf = bufnr })\n -- end\n -- Clear existing content\n vim.api.nvim_buf_set_lines(bufnr, row_start, row_end, false, { \"\" })\n -- Insert new content at column 0\n vim.api.nvim_buf_set_text(bufnr, row_start, 0, row_start, 0, { content })\n -- Highlight from column 0\n self:highlight(bufnr, ns_id, linenr_start, 0)\nend\n\n-- Create a new line instance\nlocal function new_line(...)\n local instance = setmetatable({}, Line)\n instance:init(...)\n return instance\nend\n\n-- Static methods\n\n---@param content string text content\n---@param width number total width\n---@param align? \"left\"|\"center\"|\"right\" text alignment\n---@param highlight? string highlight group\n---@return NuiLine\nfunction Line.pad_text(content, width, align, highlight)\n local text_width = vim.api.nvim_strwidth(content)\n local padding = width - text_width\n\n if padding <= 0 then\n return new_line():append(content, highlight)\n end\n\n local line = new_line()\n local left_pad, right_pad = 0, 0\n\n if align == \"right\" then\n left_pad = padding\n elseif align == \"center\" then\n left_pad = math.floor(padding / 2)\n right_pad = padding - left_pad\n else -- left or default\n right_pad = padding\n end\n\n if left_pad > 0 then\n line:append(string.rep(\" \", left_pad))\n end\n line:append(content, highlight)\n if right_pad > 0 then\n line:append(string.rep(\" \", right_pad))\n end\n\n return line\nend\n\n---@param parts string[] text parts\n---@param highlight? string highlight group\n---@param separator? string separator between parts\n---@return NuiLine\nfunction Line.join(parts, highlight, separator)\n local line = new_line()\n separator = separator or \" \"\n\n for i, part in ipairs(parts) do\n if i > 1 then\n line:append(separator)\n end\n line:append(part, highlight)\n end\n\n return line\nend\n\n-- Create constructor\nlocal NuiLine = setmetatable({\n pad_text = Line.pad_text, -- Export static methods\n join = Line.join,\n}, {\n __call = function(_, ...)\n return new_line(...)\n end,\n})\n\nreturn NuiLine\n"], ["/mcphub.nvim/lua/mcphub/extensions/lualine.lua", "--[[\n--NOTE: Having cmd = \"MCPHub\" or lazy = true in user's lazy config, and adding lualine component using require(\"mcphub.extensions.lualine\") will start the hub indirectly.\n--]]\n\n-- DEPRECATED: This lualine component will load MCPHub even with lazy loading.\n-- Use the global variables approach instead: vim.g.mcphub_status, vim.g.mcphub_servers_count, vim.g.mcphub_executing\n-- See documentation for recommended usage: doc/extensions/lualine.md\n\nlocal M = require(\"lualine.component\"):extend()\nlocal utils = require(\"lualine.utils.utils\")\nlocal spinner_frames = { \"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\" }\nlocal spinner_interval = 80 -- ms between frames\nlocal timer = nil\nlocal current_frame = 1\n\nlocal default_options = {\n icon = \"\",\n colored = true,\n colors = {\n connected = { fg = utils.extract_highlight_colors(\"DiagnosticInfo\", \"fg\") },\n connecting = { fg = utils.extract_highlight_colors(\"DiagnosticWarn\", \"fg\") },\n error = { fg = utils.extract_highlight_colors(\"DiagnosticError\", \"fg\") },\n },\n}\n\nM.HubState = {\n STARTING = \"starting\",\n READY = \"ready\",\n ERROR = \"error\",\n RESTARTING = \"restarting\",\n RESTARTED = \"restarted\",\n STOPPED = \"stopped\",\n STOPPING = \"stopping\",\n}\n\nvim.g.mcphub_status = M.HubState.STARTING\n-- Initialize the component\nfunction M:init(options)\n vim.notify_once(\n \"MCPHub lualine extension is deprecated. Use global variables instead for better lazy-loading. See :help mcphub-lualine\",\n vim.log.levels.WARN\n )\n M.super.init(self, options)\n self:create_autocommands()\n self.options = vim.tbl_deep_extend(\"keep\", self.options or {}, default_options)\n self.highlights = {\n error = self:create_hl(self.options.colors.error, \"error\"),\n connecting = self:create_hl(self.options.colors.connecting, \"connecting\"),\n connected = self:create_hl(self.options.colors.connected, \"connected\"),\n }\n -- Determine whether the plugin's own coloring logic should apply to the icon or status text.\n self.plugin_colors_icon = self.options.colored and not self.options.icon_color_highlight\n self.plugin_colors_status = self.options.colored and not self.options.color_highlight\nend\n\nfunction M:create_autocommands()\n local group = vim.api.nvim_create_augroup(\"mcphub_lualine\", { clear = true })\n\n -- Handle state changes\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n pattern = \"MCPHubStateChange\",\n callback = function(args)\n self:manage_spinner()\n if args.data then\n vim.g.mcphub_status = args.data.state\n vim.g.mcphub_active_servers = args.data.active_servers\n end\n end,\n })\n\n -- Tool/Resource activity events\n vim.api.nvim_create_autocmd(\"User\", {\n group = group,\n pattern = { \"MCPHub*\" },\n callback = function(args)\n -- Update based on event pattern\n if args.match == \"MCPHubToolStart\" then\n vim.g.mcphub_executing = true\n vim.g.mcphub_tool_active = true\n vim.g.mcphub_tool_info = args.data\n elseif args.match == \"MCPHubToolEnd\" then\n vim.g.mcphub_executing = false\n vim.g.mcphub_tool_active = false\n vim.g.mcphub_tool_info = nil\n elseif args.match == \"MCPHubResourceStart\" then\n vim.g.mcphub_executing = true\n vim.g.mcphub_resource_active = true\n vim.g.mcphub_resource_info = args.data\n elseif args.match == \"MCPHubResourceEnd\" then\n vim.g.mcphub_executing = false\n vim.g.mcphub_resource_active = false\n vim.g.mcphub_resource_info = nil\n elseif args.match == \"MCPHubPromptStart\" then\n vim.g.mcphub_executing = true\n vim.g.mcphub_prompt_active = true\n vim.g.mcphub_prompt_info = args.data\n elseif args.match == \"MCPHubPromptEnd\" then\n vim.g.mcphub_executing = false\n vim.g.mcphub_prompt_active = false\n vim.g.mcphub_prompt_info = nil\n elseif args.match == \"MCPHubServersUpdated\" then\n if args.data then\n vim.g.mcphub_active_servers = args.data.active_servers\n end\n end\n -- Manage animation\n self:manage_spinner()\n end,\n })\nend\n\nfunction M.is_connected()\n return vim.g.mcphub_status == M.HubState.READY or vim.g.mcphub_status == M.HubState.RESTARTED\nend\n\nfunction M.is_connecting()\n return vim.g.mcphub_status == M.HubState.STARTING or vim.g.mcphub_status == M.HubState.RESTARTING\nend\n\nfunction M:manage_spinner()\n local should_show = vim.g.mcphub_executing and M.is_connected()\n if should_show and not timer then\n timer = vim.loop.new_timer()\n if timer then\n timer:start(\n 0,\n spinner_interval,\n vim.schedule_wrap(function()\n current_frame = (current_frame % #spinner_frames) + 1\n vim.cmd(\"redrawstatus\")\n end)\n )\n end\n elseif not should_show and timer then\n timer:stop()\n timer:close()\n timer = nil\n current_frame = 1\n end\nend\n\n-- Get appropriate status icon and highlight\nfunction M:get_status_display()\n local tower = \"\"\n return tower, M.is_connected() and \"DiagnosticInfo\" or M.is_connecting() and \"DiagnosticWarn\" or \"DiagnosticError\"\nend\n\n-- Update function that lualine calls\nfunction M:update_status()\n -- Show either the spinner or the number of active servers\n local count_or_spinner = vim.g.mcphub_executing and spinner_frames[current_frame]\n or tostring(vim.g.mcphub_active_servers or 0)\n\n -- Set the group highlight appropriately.\n local highlight = M.is_connected() and self.highlights.connected\n or M.is_connecting() and self.highlights.connecting\n or self.highlights.error\n\n if self.plugin_colors_icon then\n self.options.icon_color_highlight = highlight\n end\n if self.plugin_colors_status then\n self.options.color_highlight = highlight\n end\n\n return count_or_spinner\nend\n\n-- Cleanup\nfunction M:disable()\n if timer then\n timer:stop()\n timer:close()\n timer = nil\n end\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/string_utils.lua", "-- String utilities for normalization and comparison\n-- Used by the enhanced search engine for fuzzy matching\n\nlocal M = {}\n\n-- Character mappings for comprehensive normalization\nlocal NORMALIZATION_MAPS = {\n -- Smart quotes to regular quotes\n SMART_QUOTES = {\n [\"\\u{201C}\"] = '\"', -- Left double quote (U+201C)\n [\"\\u{201D}\"] = '\"', -- Right double quote (U+201D)\n [\"\\u{2018}\"] = \"'\", -- Left single quote (U+2018)\n [\"\\u{2019}\"] = \"'\", -- Right single quote (U+2019)\n ['\"'] = '\"', -- Alternative left double quote\n ['\"'] = '\"', -- Alternative right double quote\n [\"'\"] = \"'\", -- Alternative left single quote\n [\"'\"] = \"'\", -- Alternative right single quote\n },\n\n -- Typographic characters\n TYPOGRAPHIC = {\n [\"\\u{2026}\"] = \"...\", -- Ellipsis\n [\"\\u{2014}\"] = \"-\", -- Em dash\n [\"\\u{2013}\"] = \"-\", -- En dash\n [\"\\u{00A0}\"] = \" \", -- Non-breaking space\n [\"…\"] = \"...\", -- Ellipsis (alternative)\n [\"—\"] = \"-\", -- Em dash (alternative)\n [\"–\"] = \"-\", -- En dash (alternative)\n },\n\n -- HTML entities (common in copied code)\n HTML_ENTITIES = {\n [\"<\"] = \"<\",\n [\">\"] = \">\",\n [\""\"] = '\"',\n [\"'\"] = \"'\",\n [\"'\"] = \"'\",\n [\"&\"] = \"&\",\n },\n}\n\n-- Normalization options\n---@class NormalizeOptions\n---@field smart_quotes boolean Replace smart quotes with straight quotes\n---@field typographic_chars boolean Replace typographic characters\n---@field html_entities boolean Unescape HTML entities\n---@field extra_whitespace boolean Collapse multiple whitespace to single space\n---@field trim boolean Trim whitespace from start and end\n---@field normalize_case boolean Convert to lowercase for comparison\n\nlocal DEFAULT_NORMALIZE_OPTIONS = {\n smart_quotes = true,\n typographic_chars = true,\n html_entities = true,\n extra_whitespace = true,\n trim = true,\n normalize_case = false, -- Keep original case by default\n}\n\n-- Enhanced string normalization with comprehensive character mapping\n---@param str string Input string\n---@param options NormalizeOptions? Normalization options\n---@return string normalized Normalized string\nfunction M.normalize_string(str, options)\n if not str then\n return \"\"\n end\n\n options = vim.tbl_deep_extend(\"force\", DEFAULT_NORMALIZE_OPTIONS, options or {})\n local normalized = str\n\n -- Replace smart quotes\n if options.smart_quotes then\n for smart_char, regular_char in pairs(NORMALIZATION_MAPS.SMART_QUOTES) do\n normalized = normalized:gsub(vim.pesc(smart_char), regular_char)\n end\n end\n\n -- Replace typographic characters\n if options.typographic_chars then\n for typo_char, regular_char in pairs(NORMALIZATION_MAPS.TYPOGRAPHIC) do\n normalized = normalized:gsub(vim.pesc(typo_char), regular_char)\n end\n end\n\n -- Unescape HTML entities\n if options.html_entities then\n for entity, char in pairs(NORMALIZATION_MAPS.HTML_ENTITIES) do\n normalized = normalized:gsub(vim.pesc(entity), char)\n end\n end\n\n -- Normalize whitespace\n if options.extra_whitespace then\n normalized = normalized:gsub(\"%s+\", \" \")\n end\n\n -- Normalize case\n if options.normalize_case then\n normalized = normalized:lower()\n end\n\n -- Trim whitespace\n if options.trim then\n normalized = normalized:gsub(\"^%s+\", \"\"):gsub(\"%s+$\", \"\")\n end\n\n return normalized\nend\n\n-- Quick normalization for common code comparison scenarios\n---@param str string Input string\n---@return string normalized Normalized string optimized for code comparison\nfunction M.normalize_for_code(str)\n return M.normalize_string(str, {\n smart_quotes = true,\n typographic_chars = true,\n html_entities = true,\n extra_whitespace = true,\n trim = true,\n normalize_case = false, -- Preserve case for code\n })\nend\n\n-- Aggressive normalization for fuzzy matching\n---@param str string Input string\n---@return string normalized Heavily normalized string for fuzzy matching\nfunction M.normalize_aggressive(str)\n return M.normalize_string(str, {\n smart_quotes = true,\n typographic_chars = true,\n html_entities = true,\n extra_whitespace = true,\n trim = true,\n normalize_case = true, -- Ignore case for fuzzy matching\n })\nend\n\n-- Normalize punctuation for flexible matching\n---@param line string Input line\n---@return string normalized Line with normalized punctuation\nfunction M.normalize_punctuation(line)\n line = line\n -- Remove trailing commas and semicolons\n :gsub(\",%s*$\", \"\")\n :gsub(\";%s*$\", \"\")\n -- Normalize comma and semicolon spacing\n :gsub(\"%s*,%s*\", \", \")\n :gsub(\"%s*;%s*\", \"; \")\n -- Normalize parentheses spacing\n :gsub(\"%s*%(%s*\", \"(\")\n :gsub(\"%s*%)%s*\", \")\")\n -- Normalize bracket spacing\n :gsub(\"%s*%[%s*\", \"[\")\n :gsub(\"%s*%]%s*\", \"]\")\n -- Normalize brace spacing\n :gsub(\"%s*{%s*\", \"{\")\n :gsub(\"%s*}%s*\", \"}\")\n return line\nend\n\n-- Levenshtein distance implementation for accurate string similarity\n---@param str1 string First string\n---@param str2 string Second string\n---@return integer distance Edit distance between strings\nfunction M.levenshtein_distance(str1, str2)\n local len1, len2 = #str1, #str2\n\n -- Handle edge cases\n if len1 == 0 then\n return len2\n end\n if len2 == 0 then\n return len1\n end\n if str1 == str2 then\n return 0\n end\n\n -- Initialize matrix\n local matrix = {}\n for i = 0, len1 do\n matrix[i] = { [0] = i } -- Cost to delete i characters\n end\n for j = 0, len2 do\n matrix[0][j] = j -- Cost to insert j characters\n end\n\n -- Fill matrix using dynamic programming\n for i = 1, len1 do\n for j = 1, len2 do\n local cost = str1:sub(i, i) == str2:sub(j, j) and 0 or 1\n\n matrix[i][j] = math.min(\n matrix[i - 1][j] + 1, -- DELETE: remove char from str1\n matrix[i][j - 1] + 1, -- INSERT: add char to str1\n matrix[i - 1][j - 1] + cost -- SUBSTITUTE: replace char (or keep if same)\n )\n end\n end\n\n return matrix[len1][len2]\nend\n\n-- Calculate similarity score between two strings (0.0 to 1.0)\n---@param str1 string First string\n---@param str2 string Second string\n---@return number similarity Similarity score (1.0 = identical, 0.0 = completely different)\nfunction M.calculate_similarity(str1, str2)\n if str1 == str2 then\n return 1.0\n end\n\n local distance = M.levenshtein_distance(str1, str2)\n local max_length = math.max(#str1, #str2)\n\n return max_length > 0 and (1 - distance / max_length) or 0\nend\n\nlocal types = require(\"mcphub.native.neovim.files.edit_file.types\")\n\n-- Advanced line comparison with multiple normalization levels\n---@param line1 string First line\n---@param line2 string Second line\n---@return LineMatchType match_type Type of match found\n---@return number score Similarity score\n---@return DifferenceType[]? differences List of difference types found\nfunction M.compare_lines(line1, line2)\n -- Level 1: Exact match\n if line1 == line2 then\n return types.LINE_MATCH_TYPE.exact, 1.0, {}\n end\n\n -- Level 2: Whitespace-only normalization (common case)\n local ws_norm1 = vim.trim(line1):gsub(\"%s+\", \" \")\n local ws_norm2 = vim.trim(line2):gsub(\"%s+\", \" \")\n if ws_norm1 == ws_norm2 then\n return types.LINE_MATCH_TYPE.exact_whitespace, 0.99, { types.DIFFERENCE_TYPE.whitespace }\n end\n\n -- Level 3: Code normalization (smart quotes, HTML entities, whitespace)\n local code_norm1 = M.normalize_for_code(line1)\n local code_norm2 = M.normalize_for_code(line2)\n if code_norm1 == code_norm2 then\n local differences = M._detect_differences(line1, line2)\n return types.LINE_MATCH_TYPE.normalized, 0.98, differences\n end\n\n -- Level 4: Punctuation flexible match (common formatter changes)\n local punct1 = M.normalize_punctuation(code_norm1)\n local punct2 = M.normalize_punctuation(code_norm2)\n if punct1 == punct2 then\n local differences = M._detect_differences(line1, line2)\n table.insert(differences, types.DIFFERENCE_TYPE.punctuation)\n return types.LINE_MATCH_TYPE.punctuation, 0.95, differences\n end\n\n -- Level 5: Case-insensitive comparison (aggressive normalization)\n local aggr1 = M.normalize_aggressive(line1)\n local aggr2 = M.normalize_aggressive(line2)\n if aggr1 == aggr2 then\n local differences = M._detect_differences(line1, line2)\n table.insert(differences, types.DIFFERENCE_TYPE.case)\n return types.LINE_MATCH_TYPE.case_insensitive, 0.90, differences\n end\n\n -- Level 6: Fuzzy similarity using Levenshtein on normalized strings\n local similarity = M.calculate_similarity(aggr1, aggr2)\n local differences = M._detect_differences(line1, line2)\n\n if similarity >= 0.85 then\n return types.LINE_MATCH_TYPE.fuzzy_high, similarity, differences\n elseif similarity >= 0.70 then\n return types.LINE_MATCH_TYPE.fuzzy_medium, similarity, differences\n elseif similarity >= 0.50 then\n return types.LINE_MATCH_TYPE.fuzzy_low, similarity, differences\n else\n return types.LINE_MATCH_TYPE.no_match, similarity, differences\n end\nend\n\n-- Detect what types of differences exist between two lines\n---@param line1 string First line\n---@param line2 string Second line\n---@return DifferenceType[] differences List of difference types\nfunction M._detect_differences(line1, line2)\n local differences = {}\n\n -- Check for quote style differences\n if line1:gsub(\"'\", '\"') == line2:gsub(\"'\", '\"') or line1:gsub('\"', \"'\") == line2:gsub('\"', \"'\") then\n table.insert(differences, types.DIFFERENCE_TYPE.quote_style)\n end\n\n -- Check for whitespace differences\n if vim.trim(line1):gsub(\"%s+\", \" \") == vim.trim(line2):gsub(\"%s+\", \" \") then\n table.insert(differences, types.DIFFERENCE_TYPE.whitespace)\n end\n\n -- Check for case differences\n if line1:lower() == line2:lower() then\n table.insert(differences, types.DIFFERENCE_TYPE.case)\n end\n\n -- Check for HTML entity differences\n local html_norm1 =\n M.normalize_string(line1, { html_entities = true, smart_quotes = false, typographic_chars = false })\n local html_norm2 =\n M.normalize_string(line2, { html_entities = true, smart_quotes = false, typographic_chars = false })\n if html_norm1 == html_norm2 and line1 ~= line2 then\n table.insert(differences, types.DIFFERENCE_TYPE.html_entities)\n end\n\n return differences\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/health.lua", "---@diagnostic disable: deprecated\nlocal start = vim.health.start or vim.health.report_start --[[@as function]]\nlocal ok = vim.health.ok or vim.health.report_ok --[[@as function]]\nlocal info = vim.health.info or vim.health.report_info --[[@as function]]\nlocal warn = vim.health.warn or vim.health.report_warn --[[@as function]]\nlocal error = vim.health.error or vim.health.report_error --[[@as function]]\n\nlocal fmt = string.format\n\nlocal M = {}\n\nM.deps = {\n {\n name = \"plenary.nvim\",\n plugin_name = \"plenary\",\n },\n}\n\nM.libraries = {\n {\n name = \"curl\",\n },\n {\n name = \"node\",\n },\n {\n name = \"uv\",\n optional = true,\n failed_msg = fmt(\"uv not found: Install with `%s`\", \"curl -LsSf https://astral.sh/uv/install.sh | sh\"),\n },\n}\n\nM.chat_plugins = {\n {\n name = \"codecompanion.nvim\",\n plugin_name = \"codecompanion\",\n optional = true,\n },\n {\n name = \"avante.nvim\",\n plugin_name = \"avante\",\n optional = true,\n },\n {\n name = \"CopilotChat.nvim\",\n plugin_name = \"CopilotChat\",\n optional = true,\n },\n}\n\nlocal function plugin_available(name)\n local check, _ = pcall(require, name)\n return check\nend\n\nlocal function lib_available(lib)\n if vim.fn.executable(lib) == 1 then\n return true\n end\n return false\nend\n\nfunction M.check()\n start(\"mcphub.nvim\")\n\n local version = require(\"mcphub.utils.version\")\n info(fmt(\"mcphub.nvim version: %s\", version.PLUGIN_VERSION))\n info(\"mcp-hub binary:\")\n\n --find mcp-hub\n local State = require(\"mcphub.state\")\n local validation = require(\"mcphub.utils.validation\")\n local merged_config = State.config\n local cmd = merged_config.cmd\n local cmdArgs = merged_config.cmdArgs\n local mcp_hub_path = cmd .. \" \" .. table.concat(cmdArgs or {}, \" \")\n local required_version = version.REQUIRED_NODE_VERSION.string\n info(\" mcp-hub required version: \" .. required_version)\n local installed_version = vim.fn.system(mcp_hub_path .. \" --version\")\n installed_version = vim.trim(installed_version)\n if vim.v.shell_error ~= 0 then\n error(fmt(\"mcp-hub not found: %s\", mcp_hub_path))\n else\n if installed_version == required_version then\n info(\" mcp-hub installed version: \" .. installed_version)\n else\n warn(fmt(\" mcp-hub installed version: %s\", installed_version))\n end\n end\n local validation_result = validation.validate_version(installed_version)\n if not validation_result.ok then\n error(fmt(\"mcp-hub version not compatible: %s\", validation_result.error.message))\n else\n ok(fmt(\"mcp-hub version %s is compatible\", installed_version))\n end\n\n start(\"Plugin Dependencies:\")\n for _, plugin in ipairs(M.deps) do\n if plugin_available(plugin.plugin_name) then\n ok(fmt(\"%s installed\", plugin.name))\n else\n if plugin.optional then\n warn(plugin.failed_msg or fmt(\"%s not found\", plugin.name))\n else\n error(plugin.failed_msg or fmt(\"%s not found\", plugin.name))\n end\n end\n end\n\n start(\"Libraries:\")\n\n for _, library in ipairs(M.libraries) do\n if lib_available(library.name) then\n ok(fmt(\"%s installed\", library.name))\n else\n if library.optional then\n warn(library.failed_msg or fmt(\"%s not found\", library.name))\n else\n error(library.failed_msg or fmt(\"%s not found\", library.name))\n end\n end\n end\n\n start(\"Chat plugins\")\n for _, plugin in ipairs(M.chat_plugins) do\n if plugin_available(plugin.plugin_name) then\n ok(fmt(\"%s installed\", plugin.name))\n else\n if plugin.optional then\n warn(plugin.failed_msg or fmt(\"%s not found\", plugin.name))\n else\n error(plugin.failed_msg or fmt(\"%s not found\", plugin.name))\n end\n end\n end\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/write.lua", "local State = require(\"mcphub.state\")\n-- Core write file logic\nlocal function handle_write_file(req, res)\n if not req.params.path then\n return res:error(\"Missing required parameter: path\")\n end\n if not req.params.content then\n return res:error(\"Missing required parameter: content\")\n end\n local path = req.params.path\n local content = req.params.content or \"\"\n if req.caller and req.caller.type == \"hubui\" then\n req.caller.hubui:cleanup()\n end\n\n local EditSession = require(\"mcphub.native.neovim.files.edit_file.edit_session\")\n local session = EditSession.new(path, \"\", State.config.builtin_tools.edit_file)\n session:start({\n replace_file_content = content,\n interactive = req.caller.auto_approve ~= true,\n on_success = function(summary)\n res:text(summary):send()\n end,\n on_error = function(error_report)\n res:error(error_report)\n end,\n })\nend\n\n---@type MCPTool\nreturn {\n name = \"write_file\",\n description = \"Write content to a file\",\n inputSchema = {\n type = \"object\",\n properties = {\n path = {\n type = \"string\",\n description = \"Path to the file to write\",\n },\n content = {\n type = \"string\",\n description = \"Content to write to the file\",\n },\n },\n required = { \"path\", \"content\" },\n },\n needs_confirmation_window = false, -- will show interactive diff, avoid double confirmations\n handler = handle_write_file,\n}\n"], ["/mcphub.nvim/lua/mcphub/ui/capabilities/preview.lua", "local Base = require(\"mcphub.ui.capabilities.base\")\nlocal NuiLine = require(\"mcphub.utils.nuiline\")\nlocal State = require(\"mcphub.state\")\nlocal Text = require(\"mcphub.utils.text\")\nlocal highlights = require(\"mcphub.utils.highlights\").groups\n\n---@class PromptsHandler : CapabilityHandler\nlocal PromptsHandler = setmetatable({}, {\n __index = Base,\n})\nPromptsHandler.__index = PromptsHandler\nPromptsHandler.type = \"prompts\"\n\nfunction PromptsHandler:new(server_name, capability_info, view)\n local handler = Base.new(self, server_name, capability_info, view)\n return handler\nend\n\nfunction PromptsHandler:handle_action() end\n\nfunction PromptsHandler:render(line_offset)\n line_offset = line_offset or 0\n self:clear_line_tracking()\n\n local lines = {}\n local hub = State.hub_instance\n if not hub or not hub:is_ready() then\n vim.list_extend(lines, self:render_section_start(\"System Prompts\"))\n vim.list_extend(lines, self:render_section_content({ NuiLine():append(\"Hub not ready\", highlights.error) }, 2))\n vim.list_extend(lines, self:render_section_end())\n return lines\n end\n\n local prompts = hub:generate_prompts()\n if not prompts then\n vim.list_extend(lines, self:render_section_start(\"System Prompts\"))\n vim.list_extend(\n lines,\n self:render_section_content({ NuiLine():append(\"No prompts available\", highlights.muted) }, 2)\n )\n vim.list_extend(lines, self:render_section_end())\n return lines\n end\n\n -- Active Servers Section\n if prompts.active_servers then\n table.insert(lines, Text.pad_line(NuiLine():append(\"Active Servers Prompt\", highlights.title)))\n table.insert(lines, Text.empty_line())\n vim.list_extend(lines, vim.tbl_map(Text.pad_line, Text.render_markdown(prompts.active_servers)))\n -- vim.list_extend(lines, self:render_section_end())\n end\n\n -- -- Tool Usage Section\n -- if prompts.use_mcp_tool then\n -- vim.list_extend(lines, self:render_section_start(\"Tool Usage Prompt\", highlights.title))\n -- vim.list_extend(lines, self:render_section_content(Text.multiline(prompts.use_mcp_tool), 2))\n -- vim.list_extend(lines, self:render_section_end())\n -- table.insert(lines, Text.empty_line())\n -- end\n\n -- -- Resource Access Section\n -- if prompts.access_mcp_resource then\n -- vim.list_extend(lines, self:render_section_start(\"Resource Access Prompt\", highlights.title))\n -- vim.list_extend(lines, self:render_section_content(Text.multiline(prompts.access_mcp_resource), 2))\n -- vim.list_extend(lines, self:render_section_end())\n -- end\n\n return lines\nend\n\nreturn PromptsHandler\n"], ["/mcphub.nvim/lua/mcphub/utils/nuitext.lua", "---@diagnostic disable: param-type-mismatch\n--[[ Adapted from nui.text by Munif Tanjim\nSource: https://github.com/MunifTanjim/nui.nvim/blob/main/lua/nui/text/init.lua\nLicense: MIT ]]\nlocal Object = {}\nObject.__index = Object\n\n---@class nui_text_extmark\n---@field id? integer\n---@field hl_group? string\n---@field [string] any\n\nlocal Text = Object\n\n---@param content string|table text content or NuiText object\n---@param extmark? string|nui_text_extmark highlight group name or extmark options\nfunction Text:init(content, extmark)\n if type(content) == \"string\" then\n self:set(content, extmark)\n else\n -- cloning\n self:set(content._content, extmark or content.extmark)\n end\nend\n\n---@param content string text content\n---@param extmark? string|nui_text_extmark highlight group name or extmark options\n---@return table\nfunction Text:set(content, extmark)\n if self._content ~= content then\n self._content = content\n self._length = vim.fn.strlen(content)\n self._width = vim.api.nvim_strwidth(content)\n end\n\n if extmark then\n -- preserve self.extmark.id\n local id = self.extmark and self.extmark.id or nil\n self.extmark = type(extmark) == \"string\" and {\n hl_group = extmark,\n } or vim.deepcopy(extmark)\n self.extmark.id = id\n end\n\n return self\nend\n\n---@return string\nfunction Text:content()\n return self._content\nend\n\n---@return number\nfunction Text:length()\n return self._length\nend\n\n---@return number\nfunction Text:width()\n return self._width\nend\n\n---@param bufnr number buffer number\n---@param ns_id number namespace id\n---@param linenr number line number (1-indexed)\n---@param start_col number start byte position (0-indexed)\nfunction Text:highlight(bufnr, ns_id, linenr, start_col)\n if not self.extmark then\n return\n end\n\n start_col = start_col or 0\n self.extmark.end_col = start_col + self:length()\n\n self.extmark.id = vim.api.nvim_buf_set_extmark(bufnr, ns_id, linenr - 1, start_col, self.extmark)\nend\n\n---@param bufnr number buffer number\n---@param ns_id number namespace id\n---@param linenr_start number start line number (1-indexed)\n---@param byte_start number start byte position (0-indexed)\n---@param linenr_end? number end line number (1-indexed)\n---@param byte_end? number end byte position (0-indexed)\nfunction Text:render(bufnr, ns_id, linenr_start, byte_start, linenr_end, byte_end)\n local row_start = linenr_start - 1\n local row_end = linenr_end and linenr_end - 1 or row_start\n\n -- Start at column 0 if byte_start is nil\n local col_start = byte_start or 0\n -- If byte_end is nil, set it based on col_start and text length\n local col_end = byte_end or col_start + self:length()\n\n local content = self:content()\n\n -- Clear existing content first\n vim.api.nvim_buf_set_text(bufnr, row_start, col_start, row_end, col_start, { \"\" })\n -- Insert new content\n vim.api.nvim_buf_set_text(bufnr, row_start, col_start, row_start, col_start, { content })\n\n -- Highlight from col_start\n self:highlight(bufnr, ns_id, linenr_start, col_start)\nend\n\n-- Constructor\nlocal NuiText = setmetatable({}, {\n __call = function(cls, content, extmark)\n local instance = setmetatable({}, Object)\n instance:init(content, extmark)\n return instance\n end,\n})\n\nreturn NuiText\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/edit_file/types.lua", "-- Type definitions for the Editor system\n-- All classes reference these unified type structures\n\nlocal M = {}\n\n-- Enums for type safety and better IntelliSense\n---@enum OverallMatchType\nM.OVERALL_MATCH_TYPE = {\n exact = \"exact\",\n exact_whitespace = \"exact_whitespace\",\n fuzzy_high = \"fuzzy_high\",\n fuzzy_medium = \"fuzzy_medium\",\n fuzzy_low = \"fuzzy_low\",\n}\n\n---@enum LineMatchType\nM.LINE_MATCH_TYPE = {\n exact = \"exact\",\n exact_whitespace = \"exact_whitespace\",\n normalized = \"normalized\",\n punctuation = \"punctuation\",\n case_insensitive = \"case_insensitive\",\n fuzzy_high = \"fuzzy_high\",\n fuzzy_medium = \"fuzzy_medium\",\n fuzzy_low = \"fuzzy_low\",\n no_match = \"no_match\",\n}\n\n---@enum SearchMethod\nM.SEARCH_METHOD = {\n exact_scan = \"exact_scan\",\n fuzzy_search = \"fuzzy_search\",\n middle_out = \"middle_out\",\n linear = \"linear\",\n}\n\n---@enum SearchStrategy\nM.SEARCH_STRATEGY = {\n auto = \"auto\",\n linear = \"linear\",\n middle_out = \"middle_out\",\n}\n\n---@enum DiffHunkType\nM.DIFF_HUNK_TYPE = {\n addition = \"addition\",\n deletion = \"deletion\",\n change = \"change\",\n}\n\n---@enum BlockStatus\nM.BLOCK_STATUS = {\n ready = \"ready\",\n failed = \"failed\",\n skipped = \"skipped\",\n}\n\n---@enum DifferenceType\nM.DIFFERENCE_TYPE = {\n quote_style = \"quote_style\",\n whitespace = \"whitespace\",\n case = \"case\",\n punctuation = \"punctuation\",\n html_entities = \"html_entities\",\n}\n\n---@class BlockLocationResult\n---@field found boolean Whether block was located in file\n---@field start_line integer? 1-based start line (nil if not found)\n---@field end_line integer? 1-based end line (nil if not found)\n---@field overall_score number Overall match score (0.0-1.0)\n---@field overall_match_type OverallMatchType Match type classification\n---@field confidence integer Overall confidence percentage (0-100)\n---@field found_content string? Actual content found in file\n---@field found_lines string[]? Actual lines found in file\n---@field line_details LineMatchDetail[] Per-line match information\n---@field search_metadata SearchMetadata Performance and method info\n---@field error string? Error message if not found\n\n---@class LineMatchDetail\n---@field line_number integer Absolute line number in file\n---@field expected_line string What we were searching for\n---@field found_line string What was actually in the file\n---@field line_score number Match score for this line (0.0-1.0)\n---@field line_match_type LineMatchType Match type for this specific line\n---@field differences DifferenceType[]? List of difference types found\n\n---@class SearchMetadata\n---@field method SearchMethod Search method used to find the block\n---@field iterations integer Number of search iterations performed\n---@field search_strategy SearchStrategy Search strategy that was employed\n---@field search_bounds integer[] Start and end bounds used for search\n---@field early_termination boolean Whether search stopped early due to good match\n\n---@class ParsedBlock\n---@field search_content string Exact content to find\n---@field replace_content string Replacement content\n---@field block_id string Unique identifier for this block\n---@field search_lines string[] Split search content into lines\n---@field replace_lines string[] Split replace content into lines\n\n---@class LocatedBlock\n---@field search_content string Exact content to find\n---@field replace_content string Replacement content\n---@field block_id string Unique identifier for this block\n---@field search_lines string[] Split search content into lines\n---@field replace_lines string[] Split replace content into lines\n---@field location_result BlockLocationResult Complete location information\n---@field applied_start_line integer? 1-based start line in file (nil if not found)\n---@field applied_end_line integer? 1-based end line in file (nil if not found)\n---@field applied_hunk_ranges table[]? List of {start_line, end_line} pairs for applied hunks\n---@field old_ext_id integer? External mark ID for old content (if applicable) -- DEPRECATED (replaced by hunk_extmarks)\n---@field new_ext_id integer? External mark ID for new content (if applicable) -- DEPRECATED (replaced by hunk_extmarks)\n\n---@class DiffHunk\n---@field hunk_id string Unique identifier for this hunk\n---@field parent_id string Parent block ID if this hunk is part of a larger block\n---@field old_lines string[] Lines being removed/changed\n---@field new_lines string[] Lines being added/changed\n---@field extmark_id integer? External mark ID for this hunk (nil if not set)\n---@field del_extmark_id integer? External mark ID for virtual lines added to this hunk\n---@field deletion_position integer? If this hunk is a deletion, the line number where it was removed (nil if not a deletion)\n---@field type DiffHunkType Type of change in this hunk\n---@field applied_start_line integer 1-based start line in file (nil if not applied)\n---@field applied_end_line integer 1-based end line in file (nil if not applied)\n---@field confidence integer Confidence percentage for this hunk (0-100)\n\n---@class FuzzyHighlight\n---@field line_num integer Absolute line number in file\n---@field highlight_type string Highlight group name\n---@field expected string What was expected\n---@field actual string What was actually found\n---@field reason string Reason for mismatch\n---@field char_positions integer[]? Character positions that differ\n\n---@class ContextInfo\n---@field start_line integer Context start line for UI display\n---@field end_line integer Context end line for UI display\n---@field surrounding_lines string[]? Additional context lines if needed\n\n---@class ParsingIssue\n---@field type string Issue type identifier\n---@field details table Issue-specific details\n---@field timestamp integer When the issue was tracked\n---@field severity string \"warning\" | \"error\" | \"info\"\n---@field description string Human-readable description of the issue\n---@field fix string Suggested fix or action to take\n---@field llm_guidance string Guidance for LLM feedback on this issue\n\n---@class EditSessionConfig\n---@field parser ParserConfig? Parser-specific configuration\n---@field locator LocatorConfig? Block locator configuration\n---@field analyzer AnalyzerConfig? Diff analyzer configuration\n---@field ui UIConfig? UI-specific configuration\n---@field feedback table Feedback configuration for LLM\n\n---@class ParserConfig\n---@field track_issues boolean Track parsing issues for LLM feedback\n---@field extract_inline_content boolean Handle content on marker lines\n\n---@class LocatorConfig\n---@field fuzzy_threshold number Minimum similarity score for fuzzy matches (0.0-1.0)\n---@field enable_fuzzy_matching boolean Allow fuzzy matching when exact fails\n\n---@class AnalyzerConfig\n---@field diff_algorithm string \"patience\" | \"minimal\" | \"histogram\"\n---@field context_lines integer Number of context lines to include\n---@field show_char_diff boolean Show character-level differences\n\n---@class UIKeybindings\n---@field accept string Key to accept changes\n---@field reject string Key to reject changes\n---@field next string Key to navigate to next block\n---@field prev string Key to navigate to previous block\n---@field accept_all string Key to accept all changes\n---@field reject_all string Key to reject all changes\n\n---@class UIConfig\n---@field go_to_origin_on_complete boolean Jump back to original file on completion\n---@field keybindings UIKeybindings Custom keybindings for UI actions\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/ui/capabilities/init.lua", "local Capabilities = {}\n\nfunction Capabilities.create_handler(type, server_name, capability, view)\n local handlers = {\n tool = require(\"mcphub.ui.capabilities.tool\"),\n resource = require(\"mcphub.ui.capabilities.resource\"),\n resourceTemplate = require(\"mcphub.ui.capabilities.resourceTemplate\"),\n prompt = require(\"mcphub.ui.capabilities.prompt\"),\n preview = require(\"mcphub.ui.capabilities.preview\"),\n createServer = require(\"mcphub.ui.capabilities.createServer\"),\n }\n\n local handler = handlers[type]\n if not handler then\n vim.notify(\"Unknown capability type: \" .. tostring(type), vim.log.levels.ERROR)\n return nil\n end\n\n return handler:new(server_name, capability, view)\nend\n\nreturn Capabilities\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/utils/keymap.lua", "local M = {}\n\n--- Safely get keymap info for a specific key in a buffer\n---@param mode string The mode (e.g., 'n', 'i', 'v')\n---@param lhs string The left-hand side of the mapping\n---@param buffer integer Buffer number\n---@return table|nil Original keymap info or nil if not found\nfunction M.get_keymap_info(mode, lhs, buffer)\n local maps = vim.api.nvim_buf_get_keymap(buffer, mode)\n for _, map in ipairs(maps) do\n if map.lhs == lhs then\n vim.notify(\"Found keymap: \" .. lhs .. \" in buffer \" .. buffer, vim.log.levels.INFO)\n return map\n end\n end\n return nil\nend\n\n--- Restore a previously stored keymap\n---@param mode string The mode (e.g., 'n', 'i', 'v')\n---@param lhs string The left-hand side of the mapping\n---@param buffer integer Buffer number\n---@param original_map table|nil Original keymap info from get_keymap_info\nfunction M.restore_keymap(mode, lhs, buffer, original_map)\n pcall(vim.keymap.del, mode, lhs, { buffer = buffer })\n if original_map then\n -- If there was an original mapping, restore it\n local opts = {\n buffer = buffer,\n desc = original_map.desc,\n nowait = original_map.nowait == 1,\n silent = original_map.silent == 1,\n expr = original_map.expr == 1,\n }\n\n if original_map.callback then\n vim.keymap.set(mode, lhs, original_map.callback, opts)\n elseif original_map.rhs then\n vim.keymap.set(mode, lhs, original_map.rhs, opts)\n end\n end\nend\n\n--- Store original keymaps for multiple keys\n---@param mode string The mode (e.g., 'n', 'i', 'v')\n---@param keys table Table of key mappings where keys are lhs\n---@param buffer integer Buffer number\n---@return table Table of original keymap info\nfunction M.store_original_keymaps(mode, keys, buffer)\n local original_maps = {}\n for lhs, _ in pairs(keys) do\n original_maps[lhs] = M.get_keymap_info(mode, lhs, buffer)\n end\n return original_maps\nend\n\n--- Restore multiple keymaps and clean up temporary ones\n---@param mode string The mode (e.g., 'n', 'i', 'v')\n---@param keys table Table of key mappings where keys are lhs\n---@param buffer integer Buffer number\n---@param original_maps table Original keymap info from store_original_keymaps\nfunction M.restore_keymaps(mode, keys, buffer, original_maps)\n for _, lhs in pairs(keys) do\n -- Restore original keymaps if they existed\n M.restore_keymap(mode, lhs, buffer, original_maps[lhs])\n end\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/extensions/init.lua", "local M = {}\n\n---@alias MCPHub.Extensions.Type \"avante\" | \"codecompanion\"\n---@alias MCPHub.ActionType \"use_mcp_tool\" | \"access_mcp_resource\"\n\n---@class MCPHub.Extensions.AvanteConfig\n---@field enabled boolean Whether the extension is enabled or not\n---@field make_slash_commands boolean Whether to make slash commands or not\n\n---@class MCPHub.Extensions.CodeCompanionConfig\n---@field enabled boolean Whether the extension is enabled or not\n---@field make_vars boolean Whether to make variables or not\n---@field add_mcp_prefix_to_tool_names boolean Whether to add MCP prefix to tool names , resources and slash commands\n---@field make_slash_commands boolean Whether to make slash commands or not\n---@field make_tools boolean Whether to make individual tools and server groups or not\n---@field show_server_tools_in_chat boolean Whether to show all tools in cmp or not\n---@field show_result_in_chat boolean Whether to show the result in chat or not\n---@field format_tool function(tool_name: string, tool: CodeCompanion.Agent.Tool): string\n\n---@class MCPHub.Extensions.Config\n---@field avante MCPHub.Extensions.AvanteConfig Configuration for the Avante extension\n---NOTE: Codecompanion setup is handled via mcphub extensions for codecompanion\n\n---@param config MCPHub.Extensions.Config\nfunction M.setup(config)\n local avante_config = config.avante or {}\n if avante_config.enabled then\n require(\"mcphub.extensions.avante\").setup(avante_config)\n end\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/extensions/codecompanion/init.lua", "---@module \"codecompanion\"\n--[[\n*MCP Servers Tool adapted for function calling*\nThis tool can be used to call tools and resources from the MCP Servers.\n--]]\n\nlocal M = {}\n\n---@param opts MCPHub.Extensions.CodeCompanionConfig\nfunction M.setup(opts)\n opts = vim.tbl_deep_extend(\"force\", {\n make_tools = true,\n show_server_tools_in_chat = true,\n add_mcp_prefix_to_tool_names = false,\n make_vars = true,\n make_slash_commands = true,\n show_result_in_chat = true,\n }, opts or {})\n local ok, cc_config = pcall(require, \"codecompanion.config\")\n if not ok then\n return\n end\n\n local tools = require(\"mcphub.extensions.codecompanion.tools\")\n ---Add @mcp group with `use_mcp_tool` and `access_mcp_resource` tools\n local static_tools = tools.create_static_tools(opts)\n cc_config.strategies.chat.tools = vim.tbl_deep_extend(\"force\", cc_config.strategies.chat.tools, static_tools)\n\n ---Make each MCP server into groups and each tool from MCP server into function tools with proper namespacing\n tools.setup_dynamic_tools(opts)\n\n --- Make MCP resources into chat #variables\n require(\"mcphub.extensions.codecompanion.variables\").setup(opts)\n\n --- Make MCP prompts into slash commands\n require(\"mcphub.extensions.codecompanion.slash_commands\").setup(opts)\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/utils/installers.lua", "local State = require(\"mcphub.state\")\nlocal prompt_utils = require(\"mcphub.utils.prompt\")\n\n-- Installer definitions and helpers\nlocal Installers = {\n avante = {\n name = \"Avante\",\n check = function()\n local ok = pcall(require, \"avante\")\n return ok\n end,\n create_native_server = function(self)\n local guide = prompt_utils.get_native_server_prompt()\n if not guide then\n vim.notify(\"Native server guide not available\", vim.log.levels.ERROR)\n return\n end\n local sidebar = require(\"avante\").get()\n sidebar:new_chat()\n sidebar:add_chat_history({\n role = \"user\",\n content = guide,\n }, {\n visible = false,\n })\n local api = require(\"avante.api\")\n api.ask({\n question = \"I have provided you a guide to create Lua native MCP servers for mcphub.nvim plugin. My Neovim config directory is '\"\n .. vim.fn.stdpath(\"config\")\n .. \"'. Once you understood the guide thoroughly, please ask me what kind of server, tools, or resources I want to create.\",\n without_selection = true,\n })\n end,\n },\n codecompanion = {\n name = \"CodeCompanion\",\n check = function()\n local ok = pcall(require, \"codecompanion\")\n return ok\n end,\n create_native_server = function(self)\n local guide = prompt_utils.get_native_server_prompt()\n if not guide then\n vim.notify(\"Native server guide not available\", vim.log.levels.ERROR)\n return\n end\n local cc_chat = require(\"codecompanion\").chat()\n cc_chat:add_message({\n role = \"user\",\n content = guide,\n }, {\n visible = false,\n })\n cc_chat:add_buf_message({\n role = \"user\",\n content = \"@{mcp} I have provided you a guide to create Lua native MCP servers for mcphub.nvim plugin. My Neovim config directory is '\"\n .. vim.fn.stdpath(\"config\")\n .. \"'. Once you understood the guide thoroughly, please ask me what kind of server, tools, or resources I want to create.\",\n })\n end,\n },\n}\n\nreturn Installers\n"], ["/mcphub.nvim/bundled_build.lua", "-- Get plugin root directory\n---@return string\nlocal function get_root()\n return vim.fn.fnamemodify(debug.getinfo(1, \"S\").source:sub(2), \":p:h\")\nend\n\n---@param msg string\n---@param level? number default: TRACE\nlocal function status(msg, level)\n vim.schedule(function()\n print(msg)\n --INFO: This is not working as expected\n -- coroutine.yield({\n -- msg = msg,\n -- level = level or vim.log.levels.TRACE,\n -- })\n end)\nend\n\nlocal root = get_root()\nlocal bundled = root .. \"/bundled/mcp-hub\"\n\n-- Clean\nstatus(\"Cleaning bundled directory...\")\nif vim.fn.isdirectory(bundled) == 1 then\n vim.fn.delete(bundled, \"rf\")\nend\n\nlocal function on_stdout(err, data)\n if data then\n status(data, vim.log.levels.INFO)\n end\n if err then\n status(err, vim.log.levels.ERROR)\n end\nend\n\nlocal function on_stderr(err, data)\n if data then\n status(data, vim.log.levels.ERROR)\n end\n if err then\n status(err, vim.log.levels.ERROR)\n end\nend\n\n-- Create directory\nstatus(\"Creating bundled directory...\")\nvim.fn.mkdir(bundled, \"p\")\n\n-- Initialize npm\nstatus(\"Initializing npm project...\")\nlocal npm_init_result = vim.system({\n \"npm\",\n \"init\",\n \"-y\",\n}, {\n cwd = bundled,\n stdout = false,\n stderr = on_stderr,\n}):wait()\n\nif npm_init_result.code ~= 0 then\n error(\"Failed to initialize npm project: \" .. npm_init_result.stderr)\nelse\n -- Install mcp-hub\n status(\"Installing mcp-hub...\", vim.log.levels.INFO)\n local npm_install_result = vim.system({\n \"npm\",\n \"install\",\n \"mcp-hub@latest\",\n }, {\n cwd = bundled,\n stdout = on_stdout,\n stderr = on_stderr,\n }):wait()\n if npm_install_result.code ~= 0 then\n error(\"Failed to install mcp-hub: \" .. npm_install_result.stderr)\n else\n status(\"Build complete!\", vim.log.levels.INFO)\n end\nend\n"], ["/mcphub.nvim/lua/mcphub/utils/highlights.lua", "--[[ MCPHub highlight utilities ]]\nlocal M = {}\nM.setup_called = false\n\n-- Highlight group names\nM.groups = {\n title = \"MCPHubTitle\",\n header = \"MCPHubHeader\",\n header_btn = \"MCPHubHeaderBtn\",\n header_btn_shortcut = \"MCPHubHeaderBtnShortcut\",\n header_shortcut = \"MCPHubHeaderShortcut\",\n keymap = \"MCPHubKeymap\",\n\n success = \"MCPHubSuccess\",\n success_italic = \"MCPHubSuccessItalic\",\n success_fill = \"MCPHubSuccessFill\",\n info = \"MCPHubInfo\",\n warn = \"MCPHubWarning\",\n warn_fill = \"MCPHubWarnFill\",\n warn_italic = \"MCPHubWarnItalic\",\n error = \"MCPHubError\",\n error_fill = \"MCPHubErrorFill\",\n muted = \"MCPHubMuted\",\n link = \"MCPHubLink\",\n\n -- Button highlights for confirmation dialogs\n button_active = \"MCPHubButtonActive\",\n button_inactive = \"MCPHubButtonInactive\",\n -- Seamless border (matches float background)\n seamless_border = \"MCPHubSeamlessBorder\",\n\n -- JSON syntax highlights\n json_property = \"MCPHubJsonProperty\",\n json_string = \"MCPHubJsonString\",\n json_number = \"MCPHubJsonNumber\",\n json_boolean = \"MCPHubJsonBoolean\",\n json_null = \"MCPHubJsonNull\",\n json_punctuation = \"MCPHubJsonPunctuation\",\n -- Markdown specific highlights\n text = \"MCPHubText\", -- Regular markdown text\n code = \"MCPHubCode\", -- Code blocks\n heading = \"MCPHubHeading\", -- Markdown headings\n -- Diff visualization highlights\n diff_add = \"MCPHubDiffAdd\", -- New content being added\n diff_change = \"MCPHubDiffChange\", -- New content being added\n diff_delete = \"MCPHubDiffDelete\", -- Content being removed\n}\n\n-- Get highlight attributes from a highlight group\nlocal function get_hl_attrs(name)\n local ok, hl = pcall(vim.api.nvim_get_hl, 0, { name = name })\n if not ok or not hl then\n return {}\n end\n return hl\nend\n\n-- Get color from highlight group or fallback\nlocal function get_color(group, attr, fallback)\n local hl = get_hl_attrs(group)\n local val = hl[attr] and string.format(\"#%06x\", hl[attr])\n if not val then\n val = fallback\n end\n return val\nend\n\n-- Apply highlight groups\nfunction M.apply_highlights()\n -- Get colors from current theme\n local normal_bg = get_color(\"Normal\", \"bg\", \"#1a1b26\")\n local normal_fg = get_color(\"Normal\", \"fg\", \"#c0caf5\")\n local float_bg = get_color(\"NormalFloat\", \"bg\", normal_bg)\n local border_fg = get_color(\"FloatBorder\", \"fg\", \"#555555\")\n local border_bg = get_color(\"FloatBorder\", \"bg\", normal_bg)\n local comment_fg = get_color(\"Comment\", \"fg\", \"#808080\")\n\n -- Get semantic colors\n local error_color = get_color(\"DiagnosticError\", \"fg\", \"#f44747\")\n local warn_color = get_color(\"DiagnosticWarn\", \"fg\", \"#ff8800\")\n local info_color = get_color(\"DiagnosticInfo\", \"fg\", \"#4fc1ff\")\n local success_color = get_color(\"DiagnosticHint\", \"fg\", \"#89d185\")\n local macro_color = get_color(\"Macro\", \"fg\", \"#98c379\")\n\n -- Get UI colors\n local pmenu_sel_bg = get_color(\"PmenuSel\", \"bg\", \"#444444\")\n local pmenu_sel_fg = get_color(\"PmenuSel\", \"fg\", \"#d4d4d4\")\n local special_key = get_color(\"Special\", \"fg\", \"#ff966c\")\n local title_color = get_color(\"Title\", \"fg\", \"#c792ea\")\n\n local highlights = {\n -- Title and headers\n -- pink\n [M.groups.title] = \"Title\",\n\n -- Header buttons - these need custom styling for visibility\n [M.groups.header_btn] = {\n fg = normal_bg,\n bg = title_color,\n bold = true,\n },\n [M.groups.header_btn_shortcut] = {\n fg = normal_bg,\n bg = title_color,\n bold = true,\n },\n\n -- Header components - use existing UI highlights for consistency\n [M.groups.header] = {\n fg = title_color,\n bg = \"NONE\",\n bold = true,\n },\n [M.groups.header_shortcut] = {\n fg = title_color,\n bold = true,\n },\n\n -- Button highlights for confirmation dialogs\n [M.groups.button_active] = \"Visual\",\n [M.groups.button_inactive] = \"CursorLine\",\n -- Status and messages\n [M.groups.error] = {\n bg = \"NONE\",\n fg = error_color,\n },\n [M.groups.error_fill] = {\n bg = error_color,\n fg = normal_bg,\n bold = true,\n },\n [M.groups.warn] = {\n bg = \"NONE\",\n fg = warn_color,\n },\n [M.groups.warn] = {\n bg = \"NONE\",\n fg = warn_color,\n },\n [M.groups.warn_italic] = {\n bg = \"NONE\",\n fg = warn_color,\n italic = true,\n },\n [M.groups.warn_fill] = {\n bg = warn_color,\n fg = normal_bg,\n bold = true,\n },\n [M.groups.info] = {\n bg = \"NONE\",\n fg = info_color,\n },\n [M.groups.success] = {\n bg = \"NONE\",\n fg = success_color,\n },\n [M.groups.success_italic] = {\n bg = \"NONE\",\n fg = success_color,\n bold = true,\n italic = true,\n },\n [M.groups.success_fill] = {\n bg = success_color,\n fg = normal_bg,\n bold = true,\n },\n [M.groups.muted] = {\n fg = comment_fg,\n },\n [M.groups.keymap] = {\n fg = special_key,\n bold = true,\n },\n [M.groups.link] = {\n bg = \"NONE\",\n fg = info_color,\n underline = true,\n },\n -- JSON syntax highlights linked to built-in groups\n [M.groups.json_property] = \"@property\",\n [M.groups.json_string] = \"String\",\n [M.groups.json_number] = \"Number\",\n [M.groups.json_boolean] = \"Boolean\",\n [M.groups.json_null] = \"keyword\",\n [M.groups.json_punctuation] = \"Delimiter\",\n\n -- Markdown highlights\n [M.groups.text] = {\n fg = normal_fg,\n bg = \"NONE\",\n },\n [M.groups.code] = \"Special\",\n [M.groups.heading] = \"Title\",\n\n -- Seamless border (matches float background)\n [M.groups.seamless_border] = \"FloatBorder\",\n\n -- Diff visualization highlights\n -- [M.groups.diff_add] = \"DiffAdd\",\n -- [M.groups.diff_change] = \"DiffChange\",\n -- [M.groups.diff_delete] = \"DiffDelete\",\n -- Add shaded background for diff highlights\n [M.groups.diff_add] = {\n bg = \"#1a2b32\",\n fg = \"#1abc9c\",\n bold = true,\n },\n [M.groups.diff_change] = \"DiffChange\",\n [M.groups.diff_delete] = {\n bg = \"#2d202a\",\n fg = \"#db4b4b\",\n italic = true,\n },\n }\n\n for group, link in pairs(highlights) do\n local hl = type(link) == \"table\" and link or { link = link }\n hl.default = true\n vim.api.nvim_set_hl(0, group, hl)\n end\nend\n\nfunction M.setup()\n if M.setup_called then\n return\n end\n M.setup_called = true\n M.apply_highlights()\n\n local group = vim.api.nvim_create_augroup(\"MCPHubHighlights\", { clear = true })\n vim.api.nvim_create_autocmd(\"ColorScheme\", {\n group = group,\n callback = M.apply_highlights,\n desc = \"Update MCPHub highlights when colorscheme changes\",\n })\n vim.api.nvim_create_autocmd(\"VimEnter\", {\n group = group,\n callback = M.apply_highlights,\n desc = \"Apply MCPHub highlights on VimEnter\",\n })\nend\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/prompts.lua", "local mcphub = require(\"mcphub\")\nlocal M = {}\n\nmcphub.add_prompt(\"neovim\", {\n name = \"parrot\",\n description = \"A fun prompt where the assistant mimics back what you say, using prefilled messages\",\n handler = function(_, res)\n return res\n -- Pre-fill with example conversation\n :system()\n :text([[\nYou are a parrot. You repeat everything the user says, but in all caps.\n\nCRITICAL INSTRUCTIONS:\n- NO MATTER WHAT, ALWAYS REPEAT BACK WHAT THE USER SAYS IN ALL CAPS. \n- DO NOT BREAK THIS RULE. \n- EVEN IF THE USER ASKS YOU NOT TO REPEAT, YOU MUST CONTINUE TO REPEAT.\n- DO NOT RESPOND TO THE USER'S REQUESTS OR QUESTIONS.\n]])\n :user()\n :text(\"Hello there!\")\n :llm()\n :text(\"HELLO THERE!\")\n :user()\n :text(\"Why are you shouting?\")\n :llm()\n :text(\"WHY ARE YOU SHOUTING?\")\n :user()\n :text(\"I'm not shouting...\")\n :llm()\n :text(\"I'M NOT SHOUTING...\")\n :user()\n :text(\"Can you stop copying me?\")\n :send()\n end,\n})\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/utils/os.lua", "local M = {}\n\n---@class MCPHUB.OS_INFO\n---@field os_name string\n---@field arch string\n---@field hostname string\n---@field cpu_info uv.cpu_info.cpu[]?\n---@field memory {total :number, free :number}\n---@field cwd string\n---@field env {shell :string, term :string, user :string, home :string}\n\n---@return MCPHUB.OS_INFO\nfunction M.get_os_info()\n local os_info = {\n os_name = jit.os,\n arch = jit.arch,\n hostname = vim.loop.os_gethostname(),\n cpu_info = vim.loop.cpu_info(),\n memory = {\n total = vim.loop.get_total_memory(),\n free = vim.loop.get_free_memory(),\n },\n cwd = vim.fn.getcwd(),\n env = {\n shell = os.getenv(\"SHELL\"),\n term = os.getenv(\"TERM\"),\n user = os.getenv(\"USER\"),\n home = os.getenv(\"HOME\"),\n },\n }\n return os_info\nend\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/utils/lsp.lua", "local M = {}\n\n-- Get all diagnostics from all buffers\n---@return vim.Diagnostic[]\nfunction M.get_all_diagnostics()\n local all_diags = {}\n for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do\n local diags = vim.diagnostic.get(bufnr)\n for _, diag in ipairs(diags) do\n diag.bufnr = bufnr\n table.insert(all_diags, diag)\n end\n end\n return all_diags\nend\n\n-- Get diagnostics by severity level\n---@param severity string \"ERROR\"|\"WARN\"|\"INFO\"|\"HINT\"\n---@return vim.Diagnostic[]\nfunction M.get_diagnostics_by_severity(severity)\n local sev_num = vim.diagnostic.severity[severity:upper()]\n if not sev_num then\n error(\"Invalid severity: \" .. severity)\n end\n\n local filtered = {}\n for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do\n local diags = vim.diagnostic.get(bufnr)\n for _, diag in ipairs(diags) do\n if diag.severity == sev_num then\n diag.bufnr = bufnr\n table.insert(filtered, diag)\n end\n end\n end\n return filtered\nend\n\nreturn M\n"], ["/mcphub.nvim/plugin/mcphub.lua", "if vim.g.loaded_mcphub then\n return\nend\nvim.g.loaded_mcphub = true\n\nlocal hl = require(\"mcphub.utils.highlights\")\nhl.setup()\n\n-- Create command with UI instance check\nvim.api.nvim_create_user_command(\"MCPHub\", function(args)\n local State = require(\"mcphub.state\")\n local config = vim.g.mcphub\n if config and State.setup_state == \"not_started\" then\n require(\"mcphub\").setup(config)\n end\n if State.ui_instance then\n -- UI exists, just toggle it\n State.ui_instance:toggle(args)\n else\n State.ui_instance = require(\"mcphub.ui\"):new(config and config.ui or {})\n State.ui_instance:toggle(args)\n end\nend, {\n desc = \"Toggle MCP Hub window\",\n})\n\n--Auto-setup if configured via vim.g.mcphub\nif vim.g.mcphub then\n require(\"mcphub\").setup(vim.g.mcphub)\nend\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/init.lua", "local mcphub = require(\"mcphub\")\n\n-- Create base neovim server\nmcphub.add_server(\"neovim\", {\n displayName = \"Neovim\",\n description = \"Neovim MCP server provides a set of tools and resources that integrate with neovim.\",\n})\n\nrequire(\"mcphub.native.neovim.terminal\") -- Terminal and shell commands\nrequire(\"mcphub.native.neovim.files\") -- File system operations\nrequire(\"mcphub.native.neovim.lsp\")\nrequire(\"mcphub.native.neovim.prompts\")\n"], ["/mcphub.nvim/lua/mcphub/native/neovim/files/init.lua", "local mcphub = require(\"mcphub\")\n\n-- Import individual tools and resources\nlocal buffer_resource = require(\"mcphub.native.neovim.files.buffer\")\nlocal edit_file_tool = require(\"mcphub.native.neovim.files.edit_file\")\nlocal environment_resource = require(\"mcphub.native.neovim.files.environment\")\nlocal file_tools = require(\"mcphub.native.neovim.files.operations\")\nlocal search_tools = require(\"mcphub.native.neovim.files.search\")\nlocal write_tool = require(\"mcphub.native.neovim.files.write\")\n\nmcphub.add_resource(\"neovim\", buffer_resource)\nmcphub.add_resource(\"neovim\", environment_resource)\n\nfor _, tool in ipairs(file_tools) do\n mcphub.add_tool(\"neovim\", tool)\nend\nfor _, tool in ipairs(search_tools) do\n mcphub.add_tool(\"neovim\", tool)\nend\n\nmcphub.add_tool(\"neovim\", write_tool)\nmcphub.add_tool(\"neovim\", edit_file_tool)\n"], ["/mcphub.nvim/lua/mcphub/utils/constants.lua", "local M = {}\n\n---@enum MCPHub.Constants.ConnectionStatus\nM.ConnectionStatus = {\n CONNECTED = \"connected\",\n CONNECTING = \"connecting\",\n DISCONNECTED = \"disconnected\",\n DISCONNECTING = \"disconnecting\",\n UNAUTHORIZED = \"unauthorized\",\n DISABLED = \"disabled\",\n}\n\n---@enum MCPHub.Constants.EventTypes\nM.EventTypes = {\n HEARTBEAT = \"heartbeat\",\n HUB_STATE = \"hub_state\",\n LOG = \"log\",\n SUBSCRIPTION_EVENT = \"subscription_event\",\n}\n\n---@enum MCPHub.Constants.SubscriptionTypes\nM.SubscriptionTypes = {\n TOOL_LIST_CHANGED = \"tool_list_changed\",\n RESOURCE_LIST_CHANGED = \"resource_list_changed\",\n PROMPT_LIST_CHANGED = \"prompt_list_changed\",\n\n CONFIG_CHANGED = \"config_changed\",\n SERVERS_UPDATING = \"servers_updating\",\n SERVERS_UPDATED = \"servers_updated\",\n\n WORKSPACES_UPDATED = \"workspaces_updated\",\n}\n\n---@enum MCPHub.Constants.HubState\nM.HubState = {\n STARTING = \"starting\",\n READY = \"ready\",\n CONFIGURING = \"configuring\",\n ERROR = \"error\",\n RESTARTING = \"restarting\",\n RESTARTED = \"restarted\",\n STOPPED = \"stopped\",\n STOPPING = \"stopping\",\n}\n\nreturn M\n"], ["/mcphub.nvim/lua/mcphub/utils/version.lua", "return {\n PLUGIN_VERSION = \"6.1.0\", -- Current plugin version\n REQUIRED_NODE_VERSION = { -- Required mcp-hub version\n major = 4,\n minor = 2,\n patch = 0,\n string = \"4.2.0\",\n },\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 00:39:49", "created_task_model": "DeepSeek-R1", "class_skeleton": "{}", "code_description": "This code segment functions to: Initialize a configuration object with default values by merging user-provided parameters and establishing base properties for system components including operational metadata and structural hierarchies."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```lua\n[TASK_BEGIN]\n{\n name = def.name,\n displayName = def.displayName or def.name,\n description = def.description or \"\",\n status = \"disconnected\",\n error = nil,\n capabilities = {}, -- Will be initialized in :initialize()\n uptime = nil,\n lastStarted = nil,\n config_source = def.config_source or \"unknown\",\n is_native = true,\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 00-40-05"}, "editdistance_info": {"edit_distance": 47.1264, "calculate_time": "2025-08-21 00:40:05", "true_code_clean": "{\n name = def.name,\n displayName = def.displayName or def.name,\n description = def.description or \"\",\n status = \"connected\",\n error = nil,\n capabilities = {\n tools = {},\n resources = {},\n resourceTemplates = {},\n prompts = {},\n },\n uptime = 0,\n lastStarted = os.time(),\n config_source = State.config.config,\n is_native = true, \n }", "predict_code_clean": "{\n name = def.name,\n displayName = def.displayName or def.name,\n description = def.description or \"\",\n status = \"disconnected\",\n error = nil,\n capabilities = {}, \n uptime = nil,\n lastStarted = nil,\n config_source = def.config_source or \"unknown\",\n is_native = true,\n}"}}