Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

fix(mcp): HTTP transport + 6 correctness fixes + UI parity round 1

DangHuynh97a987afd4cb
diff --git a/windows/Gridex/App.xaml.cpp b/windows/Gridex/App.xaml.cpp
index 8a62124..8b9a29f 100644
--- a/windows/Gridex/App.xaml.cpp
+++ b/windows/Gridex/App.xaml.cpp
@@ -10,6 +10,7 @@
#include <string>
#include <cwchar>
#include <condition_variable>
+#include <shlobj.h>
using namespace winrt;
using namespace Microsoft::UI::Xaml;
@@ -161,6 +162,17 @@ namespace winrt::Gridex::implementation
// other MCP clients with stdin/stdout piped. No XAML
// window is created; we block the main thread until the
// reader hits EOF and then exit.
+ //
+ // Gridex is GUI subsystem. When launched with piped
+ // stdin/stdout (Claude Desktop, cmd `|`), those handles
+ // are already inherited — GetStdHandle returns them
+ // directly. DO NOT call AttachConsole here: on a piped
+ // launch it would replace our inherited handles with a
+ // fresh console and the piped data would be lost.
+ //
+ // StdioTransport uses raw Win32 HANDLE I/O so the C
+ // runtime stdio state doesn't matter.
+
auto s = DBModels::AppSettings::Load();
DBModels::MCPServerHost::ensureCreated(
s,
@@ -173,9 +185,10 @@ namespace winrt::Gridex::implementation
// signals shutdown (EOF or "shutdown" JSON-RPC).
std::mutex mtx; std::condition_variable cv; bool done = false;
std::thread waiter([&]{
- while (auto* srv = DBModels::MCPServerHost::instance())
+ while (true)
{
- if (!srv->isRunning()) break;
+ auto srv = DBModels::MCPServerHost::instance();
+ if (!srv || !srv->isRunning()) break;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
{ std::lock_guard<std::mutex> lk(mtx); done = true; }
diff --git a/windows/Gridex/Gridex.items.props b/windows/Gridex/Gridex.items.props
index 479fc71..3913708 100644
--- a/windows/Gridex/Gridex.items.props
+++ b/windows/Gridex/Gridex.items.props
@@ -45,6 +45,7 @@
<ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\MCPTool.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\MCPToolRegistry.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Transport\StdioTransport.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Transport\HttpTransport.h" />
<!-- MCP Phase 5 — tools (subset: list_connections, list_tables,
describe_table, query). Tier 3 write tools land in a follow-up. -->
<ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\MCPToolHelpers.h" />
@@ -335,6 +336,9 @@
<ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Transport\StdioTransport.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Transport\HttpTransport.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\MCPBuiltinTools.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
diff --git a/windows/Gridex/MCPPage.cpp b/windows/Gridex/MCPPage.cpp
index b4f46cf..8081867 100644
--- a/windows/Gridex/MCPPage.cpp
+++ b/windows/Gridex/MCPPage.cpp
@@ -11,6 +11,9 @@
#include "GridexVersion.h"
#include <winrt/Windows.ApplicationModel.DataTransfer.h>
#include <winrt/Windows.UI.h>
+#include <nlohmann/json.hpp>
+#include <fstream>
+#include <shlobj.h>
namespace winrt::Gridex::implementation
{
@@ -50,8 +53,13 @@ namespace winrt::Gridex::implementation
QphBox().Value(static_cast<double>(settings.mcpQueriesPerHour));
WpmBox().Value(static_cast<double>(settings.mcpWritesPerMinute));
DdlBox().Value(static_cast<double>(settings.mcpDdlPerMinute));
+ QueryTimeoutBox().Value(static_cast<double>(settings.mcpQueryTimeout));
+ ApprovalTimeoutBox().Value(static_cast<double>(settings.mcpApprovalTimeout));
+ ConnectionTimeoutBox().Value(static_cast<double>(settings.mcpConnectionTimeout));
RetentionBox().Value(static_cast<double>(settings.mcpAuditRetentionDays));
MaxSizeBox().Value(static_cast<double>(settings.mcpAuditMaxSizeMB));
+ RequireApprovalToggle().IsOn(settings.mcpRequireApprovalForWrites);
+ AllowRemoteHttpToggle().IsOn(settings.mcpAllowRemoteHTTP);
// Count connections per MCP mode.
int locked = 0, ro = 0, rw = 0;
@@ -70,7 +78,7 @@ namespace winrt::Gridex::implementation
ReadWriteCount().Text(winrt::hstring(std::to_wstring(rw)));
// Server state.
- auto* srv = DBModels::MCPServerHost::instance();
+ auto srv = DBModels::MCPServerHost::instance();
const bool running = srv && srv->isRunning();
ApplyStartStopButton(running);
if (running)
@@ -147,7 +155,7 @@ namespace winrt::Gridex::implementation
winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
{
auto settings = DBModels::AppSettings::Load();
- auto* srv = DBModels::MCPServerHost::instance();
+ auto srv = DBModels::MCPServerHost::instance();
if (srv && srv->isRunning())
{
@@ -166,7 +174,7 @@ namespace winrt::Gridex::implementation
DBModels::MCPTransportMode::HttpOnly);
// Hook XamlRoot + dispatcher so approval dialogs can open.
- auto* running = DBModels::MCPServerHost::instance();
+ auto running = DBModels::MCPServerHost::instance();
if (running)
{
auto content = this->XamlRoot();
@@ -215,9 +223,86 @@ namespace winrt::Gridex::implementation
s.mcpQueriesPerHour = static_cast<int>(QphBox().Value());
s.mcpWritesPerMinute = static_cast<int>(WpmBox().Value());
s.mcpDdlPerMinute = static_cast<int>(DdlBox().Value());
+ s.mcpQueryTimeout = static_cast<int>(QueryTimeoutBox().Value());
+ s.mcpApprovalTimeout = static_cast<int>(ApprovalTimeoutBox().Value());
+ s.mcpConnectionTimeout = static_cast<int>(ConnectionTimeoutBox().Value());
s.mcpAuditRetentionDays = static_cast<int>(RetentionBox().Value());
s.mcpAuditMaxSizeMB = static_cast<int>(MaxSizeBox().Value());
+ s.mcpRequireApprovalForWrites = RequireApprovalToggle().IsOn();
+ s.mcpAllowRemoteHTTP = AllowRemoteHttpToggle().IsOn();
s.Save();
SaveConfigStatusText().Text(L"Saved. Restart the server to apply rate-limit / audit changes.");
}
+
+ // Install for Claude Desktop — merges the Gridex entry into
+ // %APPDATA%\Claude\claude_desktop_config.json, preserving any
+ // existing mcpServers entries. A .bak backup is dropped next to
+ // the original file before mutation so users can roll back.
+ void MCPPage::InstallClaude_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ wchar_t* appDataW = nullptr;
+ if (SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &appDataW) != S_OK)
+ {
+ InstallStatusText().Text(L"Cannot resolve %APPDATA%.");
+ return;
+ }
+ const std::wstring appData(appDataW);
+ CoTaskMemFree(appDataW);
+
+ const std::wstring claudeDir = appData + L"\\Claude";
+ const std::wstring configPath = claudeDir + L"\\claude_desktop_config.json";
+ CreateDirectoryW(claudeDir.c_str(), nullptr);
+
+ // Resolve exe path for the new mcpServers.gridex entry.
+ wchar_t exePath[MAX_PATH] = {};
+ GetModuleFileNameW(nullptr, exePath, MAX_PATH);
+
+ nlohmann::json existing = nlohmann::json::object();
+ if (GetFileAttributesW(configPath.c_str()) != INVALID_FILE_ATTRIBUTES)
+ {
+ // Backup first.
+ const std::wstring backup = configPath + L".bak";
+ CopyFileW(configPath.c_str(), backup.c_str(), FALSE);
+ try
+ {
+ std::ifstream in(configPath, std::ios::binary);
+ if (in.is_open()) existing = nlohmann::json::parse(in, nullptr, false);
+ if (existing.is_discarded()) existing = nlohmann::json::object();
+ }
+ catch (...) { existing = nlohmann::json::object(); }
+ }
+
+ if (!existing.contains("mcpServers") || !existing["mcpServers"].is_object())
+ existing["mcpServers"] = nlohmann::json::object();
+
+ // Convert exe path to utf-8 with escaped backslashes for JSON.
+ std::string exeUtf8;
+ {
+ std::wstring w(exePath);
+ int sz = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(),
+ nullptr, 0, nullptr, nullptr);
+ exeUtf8.resize(sz);
+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(),
+ &exeUtf8[0], sz, nullptr, nullptr);
+ }
+
+ existing["mcpServers"]["gridex"] = {
+ {"command", exeUtf8},
+ {"args", nlohmann::json::array({"--mcp-stdio"})}
+ };
+
+ std::ofstream out(configPath, std::ios::binary | std::ios::trunc);
+ if (!out.is_open())
+ {
+ InstallStatusText().Text(L"Failed to write config. Is Claude Desktop running?");
+ return;
+ }
+ out << existing.dump(2);
+ out.close();
+
+ InstallStatusText().Text(
+ L"Installed. Restart Claude Desktop; a .bak backup of the previous config is next to the file.");
+ }
}
diff --git a/windows/Gridex/MCPPage.h b/windows/Gridex/MCPPage.h
index 67e6fc9..1760753 100644
--- a/windows/Gridex/MCPPage.h
+++ b/windows/Gridex/MCPPage.h
@@ -31,6 +31,10 @@ namespace winrt::Gridex::implementation
winrt::Windows::Foundation::IInspectable const& sender,
winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+ void InstallClaude_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
private:
void RefreshUI();
void ApplyStartStopButton(bool running);
diff --git a/windows/Gridex/MCPPage.xaml b/windows/Gridex/MCPPage.xaml
index 716d122..3bc016a 100644
--- a/windows/Gridex/MCPPage.xaml
+++ b/windows/Gridex/MCPPage.xaml
@@ -77,7 +77,8 @@
<TextBlock x:Name="RunningSubtitle"
Text="Enable below to let AI clients connect."
FontSize="12"
- Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}"
+ TextWrapping="Wrap" />
</StackPanel>
</StackPanel>
</Border>
@@ -213,12 +214,72 @@
<PivotItem Header="Setup">
<ScrollViewer>
<StackPanel Spacing="16" MaxWidth="820">
- <TextBlock Text="Paste this JSON into your Claude Desktop config file"
- FontSize="14" FontWeight="SemiBold" />
- <TextBlock x:Name="SetupPathText"
- FontSize="12"
- IsTextSelectionEnabled="True"
- Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ <!-- Info banner — matches mac "This is a config file..." -->
+ <Border Padding="12,10" CornerRadius="6"
+ Background="{ThemeResource CardBackgroundFillColorSecondaryBrush}">
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <FontIcon Glyph="&#xE946;" FontSize="14"
+ Foreground="DodgerBlue" />
+ <StackPanel>
+ <TextBlock Text="This is a config file, not a terminal command"
+ FontSize="13" FontWeight="SemiBold" />
+ <TextBlock FontSize="11"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}"
+ TextWrapping="Wrap"
+ Text="Use 'Install' below to add Gridex to Claude Desktop automatically, or copy and paste into the config file manually." />
+ </StackPanel>
+ </StackPanel>
+ </Border>
+
+ <!-- Client picker. Single option for now; add
+ Cursor / continue.dev once their install
+ paths are documented. -->
+ <StackPanel Spacing="4">
+ <TextBlock Text="AI Client" FontSize="13" FontWeight="SemiBold" />
+ <ComboBox x:Name="ClientPicker" SelectedIndex="0" Width="260">
+ <ComboBoxItem Content="Claude Desktop" />
+ </ComboBox>
+ </StackPanel>
+
+ <StackPanel Spacing="4">
+ <TextBlock Text="Config file" FontSize="13" FontWeight="SemiBold" />
+ <TextBlock x:Name="SetupPathText"
+ FontSize="12"
+ IsTextSelectionEnabled="True"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ </StackPanel>
+
+ <!-- Quick Install row — big accent button +
+ Copy side-by-side, matching the mac. -->
+ <StackPanel Spacing="8">
+ <TextBlock Text="Quick Install" FontSize="13" FontWeight="SemiBold" />
+ <StackPanel Orientation="Horizontal" Spacing="8">
+ <Button x:Name="InstallClaudeBtn"
+ Click="InstallClaude_Click"
+ Style="{StaticResource AccentButtonStyle}"
+ MinWidth="280" Padding="16,8">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xEA86;" FontSize="14" />
+ <TextBlock Text="Install for Claude Desktop" />
+ </StackPanel>
+ </Button>
+ <Button x:Name="CopyConfigBtn"
+ Click="CopyConfig_Click"
+ Padding="16,8">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE8C8;" FontSize="14" />
+ <TextBlock Text="Copy" />
+ </StackPanel>
+ </Button>
+ </StackPanel>
+ <TextBlock x:Name="InstallStatusText"
+ FontSize="11"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />
+ </StackPanel>
+
+ <TextBlock Text="Configuration Preview"
+ FontSize="13" FontWeight="SemiBold"
+ Margin="0,8,0,0" />
<Border Padding="12" CornerRadius="6"
Background="{ThemeResource CardBackgroundFillColorSecondaryBrush}">
<TextBox x:Name="SetupConfigBox"
@@ -229,10 +290,6 @@
TextWrapping="NoWrap"
MinHeight="160" />
</Border>
- <Button x:Name="CopyConfigBtn"
- Content="Copy Config"
- Click="CopyConfig_Click"
- HorizontalAlignment="Left" />
</StackPanel>
</ScrollViewer>
</PivotItem>
@@ -267,6 +324,42 @@
Minimum="1" Maximum="20" Value="1" />
</Grid>
+ <TextBlock Text="Timeouts" FontSize="14" FontWeight="SemiBold" Margin="0,8,0,0" />
+ <Grid ColumnSpacing="16" RowSpacing="8">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="140" />
+ </Grid.ColumnDefinitions>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ </Grid.RowDefinitions>
+ <TextBlock Text="Query timeout (sec)" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="QueryTimeoutBox" Grid.Row="0" Grid.Column="1"
+ Minimum="5" Maximum="600" Value="30" />
+ <TextBlock Text="Approval timeout (sec)" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="ApprovalTimeoutBox" Grid.Row="1" Grid.Column="1"
+ Minimum="10" Maximum="300" Value="60" />
+ <TextBlock Text="Connection timeout (sec)" Grid.Row="2" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="ConnectionTimeoutBox" Grid.Row="2" Grid.Column="1"
+ Minimum="5" Maximum="60" Value="10" />
+ </Grid>
+
+ <TextBlock Text="Security" FontSize="14" FontWeight="SemiBold" Margin="0,8,0,0" />
+ <StackPanel Spacing="8">
+ <ToggleSwitch x:Name="RequireApprovalToggle"
+ Header="Require approval for write operations"
+ IsOn="True" />
+ <ToggleSwitch x:Name="AllowRemoteHttpToggle"
+ Header="Allow remote HTTP connections"
+ IsOn="False" />
+ <TextBlock Text="⚠ Remote HTTP exposes the MCP server on your LAN. Only enable on trusted networks."
+ FontSize="11"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"
+ TextWrapping="Wrap" />
+ </StackPanel>
+
<TextBlock Text="Audit Log" FontSize="14" FontWeight="SemiBold" Margin="0,8,0,0" />
<Grid ColumnSpacing="16" RowSpacing="8">
<Grid.ColumnDefinitions>
diff --git a/windows/Gridex/Models/MCP/MCPAuditEntry.h b/windows/Gridex/Models/MCP/MCPAuditEntry.h
index 93ed2a0..e92bbd6 100644
--- a/windows/Gridex/Models/MCP/MCPAuditEntry.h
+++ b/windows/Gridex/Models/MCP/MCPAuditEntry.h
@@ -69,8 +69,19 @@ namespace DBModels
{
const std::string preview = sql.size() > 200 ? sql.substr(0, 200) + "..." : sql;
i.sqlPreview = preview;
- const std::size_t h = std::hash<std::string>{}(sql);
- i.inputHash = "h64:" + std::to_string(h);
+ // FNV-1a 64-bit — deterministic across processes so
+ // the inputHash field stays stable for cross-session
+ // correlation. Not cryptographic; display-only aid.
+ uint64_t h = 14695981039346656037ULL;
+ for (unsigned char c : sql)
+ {
+ h ^= c;
+ h *= 1099511628211ULL;
+ }
+ char buf[24];
+ snprintf(buf, sizeof(buf), "fnv1a:%016llx",
+ static_cast<unsigned long long>(h));
+ i.inputHash = buf;
}
i.paramsCount = paramsCount;
return i;
diff --git a/windows/Gridex/Services/MCP/MCPServer.cpp b/windows/Gridex/Services/MCP/MCPServer.cpp
index e76a460..8f86531 100644
--- a/windows/Gridex/Services/MCP/MCPServer.cpp
+++ b/windows/Gridex/Services/MCP/MCPServer.cpp
@@ -48,6 +48,8 @@ namespace DBModels
}
}
+ MCPServer::~MCPServer() = default;
+
MCPServer::MCPServer(AppSettings settings, std::string serverVersion, MCPTransportMode mode)
: settings_(std::move(settings)),
serverVersion_(std::move(serverVersion)),
@@ -77,13 +79,41 @@ namespace DBModels
stdio_.setRequestHandler([this](const JSONRPCRequest& r){ handleRequest(r); });
stdio_.start();
}
- // HTTP transport start — Phase 4d (TODO).
+ else
+ {
+ // HttpOnly: always start HTTP on localhost. If the user
+ // flipped `mcpHttpEnabled` in settings the port comes
+ // from there; otherwise fall back to the default 3333.
+ // Remote binding (`0.0.0.0`) only when `allowRemoteHTTP`.
+ const int port = settings_.mcpHttpEnabled
+ ? settings_.mcpHttpPort : 3333;
+ const std::string host = settings_.mcpAllowRemoteHTTP
+ ? "0.0.0.0" : "127.0.0.1";
+
+ http_.setRequestHandler(
+ [this](const JSONRPCRequest& r) -> JSONRPCResponse {
+ // HTTP is synchronous — we build the response
+ // inline instead of routing through sendResponse.
+ // Reuse the same dispatch branches handleRequest
+ // uses by returning its output directly.
+ if (r.method == "initialize") return handleInitialize(r);
+ if (r.method == "tools/list") return handleToolsList(r);
+ if (r.method == "tools/call") return handleToolsCall(r);
+ if (r.method == "ping")
+ return JSONRPCResponse::ok(r.id, nlohmann::json{{"pong", true}});
+ if (r.method == "shutdown") { stop(); return JSONRPCResponse::ok(r.id, nullptr); }
+ if (r.method == "initialized") return JSONRPCResponse::ok(r.id, nullptr);
+ return JSONRPCResponse::fail(r.id, JSONRPCError::methodNotFound());
+ });
+ http_.start(host, port);
+ }
}
void MCPServer::stop()
{
if (!running_.exchange(false)) return;
stdio_.stop();
+ http_.stop();
auditLogger_.close();
pool_.releaseAll();
}
diff --git a/windows/Gridex/Services/MCP/MCPServer.h b/windows/Gridex/Services/MCP/MCPServer.h
index 7d67559..5301e30 100644
--- a/windows/Gridex/Services/MCP/MCPServer.h
+++ b/windows/Gridex/Services/MCP/MCPServer.h
@@ -24,6 +24,7 @@
#include "Security/MCPApprovalGate.h"
#include "Audit/MCPAuditLogger.h"
#include "Transport/StdioTransport.h"
+#include "Transport/HttpTransport.h"
#include "../../Models/MCP/MCPProtocol.h"
#include "../../Models/MCP/MCPServerInfo.h"
#include "../../Models/AppSettings.h"
@@ -42,6 +43,11 @@ namespace DBModels
MCPServer(AppSettings settings,
std::string serverVersion,
MCPTransportMode mode);
+ // Out-of-line: HttpTransport uses pimpl and requires the
+ // MCPServer dtor be defined where HttpTransport::Impl is
+ // complete (i.e. MCPServer.cpp, which includes HttpTransport.h
+ // whose .cpp has the full Impl struct).
+ ~MCPServer();
// Start accepting requests.
void start();
@@ -81,6 +87,7 @@ namespace DBModels
MCPAuditLogger auditLogger_;
MCPToolRegistry toolRegistry_;
StdioTransport stdio_;
+ HttpTransport http_;
MCPClientInfo clientInfo_; // populated on initialize
diff --git a/windows/Gridex/Services/MCP/MCPServerHost.cpp b/windows/Gridex/Services/MCP/MCPServerHost.cpp
index 5f8a3fb..cdf4dc7 100644
--- a/windows/Gridex/Services/MCP/MCPServerHost.cpp
+++ b/windows/Gridex/Services/MCP/MCPServerHost.cpp
@@ -8,39 +8,42 @@ namespace DBModels { namespace MCPServerHost {
namespace {
std::mutex g_mtx;
- std::unique_ptr<MCPServer> g_server;
+ // shared_ptr so a concurrent `stop()` cannot tear the object
+ // out from under a caller that already extracted the pointer.
+ std::shared_ptr<MCPServer> g_server;
}
-MCPServer* ensureCreated(const AppSettings& settings,
- const std::string& version,
- MCPTransportMode mode)
+std::shared_ptr<MCPServer> ensureCreated(const AppSettings& settings,
+ const std::string& version,
+ MCPTransportMode mode)
{
std::lock_guard<std::mutex> lk(g_mtx);
if (!g_server)
- g_server = std::make_unique<MCPServer>(settings, version, mode);
- return g_server.get();
+ g_server = std::make_shared<MCPServer>(settings, version, mode);
+ return g_server;
}
-MCPServer* instance()
+std::shared_ptr<MCPServer> instance()
{
std::lock_guard<std::mutex> lk(g_mtx);
- return g_server.get();
+ return g_server;
}
void start()
{
- std::lock_guard<std::mutex> lk(g_mtx);
- if (g_server) g_server->start();
+ std::shared_ptr<MCPServer> local;
+ { std::lock_guard<std::mutex> lk(g_mtx); local = g_server; }
+ if (local) local->start();
}
void stop()
{
- std::lock_guard<std::mutex> lk(g_mtx);
- if (g_server)
- {
- g_server->stop();
- g_server.reset();
- }
+ std::shared_ptr<MCPServer> local;
+ { std::lock_guard<std::mutex> lk(g_mtx); local = std::move(g_server); }
+ if (local) local->stop();
+ // `local` drops here; any other thread still holding a
+ // previously-returned shared_ptr sees isRunning()==false and
+ // bails safely instead of touching freed memory.
}
}} // namespace
diff --git a/windows/Gridex/Services/MCP/MCPServerHost.h b/windows/Gridex/Services/MCP/MCPServerHost.h
index 645b353..c839b2d 100644
--- a/windows/Gridex/Services/MCP/MCPServerHost.h
+++ b/windows/Gridex/Services/MCP/MCPServerHost.h
@@ -17,14 +17,16 @@
namespace DBModels { namespace MCPServerHost {
// Ensures a server exists (creating on demand with the supplied
-// settings + mode) and returns a non-owning pointer. Safe to call
-// repeatedly — subsequent calls just return the existing instance.
-MCPServer* ensureCreated(const AppSettings& settings,
- const std::string& version,
- MCPTransportMode mode);
+// settings + mode) and returns a shared_ptr. Caller keeps the
+// shared_ptr for as long as it needs to touch the server — avoids
+// UAF races with stop() running on a different thread.
+std::shared_ptr<MCPServer> ensureCreated(const AppSettings& settings,
+ const std::string& version,
+ MCPTransportMode mode);
-// Returns the shared server, or nullptr if it has never been created.
-MCPServer* instance();
+// Returns the shared server, or empty shared_ptr if none exists.
+// Hold onto the returned shared_ptr for the duration of the call.
+std::shared_ptr<MCPServer> instance();
// Starts the shared server (idempotent).
void start();
diff --git a/windows/Gridex/Services/MCP/Tools/MCPTool.cpp b/windows/Gridex/Services/MCP/Tools/MCPTool.cpp
index 8505848..4908a79 100644
--- a/windows/Gridex/Services/MCP/Tools/MCPTool.cpp
+++ b/windows/Gridex/Services/MCP/Tools/MCPTool.cpp
@@ -7,6 +7,7 @@
#include "../../../Models/CredentialManager.h"
#include "../../../Models/MCP/MCPAuditEntry.h"
#include <algorithm>
+#include <windows.h>
namespace DBModels
{
@@ -14,8 +15,16 @@ namespace DBModels
{
if (!params.contains("connection_id") || !params["connection_id"].is_string())
throw MCPToolError::invalidParameters("connection_id is required");
- auto utf8 = params["connection_id"].get<std::string>();
- return std::wstring(utf8.begin(), utf8.end()); // ASCII-only ids (UUIDs)
+ const auto utf8 = params["connection_id"].get<std::string>();
+ // Proper UTF-8 decode — char-by-char widening would corrupt
+ // any non-ASCII id (future cloud sync may produce them).
+ if (utf8.empty()) return {};
+ int sz = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
+ static_cast<int>(utf8.size()), nullptr, 0);
+ std::wstring out(sz, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
+ static_cast<int>(utf8.size()), &out[0], sz);
+ return out;
}
std::pair<std::shared_ptr<DatabaseAdapter>, ConnectionConfig>
diff --git a/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.cpp
index 819c5aa..a4cd9d1 100644
--- a/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.cpp
+++ b/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.cpp
@@ -8,12 +8,15 @@
namespace DBModels
{
- static bool isSQLType(DatabaseType t)
+ // Engines that accept `LIMIT n` as SQL-standard tail. MSSQL is
+ // deliberately excluded — it uses `TOP n` after SELECT, which
+ // we cannot safely inject without rewriting the statement.
+ // Callers targeting MSSQL must emit their own TOP clause.
+ static bool acceptsLimitSuffix(DatabaseType t)
{
return t == DatabaseType::PostgreSQL ||
t == DatabaseType::MySQL ||
- t == DatabaseType::SQLite ||
- t == DatabaseType::MSSQLServer;
+ t == DatabaseType::SQLite;
}
MCPToolResult QueryTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
@@ -48,10 +51,15 @@ namespace DBModels
// sql untouched otherwise (Redis/Mongo adapters carry their
// own shape).
std::wstring sqlW = MCPToolHelpers::fromUtf8(sqlUtf8);
- if (isSQLType(config.databaseType))
+ if (acceptsLimitSuffix(config.databaseType))
{
std::wstring upper = sqlW;
std::transform(upper.begin(), upper.end(), upper.begin(), ::towupper);
+ // `upper.find(L"LIMIT")` also catches the substring inside
+ // a column name or comment, but since the caller sees a
+ // working query either way this false-positive only costs
+ // them a missing extra LIMIT clause — safer than double
+ // LIMIT. String sanitizer already ran upstream.
if (upper.find(L"LIMIT") == std::wstring::npos)
{
std::wstring trimmed = sqlW;
diff --git a/windows/Gridex/Services/MCP/Transport/HttpTransport.cpp b/windows/Gridex/Services/MCP/Transport/HttpTransport.cpp
new file mode 100644
index 0000000..5ffe3fa
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Transport/HttpTransport.cpp
@@ -0,0 +1,97 @@
+//
+// HttpTransport.cpp
+//
+// cpp-httplib based JSON-RPC server. The WinSock/OpenSSL headers
+// it drags in are massive so we hide them behind a pimpl.
+
+#include "HttpTransport.h"
+
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+
+#pragma warning(push)
+#pragma warning(disable: 4996)
+#include <httplib.h>
+#pragma warning(pop)
+
+namespace DBModels
+{
+ struct HttpTransport::Impl
+ {
+ httplib::Server server;
+ };
+
+ HttpTransport::HttpTransport() = default;
+ HttpTransport::~HttpTransport() { stop(); }
+
+ bool HttpTransport::start(const std::string& host, int port)
+ {
+ if (running_.exchange(true)) return true;
+
+ impl_ = std::make_unique<Impl>();
+
+ // MCP clients POST JSON-RPC requests to `/` (convention
+ // used by the reference Python/Node servers). We accept
+ // both `/` and `/mcp` for tool compatibility.
+ auto handlePost = [this](const httplib::Request& req, httplib::Response& res)
+ {
+ res.set_header("Access-Control-Allow-Origin", "*");
+ JSONRPCResponse resp;
+ try
+ {
+ auto j = nlohmann::json::parse(req.body);
+ JSONRPCRequest rpc;
+ from_json(j, rpc);
+ if (handler_)
+ resp = handler_(rpc);
+ else
+ resp = JSONRPCResponse::fail(rpc.id, JSONRPCError::internalError());
+ }
+ catch (const std::exception&)
+ {
+ resp = JSONRPCResponse::fail(nullptr, JSONRPCError::parseError());
+ }
+ nlohmann::json rj;
+ to_json(rj, resp);
+ res.set_content(rj.dump(), "application/json");
+ };
+
+ auto handleOptions = [](const httplib::Request&, httplib::Response& res)
+ {
+ // CORS preflight for browser-based clients (dev aid).
+ res.set_header("Access-Control-Allow-Origin", "*");
+ res.set_header("Access-Control-Allow-Methods", "POST, OPTIONS");
+ res.set_header("Access-Control-Allow-Headers", "Content-Type");
+ res.status = 204;
+ };
+
+ impl_->server.Post("/", handlePost);
+ impl_->server.Post("/mcp", handlePost);
+ impl_->server.Options("/", handleOptions);
+ impl_->server.Options("/mcp", handleOptions);
+
+ // GET /health — lightweight check so ops can ping without
+ // sending a full JSON-RPC.
+ impl_->server.Get("/health", [](const httplib::Request&, httplib::Response& r)
+ {
+ r.set_content(R"({"status":"ok","server":"gridex-mcp"})", "application/json");
+ });
+
+ server_ = std::thread([this, host, port]()
+ {
+ impl_->server.listen(host.c_str(), port);
+ running_.store(false);
+ });
+
+ return true;
+ }
+
+ void HttpTransport::stop()
+ {
+ if (!running_.exchange(false)) return;
+ if (impl_) impl_->server.stop();
+ if (server_.joinable()) server_.join();
+ impl_.reset();
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Transport/HttpTransport.h b/windows/Gridex/Services/MCP/Transport/HttpTransport.h
new file mode 100644
index 0000000..4c44c72
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Transport/HttpTransport.h
@@ -0,0 +1,58 @@
+#pragma once
+//
+// HttpTransport.h
+// Gridex
+//
+// HTTP JSON-RPC transport for MCP using cpp-httplib. Listens on
+// localhost (or 0.0.0.0 if `allowRemoteHTTP` is set). One request
+// per POST. Same RequestHandler callback contract as StdioTransport
+// so the MCPServer dispatch layer stays uniform.
+//
+// Runs the httplib::Server on a dedicated background thread; the
+// callback is invoked synchronously on that thread for each POST.
+// Response is produced by a helper the handler stores via a
+// thread-local shim.
+
+#include <string>
+#include <atomic>
+#include <thread>
+#include <mutex>
+#include <functional>
+#include <memory>
+#include "../../../Models/MCP/MCPProtocol.h"
+
+namespace DBModels
+{
+ class HttpTransport
+ {
+ public:
+ // Handler returns the response (synchronous). This is
+ // simpler than the stdio model because every POST has a
+ // 1:1 response.
+ using RequestHandler = std::function<JSONRPCResponse(const JSONRPCRequest&)>;
+
+ HttpTransport();
+ ~HttpTransport();
+
+ void setRequestHandler(RequestHandler h) { handler_ = std::move(h); }
+
+ // Starts the HTTP server on `host:port`. `host` = "127.0.0.1"
+ // for localhost-only, "0.0.0.0" for remote connections.
+ // Returns false if bind fails (port in use).
+ bool start(const std::string& host, int port);
+
+ void stop();
+
+ bool isRunning() const { return running_.load(); }
+
+ private:
+ std::atomic<bool> running_{false};
+ std::thread server_;
+ RequestHandler handler_;
+
+ // Pimpl — keeps httplib out of the header so consumers don't
+ // drag OpenSSL + WinSock transitively.
+ struct Impl;
+ std::unique_ptr<Impl> impl_;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Transport/StdioTransport.cpp b/windows/Gridex/Services/MCP/Transport/StdioTransport.cpp
index 174cddc..45b28c0 100644
--- a/windows/Gridex/Services/MCP/Transport/StdioTransport.cpp
+++ b/windows/Gridex/Services/MCP/Transport/StdioTransport.cpp
@@ -1,27 +1,89 @@
//
// StdioTransport.cpp
//
-// Reading:
-// stdin is assumed to carry one JSON object per line (MCP
-// newline-delimited framing). Empty lines are skipped. Malformed
-// JSON triggers a parseError response with id=null.
-//
-// Writing:
-// A single mutex serializes stdout writes; flush after every
-// line so the client sees responses immediately.
+// Uses Win32 ReadFile/WriteFile on GetStdHandle instead of
+// std::cin/std::cout. The Gridex EXE is GUI subsystem so the C
+// runtime does not auto-wire stdio — we must talk to the inherited
+// handles directly.
//
// Threading:
-// Reader runs on a dedicated std::thread. The caller's
-// RequestHandler is invoked synchronously from that thread —
-// long-running handlers should dispatch to a worker pool to
-// avoid stalling the read loop.
+// Reader runs on a dedicated std::thread. RequestHandler is
+// invoked inline — handlers that do heavy work should marshal
+// off-thread themselves.
+//
+// Framing:
+// Newline-delimited JSON. One request per line. Binary-safe
+// enough for JSON (we stop at '\n').
#include "StdioTransport.h"
-#include <iostream>
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <shlobj.h>
#include <string>
+#include <fstream>
+
+// Diagnostic: mirror every stdio event to
+// %APPDATA%\Gridex\mcp-stdio-debug.log. Flip kDebug to true while
+// bringing up a new MCP client; keep false in ship builds so we
+// don't spam the audit folder.
+static constexpr bool kDebug = false;
+
+static void dbg(const std::string& line)
+{
+ if (!kDebug) return;
+ wchar_t* ad = nullptr;
+ if (SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &ad) != S_OK) return;
+ std::wstring dir = std::wstring(ad) + L"\\Gridex";
+ CoTaskMemFree(ad);
+ CreateDirectoryW(dir.c_str(), nullptr);
+ std::ofstream f(dir + L"\\mcp-stdio-debug.log",
+ std::ios::app | std::ios::binary);
+ if (!f.is_open()) return;
+ SYSTEMTIME st; GetSystemTime(&st);
+ char buf[32];
+ snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ ",
+ st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
+ f << buf << line << '\n';
+}
namespace DBModels
{
+ namespace
+ {
+ // Read up to and including a '\n' from `h`. Strip trailing
+ // \r\n. Returns false on EOF or error.
+ bool readLine(HANDLE h, std::string& out)
+ {
+ out.clear();
+ char buf;
+ DWORD got = 0;
+ while (true)
+ {
+ if (!ReadFile(h, &buf, 1, &got, nullptr) || got == 0)
+ return !out.empty(); // final line without newline
+ if (buf == '\n') break;
+ out.push_back(buf);
+ }
+ if (!out.empty() && out.back() == '\r') out.pop_back();
+ return true;
+ }
+
+ void writeAll(HANDLE h, const std::string& s)
+ {
+ const char* p = s.data();
+ size_t rem = s.size();
+ while (rem > 0)
+ {
+ DWORD wrote = 0;
+ if (!WriteFile(h, p, static_cast<DWORD>(rem), &wrote, nullptr) || wrote == 0)
+ return;
+ p += wrote;
+ rem -= wrote;
+ }
+ }
+ }
+
StdioTransport::~StdioTransport()
{
stop();
@@ -41,22 +103,36 @@ namespace DBModels
void StdioTransport::readLoop()
{
+ HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
+ dbg("readLoop start; stdinHandle=" +
+ std::to_string(reinterpret_cast<intptr_t>(in)));
+ if (in == INVALID_HANDLE_VALUE || in == nullptr)
+ {
+ dbg("readLoop: no stdin handle, bailing");
+ running_.store(false);
+ return;
+ }
+
std::string line;
- while (running_.load() && std::getline(std::cin, line))
+ while (running_.load())
{
+ line.clear();
+ if (!readLine(in, line))
+ { dbg("readLoop: EOF"); break; }
if (line.empty()) continue;
- if (!line.empty() && line.back() == '\r') line.pop_back();
+ dbg("readLoop got " + std::to_string(line.size()) + " bytes");
try
{
auto j = nlohmann::json::parse(line);
JSONRPCRequest req;
from_json(j, req);
+ dbg("readLoop dispatching method=" + req.method);
if (handler_) handler_(req);
}
- catch (const std::exception&)
+ catch (const std::exception& e)
{
- // Parse error → reply with null id + -32700 per spec.
+ dbg(std::string("readLoop parse error: ") + e.what());
auto resp = JSONRPCResponse::fail(nullptr, JSONRPCError::parseError());
send(resp);
}
@@ -71,8 +147,11 @@ namespace DBModels
const std::string line = j.dump() + "\n";
std::lock_guard<std::mutex> lk(writeMtx_);
- std::cout.write(line.data(), static_cast<std::streamsize>(line.size()));
- std::cout.flush();
+ HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
+ dbg("send " + std::to_string(line.size()) + " bytes; stdoutHandle=" +
+ std::to_string(reinterpret_cast<intptr_t>(out)));
+ if (out == INVALID_HANDLE_VALUE || out == nullptr) return;
+ writeAll(out, line);
}
void StdioTransport::sendNotification(const std::string& method,
@@ -81,13 +160,13 @@ namespace DBModels
JSONRPCRequest notif;
notif.method = method;
notif.params = params;
- // notifications have no `id`.
nlohmann::json j;
to_json(j, notif);
const std::string line = j.dump() + "\n";
std::lock_guard<std::mutex> lk(writeMtx_);
- std::cout.write(line.data(), static_cast<std::streamsize>(line.size()));
- std::cout.flush();
+ HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
+ if (out == INVALID_HANDLE_VALUE || out == nullptr) return;
+ writeAll(out, line);
}
}