#include "lan_network.h" #include "files_mcp.h" #include "lan_pairing.h" #include #include #include #include #include #include #include #include #include namespace ks::files { namespace { using Json=FilesMcpServer::Json; using Clock=std::chrono::steady_clock; using namespace std::chrono_literals; constexpr size_t maxHeaders=8192,maxRequest=16*1024,maxResponse=512*1024; constexpr std::string_view latestProtocol="2025-11-25"; bool supportedProtocol(std::string_view version) { return version==latestProtocol || version=="2025-06-18" || version=="2025-03-26"; } bool readySocket(SOCKET socket,bool write,std::stop_token stop,Clock::time_point deadline) { while(!stop.stop_requested() && Clock::now()0; } return false; } bool appendSocket(SOCKET socket,std::string &data,std::stop_token stop,Clock::time_point deadline) { char buffer[4096]; if(!readySocket(socket,false,stop,deadline)) return false; const auto count=recv(socket,buffer,sizeof(buffer),0); if(count<=0) return false; data.append(buffer,count); return true; } void sendSocket(SOCKET socket,std::string_view bytes,std::stop_token stop) { const auto deadline=Clock::now()+2s; while(!bytes.empty() && readySocket(socket,true,stop,deadline)) { const auto count=send(socket,bytes.data(),static_cast(bytes.size()),0); if(count<=0) return; bytes.remove_prefix(count); } } std::string lowerAscii(std::string_view text) { std::string result(text); for(auto &ch:result) if(ch>='A' && ch<='Z') ch=static_cast(ch-'A'+'a'); return result; } std::string_view trimHeader(std::string_view text) { const auto first=text.find_first_not_of(" \t"); return first==text.npos?std::string_view{}:text.substr(first,text.find_last_not_of(" \t")-first+1); } struct HttpRequest { std::string_view method,path; std::map> headers; std::string_view header(std::string_view field) const { const auto found=headers.find(field); return found==headers.end()?std::string_view{}:found->second; } }; std::optional parseHeaders(std::string_view data) { HttpRequest request; auto end=data.find("\r\n"); const auto line=data.substr(0,end); const auto first=line.find(' '),second=first==line.npos?line.npos:line.find(' ',first+1); if(end==data.npos || !first || second==line.npos || line.substr(second+1)!="HTTP/1.1") return {}; request.method=line.substr(0,first); request.path=line.substr(first+1,second-first-1); data.remove_prefix(end+2); while(!data.empty()) { end=data.find("\r\n"); const auto header=data.substr(0,end); const auto colon=header.find(':'); if(!colon || colon==header.npos) return {}; const auto name=lowerAscii(header.substr(0,colon)); const auto value=trimHeader(header.substr(colon+1)); if(!std::ranges::all_of(name,[](char ch) {return (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || ch=='-' || ch=='_';}) || !std::ranges::all_of(value,[](unsigned char ch){return ch=='\t' || (ch>=32 && ch<127);}) || !request.headers.emplace(name,value).second) return {}; if(end==data.npos) break; data.remove_prefix(end+2); } return request; } bool hasSessionToken(std::string_view authorization,std::string_view token) { if(authorization.size()!=token.size()+7 || lowerAscii(authorization.substr(0,7))!="bearer ") return false; unsigned difference=0; for(size_t i=0;i(authorization[i+7]^token[i]); return difference==0; } struct HttpReply { const char *status; std::string body; const char *headers=""; }; HttpReply jsonReply(const char *status,Json body) { return {status,body.dump(-1,' ',false,Json::error_handler_t::replace)}; } HttpReply rpcError(const char *status,const Json &id,int code,const char *message) { return jsonReply(status,{{"jsonrpc","2.0"},{"id",id},{"error",{{"code",code},{"message",message}}}}); } const Json &mcpTools() { static const auto tools=Json::parse(R"({"tools":[ {"name":"get_panels","description":"Read the two Files panes and their current local listings, selections and Find state.", "inputSchema":{"type":"object","properties":{"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"additionalProperties":false}, "annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}}, {"name":"search_files","description":"Search the current local listing or existing Find results by name or relative path.", "inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"query":{"type":"string","minLength":1,"maxLength":128},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"required":["query"],"additionalProperties":false}, "annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}}, {"name":"get_file_metadata","description":"Read cached metadata for a relative path already listed in a current local pane.", "inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"path":{"type":"string","minLength":1,"maxLength":2048}},"required":["path"],"additionalProperties":false}, "annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}} ]})"); return tools; } Json toolResult(const Json &data,bool error=false) { const auto text=error?data.get():data.dump(-1,' ',false,Json::error_handler_t::replace); Json result{{"content",Json::array({{{"type","text"},{"text",text}}})},{"isError",error}}; if(!error) result["structuredContent"]=data; return result; } template HttpReply handleRpc(std::string_view body,const Read &read) { Json message,id; try { message=Json::parse(body,[](int depth,Json::parse_event_t,Json &) { if(depth>24) throw std::runtime_error("Request nesting limit"); return true; }); } catch(const std::exception &) {return rpcError("400 Bad Request",nullptr,-32700,"Invalid JSON");} if(!message.is_object() || message.value("jsonrpc",Json())!="2.0" || !message.contains("method") || !message["method"].is_string()) return rpcError("400 Bad Request",nullptr,-32600,"Invalid request"); const auto &method=message["method"].get_ref(); if(!message.contains("id")) { if(method=="notifications/initialized" || method=="notifications/cancelled") return {"202 Accepted",{}}; return rpcError("400 Bad Request",nullptr,-32600,"Unsupported notification"); } id=message["id"]; if(!id.is_number_integer() && (!id.is_string() || id.get_ref().size()>256)) return rpcError("400 Bad Request",nullptr,-32600,"Invalid request id"); auto params=message.value("params",Json::object()); if(!params.is_object()) return rpcError("200 OK",id,-32602,"Invalid parameters"); Json result; if(method=="initialize") { if(!params.contains("protocolVersion") || !params["protocolVersion"].is_string()) return rpcError("200 OK",id,-32602,"Protocol version is required"); const auto version=params["protocolVersion"].get(); result={{"protocolVersion",supportedProtocol(version)?version:std::string(latestProtocol)}, {"capabilities",{{"tools",Json::object()}}}, {"serverInfo",{{"name","kswitcher-files"},{"version","1.0.0"}}}, {"instructions","Inspect the current local listings and cached metadata. Search uses the Files panels' current results."}}; } else if(method=="ping") result=Json::object(); else if(method=="tools/list") result=mcpTools(); else if(method=="tools/call") { if(!params.contains("name") || !params["name"].is_string()) return rpcError("200 OK",id,-32602,"Tool name is required"); const auto &name=params["name"].get_ref(); const auto args=params.value("arguments",Json::object()); if(!args.is_object() || !std::ranges::any_of(mcpTools()["tools"],[&](const auto &tool) {return tool["name"]==name;})) return rpcError("200 OK",id,-32602,"Unknown tool or invalid arguments"); auto data=read(name,args); const auto failed=data.contains("error"); result=failed?toolResult(data.at("error"),true):toolResult(data); } else return rpcError("200 OK",id,-32601,"Method not found"); auto answer=jsonReply("200 OK",{{"jsonrpc","2.0"},{"id",id},{"result",std::move(result)}}); return answer.body.size()<=maxResponse?std::move(answer):rpcError("200 OK",id,-32603,"Response is too large"); } template HttpReply handleHttp(SOCKET socket,unsigned port,std::string_view token,std::stop_token stop,const Read &read) { std::string bytes; const auto deadline=Clock::now()+2s; size_t end{}; while((end=bytes.find("\r\n\r\n"))==bytes.npos) { if(bytes.size()>=maxHeaders) return {"431 Request Header Fields Too Large",{}}; if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}}; } if(end+4>maxHeaders) return {"431 Request Header Fields Too Large",{}}; // Header fields refer into bytes. Parse before appending any further data. const auto request=parseHeaders(std::string_view(bytes).substr(0,end+2)); if(!request) return {"400 Bad Request",{}}; if(request->headers.contains("origin") || request->header("host")!="127.0.0.1:"+std::to_string(port)) return {"403 Forbidden",{}}; if(!hasSessionToken(request->header("authorization"),token)) return {"401 Unauthorized",{},"WWW-Authenticate: Bearer\r\n"}; if(request->path!="/mcp") return {"404 Not Found",{}}; if(request->method!="POST") return {"405 Method Not Allowed",{},"Allow: POST\r\n"}; if(request->headers.contains("transfer-encoding") || (request->headers.contains("mcp-protocol-version") && !supportedProtocol(request->header("mcp-protocol-version")))) return {"400 Bad Request",{}}; const auto type=request->header("content-type"); if(lowerAscii(trimHeader(type.substr(0,type.find(';'))))!="application/json") return {"415 Unsupported Media Type",{}}; const auto length=request->header("content-length"); size_t count{}; if(length.empty()) return {"411 Length Required",{}}; const auto converted=std::from_chars(length.data(),length.data()+length.size(),count); if(converted.ec!=std::errc{} || converted.ptr!=length.data()+length.size()) return {"400 Bad Request",{}}; if(count>maxRequest) return {"413 Content Too Large",{}}; const auto start=end+4; while(bytes.size()-start result; std::atomic_bool cancelled{}; }; lan::Network network; lan::WinSocket listener; unsigned port{}; std::string token=lan::randomHex(32); HWND owner{}; std::mutex gate; std::shared_ptr pending; std::jthread worker; explicit Session(HWND window):owner(window) { listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); BOOL exclusive=TRUE; u_long nonblocking=1; sockaddr_in address{}; address.sin_family=AF_INET; address.sin_addr.s_addr=htonl(INADDR_LOOPBACK); int size=sizeof(address); if(listener.value==INVALID_SOCKET || setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE, reinterpret_cast(&exclusive),sizeof(exclusive)) || ioctlsocket(listener.value,FIONBIO,&nonblocking) || bind(listener.value,reinterpret_cast(&address),sizeof(address)) || listen(listener.value,4) || getsockname(listener.value,reinterpret_cast(&address),&size)) lan::socketError(); port=ntohs(address.sin_port); worker=std::jthread([this](std::stop_token stop){run(stop);}); } ~Session() { worker.request_stop(); if(worker.joinable()) worker.join(); SecureZeroMemory(token.data(),token.size()); } Json requestUi(std::string_view name,const Json &arguments,std::stop_token stop) { auto query=std::make_shared(); query->name=name; query->arguments=arguments; auto result=query->result.get_future(); { std::lock_guard lock(gate); pending=query; } const auto deadline=Clock::now()+2s; if(PostMessageW(owner,filesMcpQueryMessage,0,0)) while(!stop.stop_requested() && Clock::now()cancelled=true; std::lock_guard lock(gate); if(pending==query) pending.reset(); return {{"error","Files did not answer in time."}}; } void run(std::stop_token stop) { while(!stop.stop_requested()) { if(!readySocket(listener.value,false,stop,Clock::now()+100ms)) continue; sockaddr_in peer{}; int peerSize=sizeof(peer); lan::WinSocket client; client.value=accept(listener.value,reinterpret_cast(&peer),&peerSize); u_long nonblocking=1; if(client.value==INVALID_SOCKET || peer.sin_family!=AF_INET || peer.sin_addr.s_addr!=htonl(INADDR_LOOPBACK) || ioctlsocket(client.value,FIONBIO,&nonblocking)) continue; HttpReply reply{"500 Internal Server Error",{}}; try { reply=handleHttp(client.value,port,token,stop,[&](std::string_view name,const Json ¶ms) {return requestUi(name,params,stop);}); } catch(const std::exception &) {} const auto header=std::string("HTTP/1.1 ")+reply.status+"\r\nConnection: close\r\n" "Cache-Control: no-store\r\nContent-Type: application/json\r\n"+reply.headers+ "Content-Length: "+std::to_string(reply.body.size())+"\r\n\r\n"; sendSocket(client.value,header+reply.body,stop); } } }; FilesMcpServer::FilesMcpServer()=default; FilesMcpServer::~FilesMcpServer()=default; void FilesMcpServer::start(HWND owner) { if(!session) session=std::make_unique(owner); } void FilesMcpServer::stop() {session.reset();} unsigned FilesMcpServer::port() const {return session?session->port:0;} std::string_view FilesMcpServer::token() const {return session?std::string_view(session->token):std::string_view{};} void FilesMcpServer::answer(const ReadTool &read) { if(!session) return; std::shared_ptr query; { std::lock_guard lock(session->gate); query=std::exchange(session->pending,{}); } if(!query || query->cancelled) return; try {query->result.set_value(read(query->name,query->arguments));} catch(const std::exception &) {query->result.set_value({{"error","Files could not read the requested state."}});} } }