Files
hrynco-kswitcher/tests/files_mcp.cpp
T

145 lines
6.5 KiB
C++

#include "lan_network.h"
#include "files_mcp.h"
#include <chrono>
#include <future>
#include <iostream>
#include <stdexcept>
namespace
{
using Server=ks::files::FilesMcpServer;
using Json=Server::Json;
using namespace std::chrono_literals;
void expect(bool condition,const char *message)
{
if(!condition) throw std::runtime_error(message);
}
bool connectLoopback(SOCKET socket,unsigned port)
{
sockaddr_in address{};
address.sin_family=AF_INET;
address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
address.sin_port=htons(static_cast<u_short>(port));
return connect(socket,reinterpret_cast<const sockaddr*>(&address),sizeof(address))==0;
}
std::string post(unsigned port,const std::string &token,const Json &message,
std::string_view extra={},std::string_view host={})
{
ks::lan::WinSocket client;
client.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
const DWORD timeout=4000;
expect(client.value!=INVALID_SOCKET &&
!setsockopt(client.value,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast<const char*>(&timeout),sizeof(timeout)) &&
connectLoopback(client.value,port),"Could not connect to fixture listener");
const auto body=message.dump();
const auto authority=host.empty()?"127.0.0.1:"+std::to_string(port):std::string(host);
const auto bytes="POST /mcp HTTP/1.1\r\nHost: "+authority+"\r\nContent-Type: application/json\r\n"
"Accept: application/json, text/event-stream\r\n"+
(token.empty()?std::string{}:"Authorization: Bearer "+token+"\r\n")+
std::string(extra)+"Content-Length: "+std::to_string(body.size())+"\r\n\r\n"+body;
expect(send(client.value,bytes.data(),static_cast<int>(bytes.size()),0)==static_cast<int>(bytes.size()),
"Could not send fixture request");
std::string response;
char buffer[4096];
for(;;)
{
const int count=recv(client.value,buffer,sizeof(buffer),0);
expect(count>=0,"Fixture request timed out");
if(!count) break;
response.append(buffer,count);
expect(response.size()<1024*1024,"Oversized fixture response");
}
return response;
}
Json content(const std::string &response)
{
const auto end=response.find("\r\n\r\n");
expect(end!=response.npos,"No HTTP headers");
return Json::parse(response.substr(end+4));
}
Json request(std::string_view method,Json params=Json::object())
{
return {{"jsonrpc","2.0"},{"id",4},{"method",method},{"params",std::move(params)}};
}
}
int main()
{
try
{
ks::lan::Network network;
const auto owner=CreateWindowExW(0,L"STATIC",L"Files MCP fixture",0,0,0,0,0,
HWND_MESSAGE,nullptr,GetModuleHandleW(nullptr),nullptr);
expect(owner!=nullptr,"Could not create fixture owner window");
Server server;
expect(!server.port() && server.token().empty(),"The listener is enabled by default");
server.start(owner);
const auto port=server.port();
const auto token=std::string(server.token());
expect(port && token.size()==64,"The session does not have a listener and token");
const auto ping=request("ping");
expect(post(port,{},ping).starts_with("HTTP/1.1 401"),"An unauthenticated request was accepted");
expect(post(port,std::string(64,'0'),ping).starts_with("HTTP/1.1 401"),"A wrong token was accepted");
expect(post(port,token,ping,"Origin: https://example.invalid\r\n").starts_with("HTTP/1.1 403"),
"A browser origin was accepted");
expect(post(port,token,ping,{},"other.invalid").starts_with("HTTP/1.1 403"),
"An unexpected Host was accepted");
expect(post(port,token,ping,"Content-Length: 1\r\n").starts_with("HTTP/1.1 400"),
"An ambiguous message length was accepted");
const auto initialized=content(post(port,token,request("initialize",{{"protocolVersion","2025-11-25"}})));
expect(initialized.at("result").at("protocolVersion")=="2025-11-25","Wrong protocol version");
const Json notification{{"jsonrpc","2.0"},{"method","notifications/initialized"}};
expect(post(port,token,notification).starts_with("HTTP/1.1 202"),"Initialization notification did not succeed");
const auto listed=content(post(port,token,request("tools/list")));
const auto &tools=listed.at("result").at("tools");
expect(tools.size()==3,"The listener advertised unexpected capabilities");
for(const auto &tool:tools) expect(tool.at("annotations").at("readOnlyHint")==true,"A tool is not read-only");
const auto unknown=content(post(port,token,request("tools/call",{{"name","write_file"}})));
expect(unknown.at("error").at("code")==-32602,"An unlisted tool was accepted");
auto pending=std::async(std::launch::async,[&]
{
return content(post(port,token,request("tools/call",
{{"name","get_panels"},{"arguments",{{"limit",3}}}})));
});
const auto deadline=std::chrono::steady_clock::now()+3s;
while(pending.wait_for(1ms)!=std::future_status::ready && std::chrono::steady_clock::now()<deadline)
{
MSG message{};
if(PeekMessageW(&message,owner,ks::files::filesMcpQueryMessage,ks::files::filesMcpQueryMessage,PM_REMOVE))
server.answer([](std::string_view name,const Json &arguments)
{
if(name!="get_panels" || arguments.at("limit")!=3) return Json{{"error","Wrong query"}};
return Json{{"active","left"}};
});
}
expect(pending.get().at("result").at("structuredContent").at("active")=="left",
"The server did not return the UI snapshot");
ks::lan::WinSocket idle;
idle.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
expect(idle.value!=INVALID_SOCKET && connectLoopback(idle.value,port),"Could not open idle connection");
const auto start=std::chrono::steady_clock::now();
server.stop();
expect(std::chrono::steady_clock::now()-start<1s && !server.port() && server.token().empty(),
"Stopping did not cancel the listener or detach the token");
server.start(owner);
expect(server.token()!=token,"A restarted listener reused a token");
expect(post(server.port(),token,ping).starts_with("HTTP/1.1 401"),"A revoked token still works");
expect(post(server.port(),std::string(server.token()),ping).starts_with("HTTP/1.1 200"),"The new token failed");
server.stop();
DestroyWindow(owner);
return 0;
}
catch(const std::exception &error)
{
std::cerr<<error.what()<<'\n';
return 1;
}
}