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++

feat(windows): port full MCP Server from macOS (13 tools, stdio+HTTP, 5-tab UI) (#16)

haidang181018114d8ede74
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
new file mode 100644
index 0000000..b12b42f
--- /dev/null
+++ b/.claude/settings.local.json
@@ -0,0 +1,8 @@
+{
+ "permissions": {
+ "allow": [
+ "Bash(powershell.exe -ExecutionPolicy Bypass -Command '& { $msbuild = & '\\\\''C:\\\\Program Files \\(x86\\)\\\\Microsoft Visual Studio\\\\Installer\\\\vswhere.exe'\\\\'' -latest -products * -requires Microsoft.Component.MSBuild -find '\\\\''MSBuild\\\\**\\\\Bin\\\\MSBuild.exe'\\\\'' 2>$null | Select-Object -First 1; if \\($msbuild\\) { Write-Host \"MSBUILD=$msbuild\" } else { Write-Host '\\\\''MSBuild not found'\\\\'' } }')",
+ "Bash(powershell -ExecutionPolicy Bypass -File windows/scripts/build-unpackaged.ps1)"
+ ]
+ }
+}
diff --git a/windows/Gridex/App.xaml.cpp b/windows/Gridex/App.xaml.cpp
index 1fe8d64..5faa2a6 100644
--- a/windows/Gridex/App.xaml.cpp
+++ b/windows/Gridex/App.xaml.cpp
@@ -3,9 +3,15 @@
#include "App.xaml.h"
#include "MainWindow.xaml.h"
#include "UpdateService.h"
+#include "Models/AppSettings.h"
+#include "Services/MCP/MCPServerHost.h"
+#include "Services/TrayIconService.h"
+#include "GridexVersion.h"
#include <shellapi.h>
#include <string>
#include <cwchar>
+#include <condition_variable>
+#include <shlobj.h>
using namespace winrt;
using namespace Microsoft::UI::Xaml;
@@ -84,6 +90,17 @@ namespace winrt::Gridex::implementation
}
HWND App::MainHwnd = nullptr;
+
+ // GRIDEX_VERSION is wide; MCPServer needs narrow for JSON-RPC.
+ static std::string GridexVersionAscii()
+ {
+ std::wstring w(GRIDEX_VERSION);
+ std::string out;
+ out.reserve(w.size());
+ for (wchar_t c : w) out.push_back(static_cast<char>(c & 0x7F));
+ return out;
+ }
+
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
@@ -121,12 +138,110 @@ namespace winrt::Gridex::implementation
/// Invoked when the application is launched.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
+ // Detect `--mcp-stdio` anywhere in the command line. WinUI 3
+ // packs args into `LaunchActivatedEventArgs::Arguments()` but for
+ // unpackaged runs we also look at the Win32 command line.
+ static bool IsMcpStdioMode()
+ {
+ LPWSTR cmd = GetCommandLineW();
+ if (!cmd) return false;
+ int argc = 0;
+ LPWSTR* argv = CommandLineToArgvW(cmd, &argc);
+ if (!argv) return false;
+ bool hit = false;
+ for (int i = 1; i < argc; ++i)
+ if (wcscmp(argv[i], L"--mcp-stdio") == 0) { hit = true; break; }
+ LocalFree(argv);
+ return hit;
+ }
+
void App::OnLaunched([[maybe_unused]] LaunchActivatedEventArgs const& e)
{
+ if (IsMcpStdioMode())
+ {
+ // Headless MCP server mode — spawned by Claude Desktop /
+ // 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.
+
+ // Wrap server bootstrap in try/catch so a constructor
+ // failure (e.g. audit logger can't create its folder,
+ // settings parse error) doesn't abort() the process
+ // before the client sees any response.
+ try
+ {
+ auto s = DBModels::AppSettings::Load();
+ DBModels::MCPServerHost::ensureCreated(
+ s,
+ GridexVersionAscii(),
+ DBModels::MCPTransportMode::Stdio);
+ DBModels::MCPServerHost::start();
+ }
+ catch (...)
+ {
+ ExitProcess(2);
+ }
+
+ // Park the main thread; stdio reader runs on its own
+ // thread inside the server. Exit when the reader thread
+ // signals shutdown (EOF or "shutdown" JSON-RPC).
+ std::mutex mtx; std::condition_variable cv; bool done = false;
+ std::thread waiter([&]{
+ while (true)
+ {
+ 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; }
+ cv.notify_all();
+ });
+ std::unique_lock<std::mutex> lk(mtx);
+ cv.wait(lk, [&]{ return done; });
+ waiter.join();
+ DBModels::MCPServerHost::stop();
+ ExitProcess(0);
+ }
+
window = make<MainWindow>();
window.Activate();
auto windowNative = window.as<IWindowNative>();
windowNative->get_WindowHandle(&MainHwnd);
+
+ // Install the system-tray icon now that MainHwnd is live.
+ // Uses subclassing so tray callbacks land in the existing
+ // WinUI message loop — no second pump required.
+ try { DBModels::TrayIconService::Initialize(MainHwnd); }
+ catch (...) { /* non-fatal */ }
+
+ // Auto-start MCP server if user enabled it last session.
+ // Wrap in try-catch so a startup failure (port 3333 busy,
+ // broken settings, missing OpenSSL for cpp-httplib, etc.)
+ // never blocks the main window from activating. Users can
+ // retry from the MCP Server page after the UI is up.
+ try
+ {
+ auto settings = DBModels::AppSettings::Load();
+ if (settings.mcpEnabled)
+ {
+ DBModels::MCPServerHost::ensureCreated(
+ settings,
+ GridexVersionAscii(),
+ DBModels::MCPTransportMode::HttpOnly);
+ DBModels::MCPServerHost::start();
+ }
+ }
+ catch (...) { /* ignore — UI still shows */ }
}
}
diff --git a/windows/Gridex/AppSettings.cpp b/windows/Gridex/AppSettings.cpp
index 1e9fcdb..80e9e99 100644
--- a/windows/Gridex/AppSettings.cpp
+++ b/windows/Gridex/AppSettings.cpp
@@ -326,6 +326,41 @@ namespace DBModels
s.rowLimit = extractInt(json, L"rowLimit", 100);
s.lastPageBeforeSettings = extractString(json, L"lastPageBeforeSettings");
s.connectionGroups = extractStringArray(json, L"connectionGroups");
+
+ // MCP — all fields optional for forward compat with 0.1.3 settings.
+ s.mcpEnabled = extractBool(json, L"mcpEnabled", false);
+ s.mcpHttpEnabled = extractBool(json, L"mcpHttpEnabled", false);
+ s.mcpHttpPort = extractInt(json, L"mcpHttpPort", 3333);
+ s.mcpAllowRemoteHTTP = extractBool(json, L"mcpAllowRemoteHTTP", false);
+ s.mcpRequireApprovalForWrites = extractBool(json, L"mcpRequireApprovalForWrites", true);
+ s.mcpQueriesPerMinute = extractInt(json, L"mcpQueriesPerMinute", 60);
+ s.mcpQueriesPerHour = extractInt(json, L"mcpQueriesPerHour", 1000);
+ s.mcpWritesPerMinute = extractInt(json, L"mcpWritesPerMinute", 10);
+ s.mcpDdlPerMinute = extractInt(json, L"mcpDdlPerMinute", 1);
+ s.mcpQueryTimeout = extractInt(json, L"mcpQueryTimeout", 30);
+ s.mcpApprovalTimeout = extractInt(json, L"mcpApprovalTimeout", 60);
+ s.mcpConnectionTimeout = extractInt(json, L"mcpConnectionTimeout", 10);
+ s.mcpAuditRetentionDays = extractInt(json, L"mcpAuditRetentionDays", 90);
+ s.mcpAuditMaxSizeMB = extractInt(json, L"mcpAuditMaxSizeMB", 100);
+ // 64-bit unix seconds: extractInt returns 32-bit; for mcpStartTime
+ // we bounce through wide-stoll to cover dates past 2038.
+ {
+ std::wstring needle = L"\"mcpStartTime\":";
+ size_t pos = json.find(needle);
+ if (pos != std::wstring::npos)
+ {
+ pos += needle.size();
+ while (pos < json.size() && (json[pos] == L' ' || json[pos] == L'\t')) pos++;
+ std::wstring num;
+ if (pos < json.size() && (json[pos] == L'-' || iswdigit(json[pos])))
+ {
+ num += json[pos++];
+ while (pos < json.size() && iswdigit(json[pos])) num += json[pos++];
+ }
+ if (!num.empty()) { try { s.mcpStartTime = std::stoll(num); } catch (...) {} }
+ }
+ }
+
return s;
}
@@ -352,7 +387,26 @@ namespace DBModels
if (i > 0) ss << L", ";
ss << L"\"" << escapeJson(connectionGroups[i]) << L"\"";
}
- ss << L"]\n";
+ ss << L"],\n";
+
+ // MCP block. Booleans written as literal true/false; ints
+ // as plain numbers. Group at the end to minimize diff churn
+ // if we add more prefs later.
+ ss << L" \"mcpEnabled\": " << (mcpEnabled ? L"true" : L"false") << L",\n";
+ ss << L" \"mcpHttpEnabled\": " << (mcpHttpEnabled ? L"true" : L"false") << L",\n";
+ ss << L" \"mcpHttpPort\": " << mcpHttpPort << L",\n";
+ ss << L" \"mcpAllowRemoteHTTP\": " << (mcpAllowRemoteHTTP ? L"true" : L"false") << L",\n";
+ ss << L" \"mcpRequireApprovalForWrites\": " << (mcpRequireApprovalForWrites ? L"true" : L"false") << L",\n";
+ ss << L" \"mcpQueriesPerMinute\": " << mcpQueriesPerMinute << L",\n";
+ ss << L" \"mcpQueriesPerHour\": " << mcpQueriesPerHour << L",\n";
+ ss << L" \"mcpWritesPerMinute\": " << mcpWritesPerMinute << L",\n";
+ ss << L" \"mcpDdlPerMinute\": " << mcpDdlPerMinute << L",\n";
+ ss << L" \"mcpQueryTimeout\": " << mcpQueryTimeout << L",\n";
+ ss << L" \"mcpApprovalTimeout\": " << mcpApprovalTimeout << L",\n";
+ ss << L" \"mcpConnectionTimeout\": " << mcpConnectionTimeout << L",\n";
+ ss << L" \"mcpAuditRetentionDays\": " << mcpAuditRetentionDays << L",\n";
+ ss << L" \"mcpAuditMaxSizeMB\": " << mcpAuditMaxSizeMB << L",\n";
+ ss << L" \"mcpStartTime\": " << mcpStartTime << L"\n";
ss << L"}\n";
std::string utf8 = toUtf8(ss.str());
diff --git a/windows/Gridex/ConnectionFormDialog.cpp b/windows/Gridex/ConnectionFormDialog.cpp
index fd576a6..3a90526 100644
--- a/windows/Gridex/ConnectionFormDialog.cpp
+++ b/windows/Gridex/ConnectionFormDialog.cpp
@@ -136,6 +136,11 @@ namespace winrt::Gridex::implementation
auto sslIdx = SslModeInput().SelectedIndex();
config.sslMode = static_cast<DBModels::SSLMode>(sslIdx);
config.sslEnabled = (sslIdx != 1);
+ // MCP access mode — 0=Locked / 1=ReadOnly / 2=ReadWrite,
+ // matches MCPConnectionMode enum ordering.
+ const auto mcpIdx = McpModeInput().SelectedIndex();
+ config.mcpMode = static_cast<DBModels::MCPConnectionMode>(
+ mcpIdx < 0 ? 0 : mcpIdx);
if (dbType_ == DBModels::DatabaseType::SQLite)
config.filePath = std::wstring(FilePathInput().Text());
if (dbType_ == DBModels::DatabaseType::MongoDB)
@@ -188,6 +193,7 @@ namespace winrt::Gridex::implementation
PasswordInput().Password(winrt::hstring(config.password));
DatabaseInput().Text(winrt::hstring(config.database));
SslModeInput().SelectedIndex(static_cast<int>(config.sslMode));
+ McpModeInput().SelectedIndex(static_cast<int>(config.mcpMode));
FilePathInput().Text(winrt::hstring(config.filePath));
UriInput().Text(winrt::hstring(config.connectionUri));
MongoOptionsInput().Text(winrt::hstring(config.mongoOptions));
diff --git a/windows/Gridex/ConnectionFormDialog.xaml b/windows/Gridex/ConnectionFormDialog.xaml
index 77b0cca..37695b3 100644
--- a/windows/Gridex/ConnectionFormDialog.xaml
+++ b/windows/Gridex/ConnectionFormDialog.xaml
@@ -22,6 +22,7 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Row 0: Name + Group -->
@@ -321,6 +322,36 @@
</Grid>
</Grid>
</StackPanel>
+
+ <!-- Row 10: MCP access mode (per-connection). Decides
+ whether the AI (via MCP server) can see / query /
+ modify this connection. Default Locked, user must
+ opt in explicitly. -->
+ <TextBlock Grid.Row="10" Grid.Column="0"
+ Text="MCP access"
+ VerticalAlignment="Center"
+ HorizontalAlignment="Right"
+ Margin="0,0,16,0"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ <Grid Grid.Row="10" Grid.Column="1" Margin="0,0,0,12">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="Auto" />
+ <ColumnDefinition Width="*" />
+ </Grid.ColumnDefinitions>
+ <ComboBox x:Name="McpModeInput" Grid.Column="0"
+ MinWidth="160" SelectedIndex="0">
+ <ComboBoxItem Content="Locked (AI hidden)" />
+ <ComboBoxItem Content="Read-only (AI can query)" />
+ <ComboBoxItem Content="Read-write (AI can modify w/ approval)" />
+ </ComboBox>
+ <TextBlock Grid.Column="1"
+ Margin="12,0,0,0"
+ VerticalAlignment="Center"
+ FontSize="11"
+ TextWrapping="Wrap"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"
+ Text="You can change this later in MCP Server → Connections." />
+ </Grid>
</Grid>
</ScrollViewer>
diff --git a/windows/Gridex/Gridex.items.props b/windows/Gridex/Gridex.items.props
index 6ef0a8d..7fa53bd 100644
--- a/windows/Gridex/Gridex.items.props
+++ b/windows/Gridex/Gridex.items.props
@@ -20,6 +20,57 @@
<ClInclude Include="$(MSBuildThisFileDirectory)Models\RowValue.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\TableInfo.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\QueryParameter.h" />
+ <!-- MCP Phase 1 — core types (header-only, no ClCompile yet). -->
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\MCP\MCPConnectionMode.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\MCP\MCPPermissionTier.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\MCP\MCPErrorCode.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\MCP\MCPProtocol.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\MCP\MCPServerInfo.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\MCP\MCPToolDefinition.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\MCP\MCPToolError.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\MCP\MCPAuditEntry.h" />
+ <!-- MCP Phase 2 — security. -->
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPSQLSanitizer.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPIdentifierValidator.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPPermissionResult.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPPermissionEngine.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPRateLimiter.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPApprovalGate.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPRowCountEstimator.h" />
+ <!-- MCP Phase 3 — audit. -->
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Audit\MCPAuditLogger.h" />
+ <!-- MCP Phase 4 — transport + server. HTTP transport TBD (Phase 4d). -->
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\MCPConnectionPool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\MCPServer.h" />
+ <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" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\MCPBuiltinTools.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\ListConnectionsTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\ListTablesTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\DescribeTableTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\ListSchemasTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\ListRelationshipsTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\GetSampleRowsTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier2\QueryTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier2\ExplainQueryTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier2\SearchAcrossTablesTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier3\InsertRowsTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier3\UpdateRowsTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier3\DeleteRowsTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier3\ExecuteWriteQueryTool.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\MCP\MCPServerHost.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\TrayIconService.h" />
+ <!-- Connection importers — TablePlus / DBeaver / DataGrip / Navicat. -->
+ <ClInclude Include="$(MSBuildThisFileDirectory)Models\Import\ImportedConnection.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\Import\DBeaverImporter.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\Import\DataGripImporter.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\Import\NavicatImporter.h" />
+ <ClInclude Include="$(MSBuildThisFileDirectory)Services\Import\TablePlusImporter.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\DatabaseAdapter.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\ConnectionManager.h" />
<ClInclude Include="$(MSBuildThisFileDirectory)Models\PostgreSQLAdapter.h" />
@@ -43,6 +94,10 @@
<DependentUpon>SettingsPage.xaml</DependentUpon>
<SubType>Code</SubType>
</ClInclude>
+ <ClInclude Include="$(MSBuildThisFileDirectory)MCPPage.h">
+ <DependentUpon>MCPPage.xaml</DependentUpon>
+ <SubType>Code</SubType>
+ </ClInclude>
<ClInclude Include="$(MSBuildThisFileDirectory)ConnectionCard.h">
<DependentUpon>ConnectionCard.xaml</DependentUpon>
<SubType>Code</SubType>
@@ -150,6 +205,9 @@
<Page Include="$(MSBuildThisFileDirectory)SettingsPage.xaml">
<SubType>Designer</SubType>
</Page>
+ <Page Include="$(MSBuildThisFileDirectory)MCPPage.xaml">
+ <SubType>Designer</SubType>
+ </Page>
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(MSBuildThisFileDirectory)ConnectionCard.cpp">
@@ -258,6 +316,109 @@
<ClCompile Include="$(MSBuildThisFileDirectory)DumpRestoreService.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPSQLSanitizer.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPIdentifierValidator.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPPermissionEngine.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPRateLimiter.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPApprovalGate.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Security\MCPRowCountEstimator.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Audit\MCPAuditLogger.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\MCPConnectionPool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\MCPServer.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\MCPTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\MCPToolRegistry.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <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>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\ListConnectionsTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\ListTablesTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\DescribeTableTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\ListSchemasTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\ListRelationshipsTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier1\GetSampleRowsTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier2\QueryTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier2\ExplainQueryTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier2\SearchAcrossTablesTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier3\InsertRowsTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier3\UpdateRowsTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier3\DeleteRowsTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\Tools\Tier3\ExecuteWriteQueryTool.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\MCP\MCPServerHost.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\TrayIconService.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\Import\DBeaverImporter.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\Import\DataGripImporter.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\Import\NavicatImporter.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="$(MSBuildThisFileDirectory)Services\Import\TablePlusImporter.cpp">
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ </ClCompile>
+ <!-- MCP Phase 6 UI — WinUI 3 Page with 5 tabs. -->
+ <ClCompile Include="$(MSBuildThisFileDirectory)MCPPage.cpp">
+ <DependentUpon>MCPPage.xaml</DependentUpon>
+ </ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)ERDiagramService.cpp">
<PrecompiledHeader>NotUsing</PrecompiledHeader>
</ClCompile>
@@ -333,5 +494,9 @@
<DependentUpon>SettingsPage.xaml</DependentUpon>
<SubType>Code</SubType>
</Midl>
+ <Midl Include="$(MSBuildThisFileDirectory)MCPPage.idl">
+ <DependentUpon>MCPPage.xaml</DependentUpon>
+ <SubType>Code</SubType>
+ </Midl>
</ItemGroup>
</Project>
diff --git a/windows/Gridex/HomePage.cpp b/windows/Gridex/HomePage.cpp
index 834c7cb..11078e6 100644
--- a/windows/Gridex/HomePage.cpp
+++ b/windows/Gridex/HomePage.cpp
@@ -17,6 +17,12 @@
#include "App.xaml.h"
#include "Models/ConnectionStore.h"
#include "Models/ConnectionManager.h"
+#include "Services/Import/DBeaverImporter.h"
+#include "Services/Import/DataGripImporter.h"
+#include "Services/Import/NavicatImporter.h"
+#include "Services/Import/TablePlusImporter.h"
+#include <winrt/Microsoft.Windows.Storage.Pickers.h>
+#include <random>
namespace winrt::Gridex::implementation
{
@@ -178,6 +184,11 @@ namespace winrt::Gridex::implementation
void HomePage::RefreshList(const std::wstring& searchQuery)
{
+ // Always re-read from the store so imports / edits / deletes
+ // don't need a page-reload to show. Cheap: ConnectionStore::Load
+ // reads one SQLite table and decrypts passwords — sub-ms for
+ // typical <200 connection counts.
+ allConnections_ = DBModels::ConnectionStore::Load();
ConnectionsListView().Items().Clear();
auto matches = [&](const DBModels::ConnectionConfig& conn) -> bool
@@ -467,6 +478,29 @@ namespace winrt::Gridex::implementation
frame.Navigate(pageType);
}
+ void HomePage::OpenMcp_Click(
+ winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)
+ {
+ muxc::Frame frame{ nullptr };
+ auto fe = this->try_as<mux::FrameworkElement>();
+ while (fe)
+ {
+ if (auto f = fe.try_as<muxc::Frame>()) { frame = f; break; }
+ fe = fe.Parent().try_as<mux::FrameworkElement>();
+ }
+ if (!frame) frame = this->Frame();
+ if (!frame) return;
+
+ auto s = DBModels::AppSettings::Load();
+ s.lastPageBeforeSettings = L"Gridex.HomePage";
+ s.Save();
+
+ winrt::Windows::UI::Xaml::Interop::TypeName pageType;
+ pageType.Name = L"Gridex.MCPPage";
+ pageType.Kind = winrt::Windows::UI::Xaml::Interop::TypeKind::Metadata;
+ frame.Navigate(pageType);
+ }
+
void HomePage::ConnectionItem_Click(
winrt::Windows::Foundation::IInspectable const&, muxc::ItemClickEventArgs const& e)
{
@@ -533,4 +567,231 @@ namespace winrt::Gridex::implementation
{
RefreshList(std::wstring(sender.Text()));
}
+
+ // ── Import Connections wizard ──────────────────────────────
+ // Builds a ContentDialog with a source switcher + list of
+ // ImportedConnections with per-row CheckBoxes. Import button
+ // writes selected rows into ConnectionStore and refreshes the
+ // sidebar list. Navicat branches through an .ncx file picker.
+
+ namespace
+ {
+ std::wstring newConnectionId()
+ {
+ std::random_device rd;
+ std::mt19937_64 gen(rd());
+ std::uniform_int_distribution<uint64_t> dist;
+ wchar_t buf[33];
+ swprintf_s(buf, 33, L"%016llx%016llx",
+ (unsigned long long)dist(gen), (unsigned long long)dist(gen));
+ return buf;
+ }
+
+ // Shared builder for a single importer-result row. The
+ // CheckBox instance is stored in `row.first` so the Import
+ // button can poll IsChecked when the user clicks confirm.
+ std::pair<muxc::CheckBox, winrt::Microsoft::UI::Xaml::Controls::Border>
+ buildImportedRow(const DBModels::ImportedConnection& c)
+ {
+ using namespace winrt::Microsoft::UI::Xaml;
+ using namespace winrt::Microsoft::UI::Xaml::Controls;
+
+ muxc::Grid row;
+ row.Padding(Thickness{ 8, 6, 8, 6 });
+ row.ColumnSpacing(10);
+
+ ColumnDefinition c0, c1, c2;
+ c0.Width(GridLengthHelper::FromPixels(36));
+ c1.Width(GridLengthHelper::FromValueAndType(1, GridUnitType::Star));
+ c2.Width(GridLengthHelper::FromPixels(90));
+ row.ColumnDefinitions().Append(c0);
+ row.ColumnDefinitions().Append(c1);
+ row.ColumnDefinitions().Append(c2);
+
+ muxc::CheckBox chk; chk.IsChecked(true);
+ muxc::Grid::SetColumn(chk, 0); row.Children().Append(chk);
+
+ muxc::StackPanel sp; sp.Spacing(2);
+ muxc::TextBlock name; name.Text(winrt::hstring(c.name));
+ name.FontSize(13); name.FontWeight(Windows::UI::Text::FontWeights::SemiBold());
+ sp.Children().Append(name);
+ std::wstring sub = !c.host.empty()
+ ? c.host + (c.port.has_value() ? L":" + std::to_wstring(*c.port) : L"")
+ : c.filePath;
+ if (!c.database.empty()) sub += L" / " + c.database;
+ if (sub.empty()) sub = L"(no host)";
+ muxc::TextBlock subt; subt.Text(winrt::hstring(sub));
+ subt.FontSize(11);
+ subt.Foreground(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(255, 150, 150, 150)));
+ sp.Children().Append(subt);
+ muxc::Grid::SetColumn(sp, 1); row.Children().Append(sp);
+
+ muxc::TextBlock type; type.Text(winrt::hstring(
+ DBModels::DatabaseTypeDisplayName(c.databaseType)));
+ type.FontSize(11); type.VerticalAlignment(VerticalAlignment::Center);
+ type.Foreground(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(255, 150, 150, 150)));
+ muxc::Grid::SetColumn(type, 2); row.Children().Append(type);
+
+ muxc::Border wrap;
+ wrap.Child(row);
+ wrap.BorderBrush(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(30, 128, 128, 128)));
+ wrap.BorderThickness(Thickness{ 0, 0, 0, 1 });
+ return { chk, wrap };
+ }
+ }
+
+ winrt::fire_and_forget HomePage::ImportConnections_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ mux::RoutedEventArgs const&)
+ {
+ auto self = get_strong();
+
+ // Dialog + source ComboBox + rows container.
+ muxc::ContentDialog dlg;
+ dlg.Title(winrt::box_value(winrt::hstring(L"Import Connections")));
+ dlg.PrimaryButtonText(L"Import Selected");
+ dlg.CloseButtonText(L"Cancel");
+ dlg.DefaultButton(muxc::ContentDialogButton::Primary);
+ dlg.XamlRoot(this->XamlRoot());
+ dlg.Resources().Insert(winrt::box_value(L"ContentDialogMaxWidth"), winrt::box_value(720.0));
+
+ muxc::StackPanel content; content.Spacing(10); content.MinWidth(520);
+
+ muxc::TextBlock intro;
+ intro.Text(L"Pick a source, review detected connections, then Import.");
+ intro.FontSize(12);
+ intro.Foreground(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(255, 150, 150, 150)));
+ content.Children().Append(intro);
+
+ muxc::ComboBox sourceCombo; sourceCombo.MinWidth(240);
+ auto addSource = [&](const wchar_t* label, bool installed)
+ {
+ muxc::ComboBoxItem item;
+ item.Content(winrt::box_value(winrt::hstring(
+ installed ? label : std::wstring(label) + L" (not detected)")));
+ sourceCombo.Items().Append(item);
+ };
+ // Kept the list conservative: no .ncx file-picker branch
+ // — that needed an inner coroutine + cross-frame captures
+ // that proved crash-prone. Users who need .ncx can import
+ // via CLI or a future dedicated entry.
+ addSource(L"DBeaver", DBModels::DBeaverImporter::isInstalled());
+ addSource(L"DataGrip", DBModels::DataGripImporter::isInstalled());
+ addSource(L"Navicat", DBModels::NavicatImporter::isInstalled());
+ addSource(L"TablePlus", DBModels::TablePlusImporter::isInstalled());
+ content.Children().Append(sourceCombo);
+
+ muxc::TextBlock status; status.FontSize(11);
+ status.Foreground(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(255, 180, 180, 180)));
+ content.Children().Append(status);
+
+ muxc::ScrollViewer sv;
+ sv.HorizontalScrollMode(muxc::ScrollMode::Disabled);
+ sv.VerticalScrollBarVisibility(muxc::ScrollBarVisibility::Auto);
+ sv.MaxHeight(360);
+ muxc::StackPanel rows; rows.Spacing(0);
+ sv.Content(rows);
+ content.Children().Append(sv);
+
+ dlg.Content(content);
+
+ // State shared with the SelectionChanged lambda. shared_ptr
+ // so the lambda's copy of the handles stays valid even if
+ // the outer coroutine is suspended in ShowAsync.
+ auto imported = std::make_shared<std::vector<DBModels::ImportedConnection>>();
+ auto checks = std::make_shared<std::vector<muxc::CheckBox>>();
+
+ // Synchronous scan — no coroutine, no reference captures to
+ // locals. Everything the lambda needs is captured by value.
+ auto loadSource = [imported, checks, rows, status](int idx)
+ {
+ try
+ {
+ imported->clear();
+ checks->clear();
+ rows.Children().Clear();
+ status.Text(L"Scanning...");
+
+ // Indices in addSource() order: 0 DBeaver, 1 DataGrip,
+ // 2 Navicat (registry), 3 TablePlus.
+ if (idx == 0) *imported = DBModels::DBeaverImporter::importConnections();
+ else if (idx == 1) *imported = DBModels::DataGripImporter::importConnections();
+ else if (idx == 2) *imported = DBModels::NavicatImporter::importConnections();
+ else if (idx == 3) *imported = DBModels::TablePlusImporter::importConnections();
+
+ if (imported->empty())
+ {
+ status.Text(L"No connections detected.");
+ return;
+ }
+ status.Text(winrt::hstring(
+ std::to_wstring(imported->size()) +
+ L" connection(s) detected. Untick any you want to skip."));
+ for (const auto& c : *imported)
+ {
+ auto [chk, wrap] = buildImportedRow(c);
+ checks->push_back(chk);
+ rows.Children().Append(wrap);
+ }
+ }
+ catch (const std::exception& e)
+ {
+ std::string msg = e.what();
+ status.Text(winrt::hstring(L"Error: " +
+ std::wstring(msg.begin(), msg.end())));
+ }
+ catch (...) { status.Text(L"Scan failed."); }
+ };
+
+ // Attach handler THEN seed the selection so the handler
+ // fires exactly once during visible-state setup instead of
+ // racing with a separate manual scan.
+ sourceCombo.SelectionChanged(
+ [loadSource](auto&& s, auto&&)
+ {
+ if (auto cb = s.try_as<muxc::ComboBox>())
+ loadSource(cb.SelectedIndex());
+ });
+ sourceCombo.SelectedIndex(0);
+
+ // Show dialog; on Primary, snapshot selections immediately
+ // (before the dialog tears its controls down) and then write
+ // to the store + refresh the sidebar.
+ muxc::ContentDialogResult result{ muxc::ContentDialogResult::None };
+ try { result = co_await dlg.ShowAsync(); }
+ catch (...) { co_return; }
+ if (result != muxc::ContentDialogResult::Primary) co_return;
+
+ std::vector<size_t> selected;
+ for (size_t i = 0; i < imported->size() && i < checks->size(); ++i)
+ {
+ try
+ {
+ auto ib = (*checks)[i].IsChecked();
+ if (ib && ib.Value()) selected.push_back(i);
+ }
+ catch (...) { /* control detached */ }
+ }
+
+ int added = 0;
+ for (size_t i : selected)
+ {
+ try
+ {
+ auto cfg = (*imported)[i].toConnectionConfig();
+ if (cfg.id.empty()) cfg.id = newConnectionId();
+ DBModels::ConnectionStore::Save(cfg);
+ ++added;
+ }
+ catch (...) { /* skip one bad row, keep the batch */ }
+ }
+
+ try { RefreshList(); } catch (...) {}
+ (void)added; // feedback is the sidebar update
+ }
}
diff --git a/windows/Gridex/HomePage.h b/windows/Gridex/HomePage.h
index befa32f..286394a 100644
--- a/windows/Gridex/HomePage.h
+++ b/windows/Gridex/HomePage.h
@@ -20,6 +20,16 @@ namespace winrt::Gridex::implementation
void Settings_Click(
winrt::Windows::Foundation::IInspectable const& sender,
winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+ void OpenMcp_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ // Opens the import wizard for TablePlus / DBeaver /
+ // DataGrip / Navicat connections. See ImportConnections.cpp
+ // for the dialog build-up; too much UI code to keep inline.
+ winrt::fire_and_forget ImportConnections_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
void ConnectionItem_Click(
winrt::Windows::Foundation::IInspectable const& sender,
winrt::Microsoft::UI::Xaml::Controls::ItemClickEventArgs const& e);
diff --git a/windows/Gridex/HomePage.xaml b/windows/Gridex/HomePage.xaml
index 70b3a57..a5ecc3e 100644
--- a/windows/Gridex/HomePage.xaml
+++ b/windows/Gridex/HomePage.xaml
@@ -52,6 +52,20 @@
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</StackPanel>
</Button>
+ <Button HorizontalAlignment="Stretch"
+ HorizontalContentAlignment="Left"
+ Padding="8,8"
+ Background="Transparent"
+ BorderThickness="0"
+ Click="ImportConnections_Click"
+ ToolTipService.ToolTip="Import connections from TablePlus / DBeaver / DataGrip / Navicat">
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <FontIcon Glyph="&#xE8B5;" FontSize="14"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ <TextBlock Text="Import Connections"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ </StackPanel>
+ </Button>
<Button HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
Padding="8,8"
@@ -65,6 +79,20 @@
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</StackPanel>
</Button>
+ <Button HorizontalAlignment="Stretch"
+ HorizontalContentAlignment="Left"
+ Padding="8,8"
+ Background="Transparent"
+ BorderThickness="0"
+ Click="OpenMcp_Click"
+ ToolTipService.ToolTip="MCP Server — let AI clients query your databases">
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <FontIcon Glyph="&#xE703;" FontSize="14"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ <TextBlock Text="MCP Server"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ </StackPanel>
+ </Button>
<Button HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
Padding="8,8"
diff --git a/windows/Gridex/MCPPage.cpp b/windows/Gridex/MCPPage.cpp
new file mode 100644
index 0000000..63b521c
--- /dev/null
+++ b/windows/Gridex/MCPPage.cpp
@@ -0,0 +1,1207 @@
+#include "pch.h"
+#include "xaml-includes.h"
+#include "MCPPage.h"
+#if __has_include("MCPPage.g.cpp")
+#include "MCPPage.g.cpp"
+#endif
+
+#include "Models/AppSettings.h"
+#include "Models/ConnectionStore.h"
+#include "Services/MCP/MCPServerHost.h"
+#include "Services/MCP/Audit/MCPAuditLogger.h"
+#include "Services/MCP/Tools/MCPToolHelpers.h"
+#include "Services/TrayIconService.h"
+#include "GridexVersion.h"
+#include <winrt/Windows.ApplicationModel.DataTransfer.h>
+#include <winrt/Windows.UI.h>
+#include <winrt/Microsoft.UI.Xaml.Shapes.h>
+#include <winrt/Windows.UI.Text.h>
+#include <nlohmann/json.hpp>
+#include <fstream>
+#include <shlobj.h>
+#include <algorithm>
+
+namespace winrt::Gridex::implementation
+{
+ namespace mux = winrt::Microsoft::UI::Xaml;
+ namespace muxc = winrt::Microsoft::UI::Xaml::Controls;
+ namespace wadt = winrt::Windows::ApplicationModel::DataTransfer;
+
+ // GRIDEX_VERSION is a wide-string literal in GridexVersion.h — we
+ // need the server version as UTF-8 for the JSON handshake.
+ static std::string versionUtf8()
+ {
+ std::wstring w(GRIDEX_VERSION);
+ std::string out;
+ out.reserve(w.size());
+ for (wchar_t c : w) out.push_back(static_cast<char>(c & 0x7F));
+ return out;
+ }
+
+ MCPPage::MCPPage()
+ {
+ InitializeComponent();
+
+ // Only RefreshUI runs on Loaded — it populates controls on
+ // the Overview + Setup + Config tabs, which are all realized
+ // by the initial Pivot render. Connections + Activity tabs
+ // use Pivot's lazy-load, so their controls are nullptr until
+ // the user selects those tabs. Tabs_SelectionChanged handles
+ // the deferred refresh safely.
+ this->Loaded([this](auto&&, auto&&) {
+ try { RefreshUI(); }
+ catch (...) { /* never block page from showing */ }
+
+ // 1 Hz uptime tick — only repaints the Overview subtitle
+ // so we don't churn Config/Connections rebuilds.
+ try
+ {
+ uptimeTimer_ = mux::DispatcherTimer();
+ uptimeTimer_.Interval(winrt::Windows::Foundation::TimeSpan{
+ std::chrono::seconds(1) });
+ uptimeTimer_.Tick([this](auto&&, auto&&) {
+ try { RefreshOverviewUptime(); } catch (...) {}
+ });
+ uptimeTimer_.Start();
+ }
+ catch (...) {}
+ });
+ this->Unloaded([this](auto&&, auto&&) {
+ if (uptimeTimer_) { uptimeTimer_.Stop(); uptimeTimer_ = nullptr; }
+ });
+ }
+
+ void MCPPage::RefreshUI()
+ {
+ // Pivot lazy-loads PivotItem content, so any control whose
+ // tab isn't realized yet will be nullptr. We null-guard each
+ // group so Refresh can safely be called when only some of
+ // the tabs have been materialized.
+ auto settings = DBModels::AppSettings::Load();
+
+ // ── Overview: Access counts + status + tools ────────────
+ {
+ int locked = 0, ro = 0, rw = 0;
+ auto configs = DBModels::ConnectionStore::Load();
+ for (const auto& c : configs)
+ {
+ switch (c.mcpMode)
+ {
+ case DBModels::MCPConnectionMode::Locked: ++locked; break;
+ case DBModels::MCPConnectionMode::ReadOnly: ++ro; break;
+ case DBModels::MCPConnectionMode::ReadWrite: ++rw; break;
+ }
+ }
+ if (LockedCount()) LockedCount().Text(winrt::hstring(std::to_wstring(locked)));
+ if (ReadOnlyCount()) ReadOnlyCount().Text(winrt::hstring(std::to_wstring(ro)));
+ if (ReadWriteCount()) ReadWriteCount().Text(winrt::hstring(std::to_wstring(rw)));
+ }
+
+ auto srv = DBModels::MCPServerHost::instance();
+ const bool running = srv && srv->isRunning();
+ ApplyStartStopButton(running);
+ if (ToolsCountText())
+ {
+ if (running)
+ {
+ const auto tools = srv->toolRegistry().definitions().size();
+ ToolsCountText().Text(winrt::hstring(std::to_wstring(tools) + L" tools"));
+ }
+ else
+ {
+ ToolsCountText().Text(L"0 tools (server stopped)");
+ }
+ }
+
+ // Overview: uptime subtitle + recent activity list.
+ RefreshOverviewUptime();
+
+ if (auto recent = RecentActivityPanel())
+ {
+ recent.Children().Clear();
+ std::vector<DBModels::MCPAuditEntry> last;
+ try
+ {
+ if (srv)
+ last = srv->auditLogger().recentEntries(5);
+ else
+ {
+ DBModels::MCPAuditLogger tmp(
+ settings.mcpAuditMaxSizeMB, settings.mcpAuditRetentionDays);
+ last = tmp.recentEntries(5);
+ }
+ }
+ catch (...) {}
+
+ if (last.empty())
+ {
+ winrt::Microsoft::UI::Xaml::Controls::TextBlock empty;
+ empty.Text(L"No activity yet");
+ empty.FontSize(12);
+ empty.Foreground(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(255, 150, 150, 150)));
+ recent.Children().Append(empty);
+ }
+ else
+ {
+ for (const auto& e : last)
+ {
+ winrt::Microsoft::UI::Xaml::Controls::Grid row;
+ row.ColumnSpacing(8);
+ winrt::Microsoft::UI::Xaml::Controls::ColumnDefinition c0, c1, c2;
+ c0.Width(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromValueAndType(
+ 1, winrt::Microsoft::UI::Xaml::GridUnitType::Star));
+ c1.Width(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromPixels(60));
+ c2.Width(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromPixels(70));
+ row.ColumnDefinitions().Append(c0);
+ row.ColumnDefinitions().Append(c1);
+ row.ColumnDefinitions().Append(c2);
+
+ winrt::Microsoft::UI::Xaml::Controls::TextBlock tool;
+ tool.Text(winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(e.tool)));
+ tool.FontSize(12);
+ tool.FontFamily(winrt::Microsoft::UI::Xaml::Media::FontFamily(L"Consolas"));
+ winrt::Microsoft::UI::Xaml::Controls::Grid::SetColumn(tool, 0);
+ row.Children().Append(tool);
+
+ winrt::Microsoft::UI::Xaml::Controls::TextBlock status;
+ status.FontSize(11);
+ const bool ok = e.result.status == DBModels::MCPAuditStatus::Success;
+ status.Text(ok ? L"success" : (e.result.status == DBModels::MCPAuditStatus::Error ? L"error" : L"denied"));
+ status.Foreground(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(
+ 255,
+ ok ? 46 : 220,
+ ok ? 139 : 53,
+ ok ? 87 : 69)));
+ winrt::Microsoft::UI::Xaml::Controls::Grid::SetColumn(status, 1);
+ row.Children().Append(status);
+
+ winrt::Microsoft::UI::Xaml::Controls::TextBlock dur;
+ dur.Text(winrt::hstring(std::to_wstring(e.result.durationMs) + L"ms"));
+ dur.FontSize(11);
+ dur.FontFamily(winrt::Microsoft::UI::Xaml::Media::FontFamily(L"Consolas"));
+ dur.Foreground(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(255, 150, 150, 150)));
+ winrt::Microsoft::UI::Xaml::Controls::Grid::SetColumn(dur, 2);
+ row.Children().Append(dur);
+
+ recent.Children().Append(row);
+ }
+ if (auto countLbl = RecentActivityCount())
+ countLbl.Text(winrt::hstring(std::to_wstring(last.size()) + L" events"));
+ }
+ }
+
+ // ── Config tab — only touch if realized ─────────────────
+ if (HttpToggle())
+ {
+ HttpToggle().IsOn(settings.mcpHttpEnabled);
+ HttpPortBox().Value(static_cast<double>(settings.mcpHttpPort));
+ HttpPortRow().Visibility(settings.mcpHttpEnabled
+ ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+ QpmBox().Value(static_cast<double>(settings.mcpQueriesPerMinute));
+ 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);
+ }
+
+ // ── Setup tab — only touch if realized ──────────────────
+ // Re-renders preview + path + button label for the
+ // currently-selected client in ClientPicker.
+ if (SetupConfigBox()) RenderSetupForSelectedClient();
+ }
+
+ void MCPPage::ApplyStartStopButton(bool running)
+ {
+ // Overview is the first Pivot tab so StartStopBtn is always
+ // realized at page Loaded — but guard anyway so this helper
+ // stays safe to call from any refresh path.
+ if (!StartStopBtn()) return;
+ StartStopBtn().Content(
+ winrt::box_value(winrt::hstring(running ? L"Stop Server" : L"Start Server")));
+ StatusText().Text(running ? L"Running" : L"Stopped");
+ RunningTitle().Text(running
+ ? L"MCP Server is running" : L"MCP Server is stopped");
+ RunningSubtitle().Text(running
+ ? L"AI clients can now see Gridex as an MCP server."
+ : L"Enable below to let AI clients connect.");
+ StatusDot().Fill(
+ mux::Media::SolidColorBrush(
+ winrt::Windows::UI::Colors::Gray()));
+ // Green when running.
+ if (running)
+ {
+ StatusDot().Fill(
+ mux::Media::SolidColorBrush(
+ winrt::Windows::UI::ColorHelper::FromArgb(255, 76, 175, 80)));
+ }
+ }
+
+ void MCPPage::Back_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ if (auto frame = this->Frame())
+ {
+ if (frame.CanGoBack()) frame.GoBack();
+ }
+ }
+
+ void MCPPage::StartStop_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ auto settings = DBModels::AppSettings::Load();
+ auto srv = DBModels::MCPServerHost::instance();
+
+ if (srv && srv->isRunning())
+ {
+ // Stop.
+ DBModels::MCPServerHost::stop();
+ settings.mcpEnabled = false;
+ settings.mcpStartTime = 0; // clear uptime anchor
+ settings.Save();
+ }
+ else
+ {
+ // Start — always in HttpOnly mode from the GUI. The
+ // --mcp-stdio CLI path uses a separate bootstrap.
+ DBModels::MCPServerHost::ensureCreated(
+ settings,
+ versionUtf8(),
+ DBModels::MCPTransportMode::HttpOnly);
+
+ // Hook XamlRoot + dispatcher so approval dialogs can open.
+ auto running = DBModels::MCPServerHost::instance();
+ if (running)
+ {
+ auto content = this->XamlRoot();
+ // Forward pointers as void* — MCPApprovalGate stores
+ // winrt handles internally. We pass the same object
+ // each time; lifetime outlives the server.
+ static winrt::Microsoft::UI::Dispatching::DispatcherQueue dq{ nullptr };
+ static winrt::Microsoft::UI::Xaml::XamlRoot xr{ nullptr };
+ dq = this->DispatcherQueue();
+ xr = content;
+ running->setUIContext(&dq, &xr);
+ }
+
+ DBModels::MCPServerHost::start();
+ settings.mcpEnabled = true;
+ // Stamp mcpStartTime so the Overview uptime counter has
+ // an anchor. Reset on stop below.
+ settings.mcpStartTime = static_cast<int64_t>(
+ std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count());
+ settings.Save();
+ }
+ DBModels::TrayIconService::Refresh();
+ RefreshUI();
+ }
+
+ void MCPPage::HttpToggle_Toggled(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ const bool on = HttpToggle().IsOn();
+ HttpPortRow().Visibility(on
+ ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+
+ // Persist immediately — toggle sits on the Overview tab,
+ // where there is no Save button. Previously the flag only
+ // lived in the control state and got lost on navigation.
+ auto s = DBModels::AppSettings::Load();
+ if (s.mcpHttpEnabled != on)
+ {
+ s.mcpHttpEnabled = on;
+ s.Save();
+ }
+
+ // Hint to restart the server if the flag changed while
+ // something is already running — the HTTP listener won't
+ // hot-swap otherwise.
+ if (auto srv = DBModels::MCPServerHost::instance();
+ srv && srv->isRunning())
+ {
+ if (auto sub = RunningSubtitle())
+ sub.Text(L"Restart the server to apply the HTTP toggle.");
+ }
+ }
+
+ void MCPPage::HttpPortBox_ValueChanged(
+ winrt::Microsoft::UI::Xaml::Controls::NumberBox const& sender,
+ winrt::Microsoft::UI::Xaml::Controls::NumberBoxValueChangedEventArgs const&)
+ {
+ const double v = sender.Value();
+ if (std::isnan(v) || v < 1024 || v > 65535) return;
+ const int port = static_cast<int>(v);
+ auto s = DBModels::AppSettings::Load();
+ if (s.mcpHttpPort != port)
+ {
+ s.mcpHttpPort = port;
+ s.Save();
+ if (auto srv = DBModels::MCPServerHost::instance();
+ srv && srv->isRunning())
+ {
+ if (auto sub = RunningSubtitle())
+ sub.Text(L"Restart the server to apply the new HTTP port.");
+ }
+ }
+ }
+
+ void MCPPage::CopyConfig_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ wadt::DataPackage pkg;
+ pkg.SetText(SetupConfigBox().Text());
+ wadt::Clipboard::SetContent(pkg);
+ }
+
+ void MCPPage::SaveConfig_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ auto s = DBModels::AppSettings::Load();
+ s.mcpHttpEnabled = HttpToggle().IsOn();
+ s.mcpHttpPort = static_cast<int>(HttpPortBox().Value());
+ s.mcpQueriesPerMinute = static_cast<int>(QpmBox().Value());
+ 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.
+ // ── AI-client registry ───────────────────────────────────
+ // Mirrors macOS MCPClientType. Each entry describes where the
+ // config file lives + how to build the mcpServers.gridex entry
+ // (stdio exe or HTTP url). Paths accept env-var placeholders
+ // which expandEnv() resolves via ExpandEnvironmentStringsW.
+ namespace
+ {
+ struct McpClient
+ {
+ std::wstring displayName;
+ std::wstring configPath; // may contain %APPDATA% / %USERPROFILE%
+ bool preferHttp = false; // Claude Code / Gemini CLI honor HTTP if enabled
+ };
+
+ const std::vector<McpClient>& mcpClients()
+ {
+ static const std::vector<McpClient> v = {
+ { L"Claude Desktop",
+ L"%APPDATA%\\Claude\\claude_desktop_config.json", false },
+ { L"Claude Code (CLI / CCD)",
+ L"%USERPROFILE%\\.claude.json", true },
+ { L"Cursor",
+ L"%USERPROFILE%\\.cursor\\mcp.json", false },
+ { L"Windsurf",
+ L"%USERPROFILE%\\.windsurf\\mcp.json", false },
+ { L"Gemini CLI",
+ L"%USERPROFILE%\\.gemini\\settings.json", true }
+ };
+ return v;
+ }
+
+ std::wstring expandEnv(const std::wstring& in)
+ {
+ DWORD needed = ExpandEnvironmentStringsW(in.c_str(), nullptr, 0);
+ if (needed == 0) return in;
+ std::wstring out(needed, L'\0');
+ ExpandEnvironmentStringsW(in.c_str(), &out[0], needed);
+ if (!out.empty() && out.back() == L'\0') out.pop_back();
+ return out;
+ }
+
+ std::string wideToUtf8(const std::wstring& w)
+ {
+ if (w.empty()) return {};
+ int sz = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(),
+ nullptr, 0, nullptr, nullptr);
+ std::string out(sz, '\0');
+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(),
+ &out[0], sz, nullptr, nullptr);
+ return out;
+ }
+
+ // Per-client JSON entry. Clients that prefer HTTP (Claude
+ // Code, Gemini) get {"url": "..."} when the HTTP transport
+ // toggle is on; everyone else always gets the stdio form.
+ nlohmann::json gridexEntryFor(const McpClient& c, int httpPort, bool httpEnabled)
+ {
+ wchar_t exePath[MAX_PATH] = {};
+ GetModuleFileNameW(nullptr, exePath, MAX_PATH);
+ const std::string exe = wideToUtf8(exePath);
+
+ if (c.preferHttp && httpEnabled)
+ return nlohmann::json{
+ {"type", "http"},
+ {"url", "http://127.0.0.1:" + std::to_string(httpPort) + "/"}
+ };
+
+ return nlohmann::json{
+ {"command", exe},
+ {"args", nlohmann::json::array({"--mcp-stdio"})}
+ };
+ }
+ }
+
+ void MCPPage::RenderSetupForSelectedClient()
+ {
+ if (!SetupConfigBox() || !ClientPicker()) return;
+
+ const int idx = ClientPicker().SelectedIndex();
+ const auto& list = mcpClients();
+ if (idx < 0 || idx >= static_cast<int>(list.size())) return;
+ const auto& c = list[idx];
+
+ const auto s = DBModels::AppSettings::Load();
+ const int port = s.mcpHttpPort > 0 ? s.mcpHttpPort : 3333;
+ const bool httpOn = s.mcpHttpEnabled;
+
+ // Top-level config blob — just mcpServers.gridex.
+ nlohmann::json root = {{"mcpServers", {{"gridex", gridexEntryFor(c, port, httpOn)}}}};
+ SetupConfigBox().Text(winrt::hstring(
+ DBModels::MCPToolHelpers::fromUtf8(root.dump(2))));
+
+ if (SetupPathText())
+ SetupPathText().Text(winrt::hstring(L"Config file: " + c.configPath));
+
+ if (InstallBtnText())
+ InstallBtnText().Text(winrt::hstring(L"Install for " + c.displayName));
+ }
+
+ void MCPPage::ClientPicker_SelectionChanged(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const&)
+ {
+ RenderSetupForSelectedClient();
+ }
+
+ // Install for the currently-selected client. Merges our
+ // gridex entry into the existing mcpServers object, backs the
+ // file up as .bak first, and warns if the running exe is the
+ // Debug/AppX MSIX variant (which clients can't spawn).
+ void MCPPage::InstallClaude_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ if (!ClientPicker()) return;
+ const int idx = ClientPicker().SelectedIndex();
+ const auto& list = mcpClients();
+ if (idx < 0 || idx >= static_cast<int>(list.size())) return;
+ const auto& c = list[idx];
+
+ const std::wstring configPath = expandEnv(c.configPath);
+
+ // Guard: MSIX/AppX Debug exe can't be spawned as child process.
+ {
+ wchar_t exePath[MAX_PATH] = {};
+ GetModuleFileNameW(nullptr, exePath, MAX_PATH);
+ std::wstring p(exePath);
+ auto contains = [&](const wchar_t* s) {
+ return p.find(s) != std::wstring::npos;
+ };
+ if (contains(L"\\AppX\\") || contains(L"\\Debug\\"))
+ {
+ InstallStatusText().Text(
+ L"Current build is Debug/AppX — clients can't spawn an MSIX "
+ L"package directly. Switch Visual Studio to Release or run "
+ L"build-unpackaged.ps1 then try again.");
+ return;
+ }
+ }
+
+ // Ensure parent folder exists.
+ {
+ const auto sep = configPath.find_last_of(L'\\');
+ if (sep != std::wstring::npos)
+ CreateDirectoryW(configPath.substr(0, sep).c_str(), nullptr);
+ }
+
+ // Load existing (may be empty / absent / bad JSON).
+ nlohmann::json existing = nlohmann::json::object();
+ if (GetFileAttributesW(configPath.c_str()) != INVALID_FILE_ATTRIBUTES)
+ {
+ 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();
+
+ const auto s = DBModels::AppSettings::Load();
+ const int port = s.mcpHttpPort > 0 ? s.mcpHttpPort : 3333;
+ existing["mcpServers"]["gridex"] = gridexEntryFor(c, port, s.mcpHttpEnabled);
+
+ std::ofstream out(configPath, std::ios::binary | std::ios::trunc);
+ if (!out.is_open())
+ {
+ InstallStatusText().Text(winrt::hstring(
+ L"Failed to write config at " + configPath +
+ L". Is " + c.displayName + L" running?"));
+ return;
+ }
+ out << existing.dump(2);
+ out.close();
+
+ InstallStatusText().Text(winrt::hstring(
+ L"Installed for " + c.displayName +
+ L". Restart the client; a .bak backup of the previous config is next to the file."));
+ }
+
+ // ── Connections tab ──────────────────────────────────────
+ // Mac uses a SwiftUI Table with Pickers. WinUI 3 C++/winrt
+ // data-binding through IInspectable VMs is verbose, so we do
+ // the same thing HomePage.cpp does for ConnectionCard: build
+ // each row as a Grid at refresh time.
+
+ namespace
+ {
+ using namespace winrt::Microsoft::UI::Xaml;
+ using namespace winrt::Microsoft::UI::Xaml::Controls;
+ using namespace winrt::Microsoft::UI::Xaml::Media;
+ using namespace winrt::Windows::UI;
+
+ // Mac MCPConnectionMode colors — red / blue / green.
+ SolidColorBrush modeBrush(DBModels::MCPConnectionMode m)
+ {
+ switch (m)
+ {
+ case DBModels::MCPConnectionMode::ReadOnly:
+ return SolidColorBrush(ColorHelper::FromArgb(255, 30, 144, 255));
+ case DBModels::MCPConnectionMode::ReadWrite:
+ return SolidColorBrush(ColorHelper::FromArgb(255, 46, 139, 87));
+ default: // Locked
+ return SolidColorBrush(ColorHelper::FromArgb(255, 220, 53, 69));
+ }
+ }
+
+ bool containsCI(const std::wstring& haystack, const std::wstring& needle)
+ {
+ if (needle.empty()) return true;
+ auto lowerH = haystack;
+ auto lowerN = needle;
+ std::transform(lowerH.begin(), lowerH.end(), lowerH.begin(), ::towlower);
+ std::transform(lowerN.begin(), lowerN.end(), lowerN.begin(), ::towlower);
+ return lowerH.find(lowerN) != std::wstring::npos;
+ }
+
+ std::wstring displayHost(const DBModels::ConnectionConfig& c)
+ {
+ if (c.databaseType == DBModels::DatabaseType::SQLite)
+ return c.filePath.empty() ? L"" : c.filePath;
+ std::wstring h = c.host;
+ if (c.port > 0) h += L":" + std::to_wstring(c.port);
+ return h;
+ }
+ }
+
+ void MCPPage::RefreshConnectionsTab()
+ {
+ auto panel = ConnRowsPanel();
+ // Pivot lazy-load — tab may not be realized yet on Loaded.
+ if (!panel) return;
+ if (!ConnSearchBox() || !ConnFilterCombo()) return;
+ panel.Children().Clear();
+
+ // Filter state
+ const std::wstring q = std::wstring(ConnSearchBox().Text());
+ const int filterIdx = ConnFilterCombo().SelectedIndex();
+
+ auto all = DBModels::ConnectionStore::Load();
+ int total = static_cast<int>(all.size());
+ int shown = 0;
+
+ for (const auto& c : all)
+ {
+ // Mode filter: 0=All, 1=Locked, 2=ReadOnly, 3=ReadWrite
+ if (filterIdx == 1 && c.mcpMode != DBModels::MCPConnectionMode::Locked) continue;
+ if (filterIdx == 2 && c.mcpMode != DBModels::MCPConnectionMode::ReadOnly) continue;
+ if (filterIdx == 3 && c.mcpMode != DBModels::MCPConnectionMode::ReadWrite) continue;
+
+ // Text filter on name + host
+ if (!q.empty())
+ {
+ if (!containsCI(c.name, q) && !containsCI(displayHost(c), q)) continue;
+ }
+
+ Grid row;
+ row.Padding(Thickness{ 12, 8, 12, 8 });
+ row.ColumnSpacing(12);
+
+ ColumnDefinition col0; col0.Width(GridLengthHelper::FromPixels(20));
+ ColumnDefinition col1; col1.Width(GridLengthHelper::FromValueAndType(1, GridUnitType::Star));
+ col1.MinWidth(140);
+ ColumnDefinition col2; col2.Width(GridLengthHelper::FromPixels(90));
+ ColumnDefinition col3; col3.Width(GridLengthHelper::FromPixels(180));
+ ColumnDefinition col4; col4.Width(GridLengthHelper::FromPixels(140));
+ row.ColumnDefinitions().Append(col0);
+ row.ColumnDefinitions().Append(col1);
+ row.ColumnDefinitions().Append(col2);
+ row.ColumnDefinitions().Append(col3);
+ row.ColumnDefinitions().Append(col4);
+
+ // Status dot
+ Shapes::Ellipse dot;
+ dot.Width(8); dot.Height(8);
+ dot.Fill(modeBrush(c.mcpMode));
+ dot.VerticalAlignment(VerticalAlignment::Center);
+ Grid::SetColumn(dot, 0);
+ row.Children().Append(dot);
+
+ // Name
+ TextBlock name;
+ name.Text(winrt::hstring(c.name));
+ name.VerticalAlignment(VerticalAlignment::Center);
+ Grid::SetColumn(name, 1);
+ row.Children().Append(name);
+
+ // Type
+ TextBlock type;
+ type.Text(winrt::hstring(DBModels::DatabaseTypeDisplayName(c.databaseType)));
+ type.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 160, 160, 160)));
+ type.FontSize(12);
+ type.VerticalAlignment(VerticalAlignment::Center);
+ Grid::SetColumn(type, 2);
+ row.Children().Append(type);
+
+ // Host
+ TextBlock host;
+ host.Text(winrt::hstring(displayHost(c)));
+ host.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 160, 160, 160)));
+ host.FontSize(12);
+ host.VerticalAlignment(VerticalAlignment::Center);
+ host.TextTrimming(TextTrimming::CharacterEllipsis);
+ Grid::SetColumn(host, 3);
+ row.Children().Append(host);
+
+ // Access mode picker — changes persist via ConnectionStore::Save
+ // AND sync to the running MCPServer's permissionEngine.
+ ComboBox modePicker;
+ auto addItem = [&](const wchar_t* label) {
+ ComboBoxItem item;
+ item.Content(winrt::box_value(winrt::hstring(label)));
+ modePicker.Items().Append(item);
+ };
+ addItem(L"Locked");
+ addItem(L"Read-only");
+ addItem(L"Read-write");
+ modePicker.SelectedIndex(static_cast<int>(c.mcpMode));
+ modePicker.VerticalAlignment(VerticalAlignment::Center);
+ modePicker.MinWidth(130);
+
+ const std::wstring connId = c.id;
+ modePicker.SelectionChanged(
+ [this, connId](auto&& sender, auto&&) {
+ auto cb = sender.try_as<muxc::ComboBox>();
+ if (!cb) return;
+ const auto newMode = static_cast<DBModels::MCPConnectionMode>(cb.SelectedIndex());
+
+ auto configs = DBModels::ConnectionStore::Load();
+ for (auto& cfg : configs)
+ {
+ if (cfg.id == connId)
+ {
+ cfg.mcpMode = newMode;
+ DBModels::ConnectionStore::Save(cfg);
+ break;
+ }
+ }
+ if (auto srv = DBModels::MCPServerHost::instance())
+ srv->permissionEngine().setMode(connId, newMode);
+
+ RefreshUI(); // counts on Overview
+ });
+
+ Grid::SetColumn(modePicker, 4);
+ row.Children().Append(modePicker);
+
+ // Row separator
+ Border wrap;
+ wrap.Child(row);
+ wrap.BorderBrush(SolidColorBrush(ColorHelper::FromArgb(30, 128, 128, 128)));
+ wrap.BorderThickness(Thickness{ 0, 0, 0, 1 });
+ panel.Children().Append(wrap);
+ ++shown;
+ }
+
+ ConnCountText().Text(winrt::hstring(
+ std::to_wstring(shown) + L" of " + std::to_wstring(total)));
+ ConnEmptyState().Visibility(shown == 0 && total > 0
+ ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+ }
+
+ void MCPPage::ConnFilter_Changed(
+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBox const&,
+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBoxTextChangedEventArgs const&)
+ {
+ RefreshConnectionsTab();
+ }
+
+ void MCPPage::ConnFilterCombo_SelectionChanged(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const&)
+ {
+ RefreshConnectionsTab();
+ }
+
+ // ── Activity tab ─────────────────────────────────────────
+ // Tails the last 200 entries of mcp-audit.jsonl into a table.
+ // Uses the running MCPServer's logger when available; otherwise
+ // spins up a temporary MCPAuditLogger pointing at the same
+ // disk path so previous-session entries are still visible.
+
+ namespace
+ {
+ winrt::Microsoft::UI::Xaml::Media::SolidColorBrush statusBrush(
+ DBModels::MCPAuditStatus s)
+ {
+ using namespace winrt::Microsoft::UI::Xaml::Media;
+ using namespace winrt::Windows::UI;
+ switch (s)
+ {
+ case DBModels::MCPAuditStatus::Success:
+ return SolidColorBrush(ColorHelper::FromArgb(255, 46, 139, 87));
+ case DBModels::MCPAuditStatus::Error:
+ return SolidColorBrush(ColorHelper::FromArgb(255, 220, 53, 69));
+ case DBModels::MCPAuditStatus::Denied:
+ return SolidColorBrush(ColorHelper::FromArgb(255, 255, 140, 0));
+ default:
+ return SolidColorBrush(ColorHelper::FromArgb(255, 150, 150, 150));
+ }
+ }
+
+ std::wstring formatTimeHM(std::chrono::system_clock::time_point tp)
+ {
+ const std::time_t t = std::chrono::system_clock::to_time_t(tp);
+ std::tm tm{};
+ localtime_s(&tm, &t);
+ wchar_t buf[16];
+ wcsftime(buf, 16, L"%H:%M:%S", &tm);
+ return buf;
+ }
+
+ const wchar_t* statusLabel(DBModels::MCPAuditStatus s)
+ {
+ switch (s)
+ {
+ case DBModels::MCPAuditStatus::Success: return L"success";
+ case DBModels::MCPAuditStatus::Error: return L"error";
+ case DBModels::MCPAuditStatus::Denied: return L"denied";
+ case DBModels::MCPAuditStatus::Timeout: return L"timeout";
+ }
+ return L"?";
+ }
+ }
+
+ void MCPPage::RefreshActivityTab()
+ {
+ using namespace winrt::Microsoft::UI::Xaml;
+ using namespace winrt::Microsoft::UI::Xaml::Controls;
+ using namespace winrt::Microsoft::UI::Xaml::Media;
+ using namespace winrt::Windows::UI;
+
+ auto panel = ActRowsPanel();
+ if (!panel) return;
+ if (!ActSearchBox() || !ActStatusCombo()) return;
+ panel.Children().Clear();
+
+ wchar_t* ad = nullptr;
+ if (SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &ad) == S_OK)
+ {
+ std::wstring dir = std::wstring(ad) + L"\\Gridex";
+ CoTaskMemFree(ad);
+ ActPathText().Text(winrt::hstring(L"Audit log: " + dir + L"\\mcp-audit.jsonl"));
+ }
+
+ std::vector<DBModels::MCPAuditEntry> entries;
+ if (auto srv = DBModels::MCPServerHost::instance())
+ {
+ entries = srv->auditLogger().recentEntries(200);
+ }
+ else
+ {
+ auto s = DBModels::AppSettings::Load();
+ DBModels::MCPAuditLogger tempLogger(
+ s.mcpAuditMaxSizeMB, s.mcpAuditRetentionDays);
+ entries = tempLogger.recentEntries(200);
+ }
+
+ const std::wstring q = std::wstring(ActSearchBox().Text());
+ const int statusIdx = ActStatusCombo().SelectedIndex();
+
+ // Build the filtered list first and cache it so click
+ // handlers can look up the full record by index. We need
+ // stable indices — rebuilding the cache on every refresh
+ // is fine because the table is also rebuilt each time.
+ cachedActivity_.clear();
+ cachedActivity_.reserve(entries.size());
+
+ int shown = 0;
+ for (const auto& e : entries)
+ {
+ const auto status = e.result.status;
+ if (statusIdx == 1 && status != DBModels::MCPAuditStatus::Success) continue;
+ if (statusIdx == 2 && status != DBModels::MCPAuditStatus::Error) continue;
+ if (statusIdx == 3 && status != DBModels::MCPAuditStatus::Denied) continue;
+
+ if (!q.empty())
+ {
+ auto lower = [](std::wstring s) {
+ std::transform(s.begin(), s.end(), s.begin(), ::towlower);
+ return s;
+ };
+ const std::wstring qL = lower(q);
+ auto toolW = DBModels::MCPToolHelpers::fromUtf8(e.tool);
+ auto clientW = DBModels::MCPToolHelpers::fromUtf8(e.client.name);
+ std::wstring sqlW = e.input.sqlPreview.has_value()
+ ? DBModels::MCPToolHelpers::fromUtf8(*e.input.sqlPreview) : L"";
+ if (lower(toolW).find(qL) == std::wstring::npos &&
+ lower(clientW).find(qL) == std::wstring::npos &&
+ lower(sqlW).find(qL) == std::wstring::npos) continue;
+ }
+
+ const int cacheIdx = static_cast<int>(cachedActivity_.size());
+ cachedActivity_.push_back(e);
+
+ Grid row;
+ row.Padding(Thickness{ 12, 6, 12, 6 });
+ row.ColumnSpacing(12);
+
+ ColumnDefinition c0; c0.Width(GridLengthHelper::FromPixels(90));
+ ColumnDefinition c1; c1.Width(GridLengthHelper::FromValueAndType(1, GridUnitType::Star));
+ c1.MinWidth(160);
+ ColumnDefinition c2; c2.Width(GridLengthHelper::FromPixels(120));
+ ColumnDefinition c3; c3.Width(GridLengthHelper::FromPixels(80));
+ ColumnDefinition c4; c4.Width(GridLengthHelper::FromPixels(70));
+ row.ColumnDefinitions().Append(c0);
+ row.ColumnDefinitions().Append(c1);
+ row.ColumnDefinitions().Append(c2);
+ row.ColumnDefinitions().Append(c3);
+ row.ColumnDefinitions().Append(c4);
+
+ TextBlock t; t.Text(winrt::hstring(formatTimeHM(e.timestamp)));
+ t.FontSize(12); t.FontFamily(winrt::Microsoft::UI::Xaml::Media::FontFamily(L"Consolas"));
+ t.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 160, 160, 160)));
+ Grid::SetColumn(t, 0); row.Children().Append(t);
+
+ TextBlock tool; tool.Text(winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(e.tool)));
+ tool.FontSize(12); tool.FontFamily(winrt::Microsoft::UI::Xaml::Media::FontFamily(L"Consolas"));
+ Grid::SetColumn(tool, 1); row.Children().Append(tool);
+
+ TextBlock client; client.Text(winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(e.client.name)));
+ client.FontSize(12);
+ client.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 160, 160, 160)));
+ Grid::SetColumn(client, 2); row.Children().Append(client);
+
+ TextBlock st; st.Text(winrt::hstring(statusLabel(status)));
+ st.FontSize(12); st.Foreground(statusBrush(status));
+ Grid::SetColumn(st, 3); row.Children().Append(st);
+
+ TextBlock dur;
+ dur.Text(winrt::hstring(std::to_wstring(e.result.durationMs) + L"ms"));
+ dur.FontSize(12); dur.FontFamily(winrt::Microsoft::UI::Xaml::Media::FontFamily(L"Consolas"));
+ dur.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 160, 160, 160)));
+ Grid::SetColumn(dur, 4); row.Children().Append(dur);
+
+ Border wrap; wrap.Child(row);
+ wrap.BorderBrush(SolidColorBrush(ColorHelper::FromArgb(30, 128, 128, 128)));
+ wrap.BorderThickness(Thickness{ 0, 0, 0, 1 });
+ wrap.Background(SolidColorBrush(ColorHelper::FromArgb(0, 0, 0, 0)));
+ // Row click → populate detail pane. Uses Tapped rather
+ // than PointerPressed so touch + mouse both fire one
+ // event with click semantics.
+ wrap.Tapped([this, cacheIdx](auto&&, auto&&) {
+ SelectActivityEntry(cacheIdx);
+ });
+ panel.Children().Append(wrap);
+ ++shown;
+ }
+
+ ActEmptyState().Visibility(shown == 0
+ ? mux::Visibility::Visible : mux::Visibility::Collapsed);
+
+ // Auto-select the first entry so the detail pane isn't empty
+ // on load. Skipped when nothing passed the filter.
+ if (!cachedActivity_.empty()) SelectActivityEntry(0);
+ }
+
+ // Populate the right-side detail panel for a given cached entry.
+ // Mirrors the Form sections in macOS MCPActivityView.detailPanel:
+ // Event, Client, Connection, Result, SQL, Error.
+ void MCPPage::SelectActivityEntry(int index)
+ {
+ using namespace winrt::Microsoft::UI::Xaml;
+ using namespace winrt::Microsoft::UI::Xaml::Controls;
+ using namespace winrt::Microsoft::UI::Xaml::Media;
+ using namespace winrt::Windows::UI;
+
+ auto panel = ActDetailPanel();
+ if (!panel) return;
+ if (index < 0 || index >= static_cast<int>(cachedActivity_.size())) return;
+ const auto& e = cachedActivity_[index];
+
+ selectedActivityIndex_ = index;
+
+ // Highlight the active row on the left table. Iterate the
+ // row panel's Border children and swap Background — accent
+ // tint on the selected row, transparent elsewhere. Cheap
+ // because we only have up to 200 rows.
+ if (auto rows = ActRowsPanel())
+ {
+ const auto sel = SolidColorBrush(ColorHelper::FromArgb(60, 130, 90, 220));
+ const auto none = SolidColorBrush(ColorHelper::FromArgb(0, 0, 0, 0));
+ auto kids = rows.Children();
+ for (uint32_t i = 0; i < kids.Size(); ++i)
+ {
+ if (auto b = kids.GetAt(i).try_as<Border>())
+ b.Background(static_cast<int>(i) == index ? sel : none);
+ }
+ }
+
+ panel.Children().Clear();
+
+ auto addHeader = [&](winrt::hstring text) {
+ TextBlock h;
+ h.Text(text);
+ h.FontSize(13);
+ h.FontWeight(Windows::UI::Text::FontWeights::SemiBold());
+ h.Margin(Thickness{ 0, 8, 0, 2 });
+ panel.Children().Append(h);
+ };
+
+ auto addRow = [&](const wchar_t* label, winrt::hstring value, bool mono = false) {
+ Grid g; g.ColumnSpacing(8);
+ ColumnDefinition l; l.Width(GridLengthHelper::FromPixels(100));
+ ColumnDefinition v; v.Width(GridLengthHelper::FromValueAndType(1, GridUnitType::Star));
+ g.ColumnDefinitions().Append(l);
+ g.ColumnDefinitions().Append(v);
+
+ TextBlock lb; lb.Text(label); lb.FontSize(11);
+ lb.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 150, 150, 150)));
+ Grid::SetColumn(lb, 0); g.Children().Append(lb);
+
+ TextBlock vb; vb.Text(value); vb.FontSize(12);
+ vb.TextWrapping(TextWrapping::Wrap);
+ vb.IsTextSelectionEnabled(true);
+ if (mono) vb.FontFamily(winrt::Microsoft::UI::Xaml::Media::FontFamily(L"Consolas"));
+ Grid::SetColumn(vb, 1); g.Children().Append(vb);
+
+ panel.Children().Append(g);
+ };
+
+ auto addBlock = [&](const wchar_t* label, winrt::hstring value, bool mono = true) {
+ TextBlock lb; lb.Text(label); lb.FontSize(11);
+ lb.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 150, 150, 150)));
+ lb.Margin(Thickness{ 0, 4, 0, 2 });
+ panel.Children().Append(lb);
+
+ Border b;
+ b.Padding(Thickness{ 8, 6, 8, 6 });
+ b.CornerRadius(winrt::Microsoft::UI::Xaml::CornerRadius{ 4, 4, 4, 4 });
+ b.Background(SolidColorBrush(ColorHelper::FromArgb(255, 28, 28, 30)));
+ TextBlock vb; vb.Text(value); vb.FontSize(12);
+ vb.TextWrapping(TextWrapping::Wrap);
+ vb.IsTextSelectionEnabled(true);
+ if (mono) vb.FontFamily(winrt::Microsoft::UI::Xaml::Media::FontFamily(L"Consolas"));
+ b.Child(vb);
+ panel.Children().Append(b);
+ };
+
+ // Format full timestamp.
+ auto fullTime = [](std::chrono::system_clock::time_point tp) {
+ const std::time_t t = std::chrono::system_clock::to_time_t(tp);
+ std::tm tm{};
+ localtime_s(&tm, &t);
+ wchar_t buf[32];
+ wcsftime(buf, 32, L"%Y-%m-%d %H:%M:%S", &tm);
+ return std::wstring(buf);
+ };
+
+ addHeader(L"Event");
+ addRow(L"Tool", winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(e.tool)), true);
+ addRow(L"Tier", winrt::hstring(L"Tier " + std::to_wstring(e.tier)));
+ addRow(L"Time", winrt::hstring(fullTime(e.timestamp)));
+ if (!e.eventId.empty())
+ {
+ std::string shortId = e.eventId.size() > 8 ? e.eventId.substr(0, 8) + "..." : e.eventId;
+ addRow(L"Event ID", winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(shortId)), true);
+ }
+
+ addHeader(L"Client");
+ addRow(L"Name", winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(e.client.name)));
+ addRow(L"Version", winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(e.client.version)));
+ addRow(L"Transport", winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(e.client.transport)));
+
+ if (e.connectionId.has_value() || e.connectionType.has_value())
+ {
+ addHeader(L"Connection");
+ if (e.connectionType.has_value())
+ addRow(L"Database", winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(*e.connectionType)));
+ if (e.connectionId.has_value())
+ {
+ const auto& cid = *e.connectionId;
+ std::string shortId = cid.size() > 8 ? cid.substr(0, 8) + "..." : cid;
+ addRow(L"ID", winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(shortId)), true);
+ }
+ }
+
+ addHeader(L"Result");
+ addRow(L"Status", winrt::hstring(statusLabel(e.result.status)));
+ addRow(L"Duration", winrt::hstring(std::to_wstring(e.result.durationMs) + L" ms"));
+ if (e.result.rowsReturned.has_value())
+ addRow(L"Rows returned", winrt::hstring(std::to_wstring(*e.result.rowsReturned)));
+ if (e.result.rowsAffected.has_value())
+ addRow(L"Rows affected", winrt::hstring(std::to_wstring(*e.result.rowsAffected)));
+
+ if (e.input.sqlPreview.has_value() && !e.input.sqlPreview->empty())
+ {
+ addBlock(L"SQL", winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(*e.input.sqlPreview)));
+ }
+
+ if (e.error.has_value() && !e.error->empty())
+ {
+ TextBlock lb; lb.Text(L"Error"); lb.FontSize(11);
+ lb.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 220, 53, 69)));
+ lb.Margin(Thickness{ 0, 8, 0, 2 });
+ panel.Children().Append(lb);
+
+ Border b;
+ b.Padding(Thickness{ 8, 6, 8, 6 });
+ b.CornerRadius(winrt::Microsoft::UI::Xaml::CornerRadius{ 4, 4, 4, 4 });
+ b.Background(SolidColorBrush(ColorHelper::FromArgb(255, 40, 20, 22)));
+ TextBlock vb; vb.Text(winrt::hstring(DBModels::MCPToolHelpers::fromUtf8(*e.error)));
+ vb.FontSize(12); vb.TextWrapping(TextWrapping::Wrap);
+ vb.IsTextSelectionEnabled(true);
+ vb.Foreground(SolidColorBrush(ColorHelper::FromArgb(255, 255, 180, 180)));
+ b.Child(vb);
+ panel.Children().Append(b);
+ }
+ }
+
+ void MCPPage::ActFilter_Changed(
+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBox const&,
+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBoxTextChangedEventArgs const&)
+ {
+ RefreshActivityTab();
+ }
+
+ void MCPPage::ActStatusCombo_SelectionChanged(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const&)
+ {
+ RefreshActivityTab();
+ }
+
+ void MCPPage::ActRefresh_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ RefreshActivityTab();
+ }
+
+ // Deferred-load refresh — Pivot lazily realizes PivotItem
+ // content, so controls inside non-selected tabs are nullptr at
+ // page Loaded. Refresh the body of whichever tab just became
+ // active; guard with try/catch so a single tab's error can't
+ // kill navigation.
+ void MCPPage::Tabs_SelectionChanged(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const&)
+ {
+ const int idx = Tabs().SelectedIndex();
+ try
+ {
+ if (idx == 0) RefreshUI();
+ else if (idx == 1) RefreshConnectionsTab();
+ else if (idx == 2) RefreshActivityTab();
+ else if (idx == 3) RefreshUI(); // Setup has JSON preview
+ else if (idx == 4) RefreshUI(); // Config loads from AppSettings
+ }
+ catch (...) { /* don't kill navigation */ }
+ }
+
+ // Paint the "Running for Xh Ym · N of M connections exposed"
+ // subtitle on the Overview card. Called on Loaded and once per
+ // second from the uptime timer.
+ void MCPPage::RefreshOverviewUptime()
+ {
+ auto sub = RunningSubtitle();
+ if (!sub) return;
+
+ auto srv = DBModels::MCPServerHost::instance();
+ const bool running = srv && srv->isRunning();
+ if (!running)
+ {
+ sub.Text(L"Enable below to let AI clients connect.");
+ return;
+ }
+
+ auto settings = DBModels::AppSettings::Load();
+ std::wstring uptime = L"just started";
+ if (settings.mcpStartTime > 0)
+ {
+ const int64_t now = static_cast<int64_t>(
+ std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count());
+ int64_t dt = now - settings.mcpStartTime;
+ if (dt < 0) dt = 0;
+ const int h = static_cast<int>(dt / 3600);
+ const int m = static_cast<int>((dt % 3600) / 60);
+ const int s = static_cast<int>(dt % 60);
+ if (h > 0) uptime = std::to_wstring(h) + L"h " + std::to_wstring(m) + L"m";
+ else if (m > 0) uptime = std::to_wstring(m) + L"m " + std::to_wstring(s) + L"s";
+ else uptime = std::to_wstring(s) + L"s";
+ }
+
+ // Count exposed connections (non-Locked).
+ int exposed = 0, total = 0;
+ for (const auto& c : DBModels::ConnectionStore::Load())
+ {
+ ++total;
+ if (c.mcpMode != DBModels::MCPConnectionMode::Locked) ++exposed;
+ }
+
+ sub.Text(winrt::hstring(
+ L"Running for " + uptime + L" · " +
+ std::to_wstring(exposed) + L" of " + std::to_wstring(total) +
+ L" connections exposed"));
+ }
+
+ // Overview → "Manage Connections..." button: jump to the
+ // Connections tab (Pivot index 1).
+ void MCPPage::ManageConnections_Click(
+ winrt::Windows::Foundation::IInspectable const&,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
+ {
+ if (auto t = Tabs()) t.SelectedIndex(1);
+ }
+}
diff --git a/windows/Gridex/MCPPage.h b/windows/Gridex/MCPPage.h
new file mode 100644
index 0000000..319c988
--- /dev/null
+++ b/windows/Gridex/MCPPage.h
@@ -0,0 +1,101 @@
+#pragma once
+
+#include "MCPPage.g.h"
+#include "Models/MCP/MCPAuditEntry.h"
+#include <vector>
+
+namespace winrt::Gridex::implementation
+{
+ // MCPPage — Gridex MCP Server dashboard (5 tabs, mirrors macOS).
+ // Overview tab is fully wired; Connections / Activity / Setup / Config
+ // have minimum viable bodies and will grow in follow-up sprints.
+ struct MCPPage : MCPPageT<MCPPage>
+ {
+ MCPPage();
+
+ void Back_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ void StartStop_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ void HttpToggle_Toggled(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ // Port persists on edit (auto-save) so the Overview tab
+ // doesn't need a dedicated Save button for this field.
+ void HttpPortBox_ValueChanged(
+ winrt::Microsoft::UI::Xaml::Controls::NumberBox const& sender,
+ winrt::Microsoft::UI::Xaml::Controls::NumberBoxValueChangedEventArgs const& args);
+
+ void CopyConfig_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ void SaveConfig_Click(
+ 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);
+
+ // Re-render Setup tab (preview JSON + config path + button
+ // label) whenever the AI-client dropdown changes.
+ void ClientPicker_SelectionChanged(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const& e);
+
+ // Connections tab handlers
+ void ConnFilter_Changed(
+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBox const& sender,
+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBoxTextChangedEventArgs const& e);
+ void ConnFilterCombo_SelectionChanged(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const& e);
+
+ // Activity tab handlers
+ void ActFilter_Changed(
+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBox const& sender,
+ winrt::Microsoft::UI::Xaml::Controls::AutoSuggestBoxTextChangedEventArgs const& e);
+ void ActStatusCombo_SelectionChanged(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const& e);
+ void ActRefresh_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ // Pivot lazy-loads PivotItems; refresh the tab's body when
+ // it first becomes selected so named controls are live.
+ void Tabs_SelectionChanged(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::Controls::SelectionChangedEventArgs const& e);
+
+ void ManageConnections_Click(
+ winrt::Windows::Foundation::IInspectable const& sender,
+ winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e);
+
+ private:
+ void RefreshUI();
+ void RefreshOverviewUptime();
+ void RenderSetupForSelectedClient();
+ winrt::Microsoft::UI::Xaml::DispatcherTimer uptimeTimer_{ nullptr };
+ void ApplyStartStopButton(bool running);
+ void RefreshConnectionsTab();
+ void RefreshActivityTab();
+ void SelectActivityEntry(int index);
+
+ // Cache tailed audit entries so a click on a row can look
+ // up the full record by index. Populated by RefreshActivityTab.
+ std::vector<DBModels::MCPAuditEntry> cachedActivity_;
+ int selectedActivityIndex_ = -1;
+ };
+}
+
+namespace winrt::Gridex::factory_implementation
+{
+ struct MCPPage : MCPPageT<MCPPage, implementation::MCPPage> {};
+}
diff --git a/windows/Gridex/MCPPage.idl b/windows/Gridex/MCPPage.idl
new file mode 100644
index 0000000..aa50280
--- /dev/null
+++ b/windows/Gridex/MCPPage.idl
@@ -0,0 +1,8 @@
+namespace Gridex
+{
+ [default_interface]
+ runtimeclass MCPPage : Microsoft.UI.Xaml.Controls.Page
+ {
+ MCPPage();
+ }
+}
diff --git a/windows/Gridex/MCPPage.xaml b/windows/Gridex/MCPPage.xaml
new file mode 100644
index 0000000..704ae61
--- /dev/null
+++ b/windows/Gridex/MCPPage.xaml
@@ -0,0 +1,661 @@
+<Page
+ x:Class="Gridex.MCPPage"
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:local="using:Gridex"
+ Background="Transparent">
+
+ <Grid RowSpacing="0">
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="*" />
+ </Grid.RowDefinitions>
+
+ <!-- Header: back button + title + server status pill + Start/Stop -->
+ <Grid Grid.Row="0" Padding="24,16,24,12">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="Auto" />
+ <ColumnDefinition Width="Auto" />
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+
+ <Button x:Name="BackBtn" Grid.Column="0"
+ Background="Transparent" BorderThickness="0"
+ Padding="8,4" VerticalAlignment="Center"
+ ToolTipService.ToolTip="Back"
+ Click="Back_Click">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE72B;" FontSize="14" />
+ <TextBlock Text="Back" FontSize="13" />
+ </StackPanel>
+ </Button>
+
+ <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="10"
+ VerticalAlignment="Center" Margin="16,0,0,0">
+ <!-- Status dot — gray (off) / green (running) / orange (pending). -->
+ <Ellipse x:Name="StatusDot" Width="10" Height="10"
+ Fill="Gray" />
+ <StackPanel>
+ <TextBlock Text="MCP Server" FontSize="18" FontWeight="SemiBold" />
+ <TextBlock x:Name="StatusText"
+ Text="Stopped"
+ FontSize="12"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ </StackPanel>
+ </StackPanel>
+
+ <Button x:Name="StartStopBtn" Grid.Column="3"
+ Padding="16,6"
+ Content="Start Server"
+ Click="StartStop_Click"
+ Style="{StaticResource AccentButtonStyle}" />
+ </Grid>
+
+ <!-- Pivot = 5 tabs matching mac. Each tab body is its own
+ panel — Overview is wired fully, the rest show a
+ placeholder until the implementation catches up.
+ HorizontalAlignment=Center + MaxWidth keeps the
+ tab-strip centered on ultra-wide displays instead of
+ letting the 5 short tab labels cluster on the left. -->
+ <!-- Wrapper Grid with flexible side columns so the Pivot
+ stays centered on any window width. MinWidth on the
+ middle column guarantees the tabs + content get enough
+ room when the window is narrow. -->
+ <Grid Grid.Row="1" Margin="24,0,24,16">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" MinWidth="960" />
+ <ColumnDefinition Width="*" />
+ </Grid.ColumnDefinitions>
+
+ <Pivot Grid.Column="1" x:Name="Tabs"
+ HorizontalAlignment="Stretch"
+ HorizontalContentAlignment="Stretch"
+ SelectionChanged="Tabs_SelectionChanged">
+ <Pivot.Resources>
+ <!-- Shrink + tighten the tab labels so they read
+ more like the mac SegmentedControl (~14pt) and
+ stop dominating the top of the page. -->
+ <Style TargetType="PivotHeaderItem">
+ <Setter Property="FontSize" Value="14" />
+ <Setter Property="FontWeight" Value="Normal" />
+ <Setter Property="Padding" Value="14,6,14,6" />
+ <Setter Property="MinHeight" Value="36" />
+ </Style>
+ </Pivot.Resources>
+ <PivotItem Header="Overview">
+ <ScrollViewer>
+ <!-- HorizontalAlignment=Center so the content
+ sits in the middle of the screen like the
+ mac reference instead of stretching right. -->
+ <StackPanel Spacing="20" MaxWidth="900" HorizontalAlignment="Center">
+
+ <!-- Running card -->
+ <Border Padding="16"
+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
+ CornerRadius="8"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1">
+ <StackPanel Orientation="Horizontal" Spacing="12">
+ <FontIcon x:Name="RunningIcon" Glyph="&#xE711;"
+ FontSize="22"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />
+ <StackPanel>
+ <TextBlock x:Name="RunningTitle"
+ Text="MCP Server is stopped"
+ FontSize="14" FontWeight="SemiBold" />
+ <TextBlock x:Name="RunningSubtitle"
+ Text="Enable below to let AI clients connect."
+ FontSize="12"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}"
+ TextWrapping="Wrap" />
+ </StackPanel>
+ </StackPanel>
+ </Border>
+
+ <!-- Access summary (per-mode connection counts). -->
+ <StackPanel Spacing="8">
+ <TextBlock Text="Access" FontSize="14" FontWeight="SemiBold" />
+ <Border Padding="16" CornerRadius="8"
+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1">
+ <StackPanel Spacing="10">
+ <Grid>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Text="Locked" Grid.Column="0" />
+ <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="6">
+ <Ellipse Width="8" Height="8" Fill="Red" />
+ <TextBlock x:Name="LockedCount" Text="0" />
+ </StackPanel>
+ </Grid>
+ <Grid>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Text="Read-only" Grid.Column="0" />
+ <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="6">
+ <Ellipse Width="8" Height="8" Fill="DodgerBlue" />
+ <TextBlock x:Name="ReadOnlyCount" Text="0" />
+ </StackPanel>
+ </Grid>
+ <Grid>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Text="Read-write" Grid.Column="0" />
+ <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="6">
+ <Ellipse Width="8" Height="8" Fill="SeaGreen" />
+ <TextBlock x:Name="ReadWriteCount" Text="0" />
+ </StackPanel>
+ </Grid>
+ <Button x:Name="ManageConnectionsBtn"
+ HorizontalAlignment="Left"
+ Margin="0,4,0,0"
+ Padding="12,4"
+ Click="ManageConnections_Click">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <FontIcon Glyph="&#xE762;" FontSize="12" />
+ <TextBlock Text="Manage Connections..." FontSize="12" />
+ </StackPanel>
+ </Button>
+ </StackPanel>
+ </Border>
+ </StackPanel>
+
+ <!-- Transport -->
+ <StackPanel Spacing="8">
+ <TextBlock Text="Transport" FontSize="14" FontWeight="SemiBold" />
+ <Border Padding="16" CornerRadius="8"
+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1">
+ <StackPanel Spacing="10">
+ <Grid>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Text="stdio" Grid.Column="0" />
+ <TextBlock Text="Local clients ✓"
+ Grid.Column="1"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ </Grid>
+ <Grid>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Text="HTTP" Grid.Column="0" />
+ <ToggleSwitch x:Name="HttpToggle"
+ Grid.Column="1"
+ Toggled="HttpToggle_Toggled"
+ OffContent="" OnContent="" />
+ </Grid>
+ <Grid x:Name="HttpPortRow" Visibility="Collapsed">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Text="Port" Grid.Column="0" />
+ <NumberBox x:Name="HttpPortBox"
+ Grid.Column="1"
+ Minimum="1024" Maximum="65535"
+ Value="3333" Width="120"
+ ValueChanged="HttpPortBox_ValueChanged" />
+ </Grid>
+ </StackPanel>
+ </Border>
+ </StackPanel>
+
+ <!-- Tool inventory -->
+ <StackPanel Spacing="4">
+ <TextBlock Text="Tools registered"
+ FontSize="12"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ <TextBlock x:Name="ToolsCountText"
+ Text="0 tools"
+ FontSize="13" />
+ </StackPanel>
+
+ <!-- Recent Activity — last 5 audit entries.
+ Populated by RefreshUI from
+ MCPAuditLogger::recentEntries(5). -->
+ <StackPanel Spacing="8">
+ <Grid>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Text="Recent Activity"
+ FontSize="14" FontWeight="SemiBold" />
+ <TextBlock x:Name="RecentActivityCount"
+ Grid.Column="1"
+ FontSize="11"
+ VerticalAlignment="Bottom"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />
+ </Grid>
+ <Border Padding="12" CornerRadius="8"
+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1">
+ <StackPanel x:Name="RecentActivityPanel" Spacing="6">
+ <TextBlock Text="No activity yet"
+ FontSize="12"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />
+ </StackPanel>
+ </Border>
+ </StackPanel>
+ </StackPanel>
+ </ScrollViewer>
+ </PivotItem>
+
+ <PivotItem Header="Connections">
+ <Grid RowSpacing="0">
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="*" />
+ </Grid.RowDefinitions>
+
+ <!-- Filter bar: search + mode filter + count -->
+ <Grid Grid.Row="0" Padding="4,6,4,10" ColumnSpacing="10">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" MaxWidth="300" />
+ <ColumnDefinition Width="160" />
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <AutoSuggestBox x:Name="ConnSearchBox"
+ Grid.Column="0"
+ PlaceholderText="Search connections"
+ QueryIcon="Find"
+ TextChanged="ConnFilter_Changed" />
+ <ComboBox x:Name="ConnFilterCombo" Grid.Column="1"
+ SelectedIndex="0"
+ SelectionChanged="ConnFilterCombo_SelectionChanged">
+ <ComboBoxItem Content="All Access" />
+ <ComboBoxItem Content="Locked" />
+ <ComboBoxItem Content="Read-only" />
+ <ComboBoxItem Content="Read-write" />
+ </ComboBox>
+ <TextBlock x:Name="ConnCountText" Grid.Column="3"
+ VerticalAlignment="Center"
+ FontSize="12"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ </Grid>
+
+ <!-- Column headers -->
+ <Border Grid.Row="1"
+ Padding="12,8"
+ Background="{ThemeResource CardBackgroundFillColorSecondaryBrush}"
+ CornerRadius="6,6,0,0"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1,1,1,0">
+ <Grid ColumnSpacing="12">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="20" />
+ <ColumnDefinition Width="*" MinWidth="140" />
+ <ColumnDefinition Width="90" />
+ <ColumnDefinition Width="180" />
+ <ColumnDefinition Width="140" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Grid.Column="1" Text="Name"
+ FontSize="12" FontWeight="SemiBold" />
+ <TextBlock Grid.Column="2" Text="Type"
+ FontSize="12" FontWeight="SemiBold" />
+ <TextBlock Grid.Column="3" Text="Host"
+ FontSize="12" FontWeight="SemiBold" />
+ <TextBlock Grid.Column="4" Text="Access"
+ FontSize="12" FontWeight="SemiBold" />
+ </Grid>
+ </Border>
+
+ <!-- Rows container — populated in MCPPage.cpp.
+ Not using DataTemplate + IInspectable binding
+ because the codebase already uses
+ programmatic row assembly (HomePage does the
+ same for ConnectionCard). -->
+ <ScrollViewer Grid.Row="2"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1,0,1,1"
+ CornerRadius="0,0,6,6">
+ <StackPanel x:Name="ConnRowsPanel" Spacing="0" />
+ </ScrollViewer>
+
+ <!-- Empty state -->
+ <StackPanel x:Name="ConnEmptyState" Grid.Row="2"
+ VerticalAlignment="Center" HorizontalAlignment="Center"
+ Spacing="8"
+ Visibility="Collapsed">
+ <FontIcon Glyph="&#xE968;" FontSize="36"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />
+ <TextBlock Text="No connections match"
+ HorizontalAlignment="Center" FontSize="14" />
+ <TextBlock Text="Try a different search or filter."
+ HorizontalAlignment="Center" FontSize="12"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ </StackPanel>
+ </Grid>
+ </PivotItem>
+
+ <PivotItem Header="Activity">
+ <!-- Outer grid: filter bar + detail split + footer.
+ The split row (*) contains a 2-column grid — the
+ audit table on the left and the selected-entry
+ detail pane on the right, same layout mac's
+ HSplitView uses. -->
+ <Grid RowSpacing="0">
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="*" />
+ <RowDefinition Height="Auto" />
+ </Grid.RowDefinitions>
+
+ <!-- Filter bar -->
+ <Grid Grid.Row="0" Padding="4,6,4,10" ColumnSpacing="10">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" MaxWidth="280" />
+ <ColumnDefinition Width="140" />
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ <AutoSuggestBox x:Name="ActSearchBox" Grid.Column="0"
+ PlaceholderText="Search tool, SQL, or client"
+ QueryIcon="Find"
+ TextChanged="ActFilter_Changed" />
+ <ComboBox x:Name="ActStatusCombo" Grid.Column="1"
+ SelectedIndex="0"
+ SelectionChanged="ActStatusCombo_SelectionChanged">
+ <ComboBoxItem Content="All Status" />
+ <ComboBoxItem Content="Success" />
+ <ComboBoxItem Content="Error" />
+ <ComboBoxItem Content="Denied" />
+ </ComboBox>
+ <Button Grid.Column="3"
+ Click="ActRefresh_Click"
+ ToolTipService.ToolTip="Refresh">
+ <FontIcon Glyph="&#xE72C;" FontSize="12" />
+ </Button>
+ </Grid>
+
+ <!-- Table + detail split -->
+ <Grid Grid.Row="1" ColumnSpacing="12">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" MinWidth="440" />
+ <ColumnDefinition Width="360" />
+ </Grid.ColumnDefinitions>
+
+ <!-- Left: audit table -->
+ <Grid Grid.Column="0" RowSpacing="0">
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="*" />
+ </Grid.RowDefinitions>
+
+ <Border Grid.Row="0" Padding="12,8"
+ Background="{ThemeResource CardBackgroundFillColorSecondaryBrush}"
+ CornerRadius="6,6,0,0"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1,1,1,0">
+ <Grid ColumnSpacing="12">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="90" />
+ <ColumnDefinition Width="*" MinWidth="160" />
+ <ColumnDefinition Width="120" />
+ <ColumnDefinition Width="80" />
+ <ColumnDefinition Width="70" />
+ </Grid.ColumnDefinitions>
+ <TextBlock Grid.Column="0" Text="Time" FontSize="12" FontWeight="SemiBold" />
+ <TextBlock Grid.Column="1" Text="Tool" FontSize="12" FontWeight="SemiBold" />
+ <TextBlock Grid.Column="2" Text="Client" FontSize="12" FontWeight="SemiBold" />
+ <TextBlock Grid.Column="3" Text="Status" FontSize="12" FontWeight="SemiBold" />
+ <TextBlock Grid.Column="4" Text="Duration" FontSize="12" FontWeight="SemiBold" />
+ </Grid>
+ </Border>
+
+ <ScrollViewer Grid.Row="1"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1,0,1,1"
+ CornerRadius="0,0,6,6">
+ <StackPanel x:Name="ActRowsPanel" Spacing="0" />
+ </ScrollViewer>
+
+ <StackPanel x:Name="ActEmptyState" Grid.Row="1"
+ VerticalAlignment="Center" HorizontalAlignment="Center"
+ Spacing="8"
+ Visibility="Collapsed">
+ <FontIcon Glyph="&#xE9D9;" FontSize="36"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />
+ <TextBlock Text="No activity yet"
+ HorizontalAlignment="Center" FontSize="14" />
+ <TextBlock Text="MCP tool invocations will appear here once a client connects."
+ HorizontalAlignment="Center" FontSize="12"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}"
+ TextWrapping="Wrap" MaxWidth="380" TextAlignment="Center" />
+ </StackPanel>
+ </Grid>
+
+ <!-- Right: detail pane (populated on row click) -->
+ <Border Grid.Column="1"
+ Padding="16"
+ Background="{ThemeResource CardBackgroundFillColorDefaultBrush}"
+ CornerRadius="6"
+ BorderBrush="{ThemeResource CardStrokeColorDefaultBrush}"
+ BorderThickness="1">
+ <ScrollViewer>
+ <StackPanel x:Name="ActDetailPanel" Spacing="12">
+ <TextBlock x:Name="ActDetailPlaceholder"
+ Text="Click a row on the left to see the full audit entry (SQL preview, client info, error message, etc.)."
+ FontSize="12"
+ TextWrapping="Wrap"
+ Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
+ </StackPanel>
+ </ScrollViewer>
+ </Border>
+ </Grid>
+
+ <TextBlock Grid.Row="2" x:Name="ActPathText"
+ FontSize="11"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"
+ IsTextSelectionEnabled="True"
+ Margin="4,8,0,0" />
+ </Grid>
+ </PivotItem>
+
+ <PivotItem Header="Setup">
+ <ScrollViewer>
+ <StackPanel Spacing="16" MaxWidth="900" HorizontalAlignment="Center">
+ <!-- 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>
+
+ <!-- AI-client picker. Changing this
+ regenerates the config preview + the
+ path label + routes Install / Copy to
+ the right file. -->
+ <StackPanel Spacing="4">
+ <TextBlock Text="AI Client" FontSize="13" FontWeight="SemiBold" />
+ <ComboBox x:Name="ClientPicker" SelectedIndex="0" Width="260"
+ SelectionChanged="ClientPicker_SelectionChanged">
+ <ComboBoxItem Content="Claude Desktop" />
+ <ComboBoxItem Content="Claude Code (CLI / CCD)" />
+ <ComboBoxItem Content="Cursor" />
+ <ComboBoxItem Content="Windsurf" />
+ <ComboBoxItem Content="Gemini CLI" />
+ </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 x:Name="InstallBtnText"
+ 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"
+ IsReadOnly="True"
+ AcceptsReturn="True"
+ FontFamily="Consolas"
+ FontSize="12"
+ TextWrapping="NoWrap"
+ MinHeight="160" />
+ </Border>
+ </StackPanel>
+ </ScrollViewer>
+ </PivotItem>
+
+ <PivotItem Header="Config">
+ <ScrollViewer>
+ <StackPanel Spacing="16" MaxWidth="900" HorizontalAlignment="Center">
+ <TextBlock Text="Rate Limits" FontSize="14" FontWeight="SemiBold" />
+ <Grid ColumnSpacing="16" RowSpacing="8">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="180" />
+ </Grid.ColumnDefinitions>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ </Grid.RowDefinitions>
+
+ <TextBlock Text="Queries per minute" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="QpmBox" Grid.Row="0" Grid.Column="1"
+ Minimum="10" Maximum="500" Value="60" />
+ <TextBlock Text="Queries per hour" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="QphBox" Grid.Row="1" Grid.Column="1"
+ Minimum="100" Maximum="10000" Value="1000" />
+ <TextBlock Text="Writes per minute" Grid.Row="2" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="WpmBox" Grid.Row="2" Grid.Column="1"
+ Minimum="1" Maximum="100" Value="10" />
+ <TextBlock Text="DDL per minute" Grid.Row="3" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="DdlBox" Grid.Row="3" Grid.Column="1"
+ 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="180" />
+ </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>
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="180" />
+ </Grid.ColumnDefinitions>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ </Grid.RowDefinitions>
+ <TextBlock Text="Retention (days)" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="RetentionBox" Grid.Row="0" Grid.Column="1"
+ Minimum="0" Maximum="3650" Value="90" />
+ <TextBlock Text="Max log size (MB)" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" />
+ <NumberBox x:Name="MaxSizeBox" Grid.Row="1" Grid.Column="1"
+ Minimum="10" Maximum="1000" Value="100" />
+ </Grid>
+
+ <Button x:Name="SaveConfigBtn"
+ Content="Save Config"
+ Style="{StaticResource AccentButtonStyle}"
+ HorizontalAlignment="Left"
+ Margin="0,8,0,0"
+ Click="SaveConfig_Click" />
+ <TextBlock x:Name="SaveConfigStatusText"
+ FontSize="11"
+ Foreground="{ThemeResource TextFillColorTertiaryBrush}" />
+ </StackPanel>
+ </ScrollViewer>
+ </PivotItem>
+ </Pivot>
+ </Grid>
+ </Grid>
+</Page>
diff --git a/windows/Gridex/Models/AppSettings.h b/windows/Gridex/Models/AppSettings.h
index 402da1d..ee36af8 100644
--- a/windows/Gridex/Models/AppSettings.h
+++ b/windows/Gridex/Models/AppSettings.h
@@ -26,6 +26,36 @@ namespace DBModels
// Connection groups (user-defined labels)
std::vector<std::wstring> connectionGroups;
+ // ── MCP Server ───────────────────────────────────────
+ // All MCP prefs live in the same settings.json as the rest
+ // of the app (no separate file). Defaults mirror macOS so
+ // first-launch behavior is identical across platforms.
+
+ // Transport / server lifecycle
+ bool mcpEnabled = false;
+ bool mcpHttpEnabled = false;
+ int mcpHttpPort = 3333; // localhost by default
+ bool mcpAllowRemoteHTTP = false; // flips bind to 0.0.0.0
+ int64_t mcpStartTime = 0; // unix seconds; uptime tracking
+
+ // Security
+ bool mcpRequireApprovalForWrites = true;
+
+ // Rate limits (mac defaults)
+ int mcpQueriesPerMinute = 60;
+ int mcpQueriesPerHour = 1000;
+ int mcpWritesPerMinute = 10;
+ int mcpDdlPerMinute = 1;
+
+ // Timeouts (seconds)
+ int mcpQueryTimeout = 30;
+ int mcpApprovalTimeout = 60;
+ int mcpConnectionTimeout = 10;
+
+ // Audit log rotation (JSONL at %APPDATA%\Gridex\mcp-audit.jsonl)
+ int mcpAuditRetentionDays = 90;
+ int mcpAuditMaxSizeMB = 100;
+
// Load from file (returns default if file missing)
static AppSettings Load();
diff --git a/windows/Gridex/Models/ConnectionConfig.h b/windows/Gridex/Models/ConnectionConfig.h
index 605ad44..e90346b 100644
--- a/windows/Gridex/Models/ConnectionConfig.h
+++ b/windows/Gridex/Models/ConnectionConfig.h
@@ -4,6 +4,7 @@
#include <cstdint>
#include "DatabaseType.h"
#include "ColorTag.h"
+#include "MCP/MCPConnectionMode.h"
namespace DBModels
{
@@ -59,6 +60,11 @@ namespace DBModels
std::wstring mongoOptions;
std::optional<SSHTunnelConfig> sshConfig;
+ // Per-connection MCP access gate. Default Locked — every new
+ // connection must be explicitly opened up in MCPConnectionsView.
+ // Mirrors mac's ConnectionConfig.mcpMode.
+ MCPConnectionMode mcpMode = MCPConnectionMode::Locked;
+
std::wstring subtitle() const
{
if (databaseType == DatabaseType::SQLite)
diff --git a/windows/Gridex/Models/ConnectionStore.h b/windows/Gridex/Models/ConnectionStore.h
index 51f547b..72942d5 100644
--- a/windows/Gridex/Models/ConnectionStore.h
+++ b/windows/Gridex/Models/ConnectionStore.h
@@ -30,7 +30,7 @@ namespace DBModels
"sort_order, created_at, last_connected_at, connection_uri, "
"mongo_options, "
"ssh_host, ssh_port, ssh_username, ssh_password_enc, "
- "ssh_auth_method, ssh_key_path "
+ "ssh_auth_method, ssh_key_path, mcp_mode "
"FROM connections ORDER BY sort_order, name";
sqlite3_stmt* stmt = nullptr;
@@ -72,6 +72,9 @@ namespace DBModels
c.sshConfig = ssh;
}
}
+ // Column 24: per-connection MCP mode. Defaults to
+ // Locked (0) for rows created before the migration.
+ c.mcpMode = static_cast<MCPConnectionMode>(sqlite3_column_int(stmt, 24));
results.push_back(c);
}
sqlite3_finalize(stmt);
@@ -98,10 +101,10 @@ namespace DBModels
"sort_order, created_at, last_connected_at, connection_uri, "
"mongo_options, "
"ssh_host, ssh_port, ssh_username, ssh_password_enc, "
- "ssh_auth_method, ssh_key_path) "
+ "ssh_auth_method, ssh_key_path, mcp_mode) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0, "
"COALESCE((SELECT created_at FROM connections WHERE id=?), datetime('now')), "
- "datetime('now'), ?, ?, ?,?,?,?,?,?)";
+ "datetime('now'), ?, ?, ?,?,?,?,?,?,?)";
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) == SQLITE_OK)
@@ -143,6 +146,9 @@ namespace DBModels
sqlite3_bind_int(stmt, 21, 0);
BindText(stmt, 22, "");
}
+ // Placeholder 23: per-connection MCP mode. Defaults
+ // to Locked so new rows never auto-expose data to AI.
+ sqlite3_bind_int(stmt, 23, static_cast<int>(c.mcpMode));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
@@ -215,6 +221,10 @@ namespace DBModels
sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_password_enc TEXT DEFAULT ''", nullptr, nullptr, nullptr);
sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_auth_method INTEGER DEFAULT 0", nullptr, nullptr, nullptr);
sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN ssh_key_path TEXT DEFAULT ''", nullptr, nullptr, nullptr);
+ // Migration: per-connection MCP access mode (0=Locked, 1=ReadOnly, 2=ReadWrite).
+ // Default 0 keeps existing connections firewalled from AI until the
+ // user explicitly opens them up in the MCP Connections tab.
+ sqlite3_exec(db, "ALTER TABLE connections ADD COLUMN mcp_mode INTEGER DEFAULT 0", nullptr, nullptr, nullptr);
}
static std::wstring GetDbPath()
diff --git a/windows/Gridex/Models/Import/ImportedConnection.h b/windows/Gridex/Models/Import/ImportedConnection.h
new file mode 100644
index 0000000..9d5a6a9
--- /dev/null
+++ b/windows/Gridex/Models/Import/ImportedConnection.h
@@ -0,0 +1,103 @@
+#pragma once
+//
+// ImportedConnection.h
+// Gridex
+//
+// Shared data model for connections read from external GUI tools
+// (TablePlus, DBeaver, DataGrip, Navicat). Kept separate from
+// ConnectionConfig so the pre-import preview list doesn't pollute
+// the active store — user ticks rows in the wizard, then we
+// convert to ConnectionConfig on Import.
+//
+// Mirrors macos/Services/Import/ImportedConnection.swift 1:1; same
+// field names so cross-platform UI code can read either.
+
+#include <string>
+#include <optional>
+#include <vector>
+#include <cstdint>
+#include "../ConnectionConfig.h"
+
+namespace DBModels
+{
+ enum class ImportSource
+ {
+ TablePlus,
+ DBeaver,
+ DataGrip,
+ Navicat
+ };
+
+ inline std::wstring ImportSourceDisplayName(ImportSource s)
+ {
+ switch (s)
+ {
+ case ImportSource::TablePlus: return L"TablePlus";
+ case ImportSource::DBeaver: return L"DBeaver";
+ case ImportSource::DataGrip: return L"DataGrip";
+ case ImportSource::Navicat: return L"Navicat";
+ }
+ return L"Unknown";
+ }
+
+ inline std::wstring ImportSourceBadge(ImportSource s)
+ {
+ switch (s)
+ {
+ case ImportSource::TablePlus: return L"T+";
+ case ImportSource::DBeaver: return L"DB";
+ case ImportSource::DataGrip: return L"DG";
+ case ImportSource::Navicat: return L"N";
+ }
+ return L"?";
+ }
+
+ struct ImportedConnection
+ {
+ std::wstring id;
+ ImportSource source = ImportSource::DBeaver;
+ std::wstring name;
+ DatabaseType databaseType = DatabaseType::PostgreSQL;
+ std::wstring host;
+ std::optional<uint16_t> port;
+ std::wstring database;
+ std::wstring username;
+ std::wstring password; // may be empty when tool hides it
+ bool sslEnabled = false;
+ std::wstring filePath; // SQLite
+ std::wstring sshHost;
+ std::optional<uint16_t> sshPort;
+ std::wstring sshUser;
+ std::wstring group; // optional folder/group name
+
+ // Convert to ConnectionConfig ready to Save() into
+ // ConnectionStore. Caller should generate a fresh id if
+ // merging into an already-populated store (mac uses UUID —
+ // Windows ConnectionStore keys on wstring id).
+ ConnectionConfig toConnectionConfig() const
+ {
+ ConnectionConfig c;
+ c.id = id;
+ c.name = name;
+ c.databaseType = databaseType;
+ c.host = host;
+ c.port = port.value_or(DatabaseTypeDefaultPort(databaseType));
+ c.database = database;
+ c.username = username;
+ c.password = password;
+ c.sslEnabled = sslEnabled;
+ c.filePath = filePath;
+ c.group = group;
+ if (!sshHost.empty() && !sshUser.empty())
+ {
+ SSHTunnelConfig ssh;
+ ssh.host = sshHost;
+ ssh.port = sshPort.value_or(22);
+ ssh.username = sshUser;
+ ssh.authMethod = SSHAuthMethod::Password;
+ c.sshConfig = ssh;
+ }
+ return c;
+ }
+ };
+}
diff --git a/windows/Gridex/Models/MCP/MCPAuditEntry.h b/windows/Gridex/Models/MCP/MCPAuditEntry.h
new file mode 100644
index 0000000..e92bbd6
--- /dev/null
+++ b/windows/Gridex/Models/MCP/MCPAuditEntry.h
@@ -0,0 +1,177 @@
+#pragma once
+//
+// MCPAuditEntry.h
+// Gridex
+//
+// Audit log entry for MCP tool invocations. One of these is
+// serialized per line in mcp-audit.jsonl. Mirrors
+// macos/Core/Models/MCP/MCPAuditEntry.swift.
+//
+// IMPORTANT: this JSONL is cross-platform — the mac and Windows
+// builds write to the same format so `jq` and future sync work
+// uniformly. DO NOT rename or retype fields.
+
+#include <string>
+#include <optional>
+#include <vector>
+#include <chrono>
+#include <cstdint>
+#include <nlohmann/json.hpp>
+#include "MCPPermissionTier.h"
+#include "MCPConnectionMode.h"
+
+namespace DBModels
+{
+ // Raw status values match Swift MCPAuditStatus.
+ enum class MCPAuditStatus { Success, Error, Denied, Timeout };
+
+ inline std::string mcpAuditStatusRaw(MCPAuditStatus s)
+ {
+ switch (s)
+ {
+ case MCPAuditStatus::Success: return "success";
+ case MCPAuditStatus::Error: return "error";
+ case MCPAuditStatus::Denied: return "denied";
+ case MCPAuditStatus::Timeout: return "timeout";
+ }
+ return "success";
+ }
+
+ inline MCPAuditStatus mcpAuditStatusFromRaw(const std::string& raw)
+ {
+ if (raw == "error") return MCPAuditStatus::Error;
+ if (raw == "denied") return MCPAuditStatus::Denied;
+ if (raw == "timeout") return MCPAuditStatus::Timeout;
+ return MCPAuditStatus::Success;
+ }
+
+ struct MCPAuditClient
+ {
+ std::string name = "unknown";
+ std::string version = "0.0.0";
+ std::string transport = "stdio"; // "stdio" | "http"
+ };
+
+ // `sqlPreview` is truncated to 200 chars at construction so
+ // secrets can never leak through oversized logs. `inputHash`
+ // is a non-cryptographic correlation aid (std::hash), NOT a
+ // security primitive — documented explicitly for auditors.
+ struct MCPAuditInput
+ {
+ std::optional<std::string> sqlPreview;
+ std::optional<int> paramsCount;
+ std::optional<std::string> inputHash;
+
+ static MCPAuditInput fromSQL(const std::string& sql, std::optional<int> paramsCount = std::nullopt)
+ {
+ MCPAuditInput i;
+ if (!sql.empty())
+ {
+ const std::string preview = sql.size() > 200 ? sql.substr(0, 200) + "..." : sql;
+ i.sqlPreview = preview;
+ // 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;
+ }
+ };
+
+ struct MCPAuditResult
+ {
+ MCPAuditStatus status = MCPAuditStatus::Success;
+ std::optional<int> rowsAffected;
+ std::optional<int> rowsReturned;
+ int durationMs = 0;
+ std::optional<int64_t> bytesReturned;
+ };
+
+ struct MCPAuditSecurity
+ {
+ MCPConnectionMode permissionMode = MCPConnectionMode::Locked;
+ std::optional<bool> userApproved;
+ std::optional<std::string> approvalSessionId;
+ std::optional<std::vector<std::string>> scopesApplied;
+ };
+
+ struct MCPAuditEntry
+ {
+ // ISO-8601 UTC — formatted lazily in to_json so we don't
+ // depend on C++20 chrono formatters.
+ std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now();
+ std::string eventId; // UUID-like string (UuidCreate → hex)
+ MCPAuditClient client;
+ std::string tool;
+ int tier = 1; // MCPPermissionTier::Schema
+ std::optional<std::string> connectionId;
+ std::optional<std::string> connectionType; // "postgres"/"mysql"/...
+ MCPAuditInput input;
+ MCPAuditResult result;
+ MCPAuditSecurity security;
+ std::optional<std::string> error;
+ };
+
+ // ── Serialization ─────────────────────────────────────────
+ // These write the same field names Swift uses so mac + Windows
+ // logs are indistinguishable on disk.
+
+ inline std::string mcpFormatIso8601(std::chrono::system_clock::time_point tp)
+ {
+ // strftime-based path — portable across MSVC versions where
+ // std::format chrono support varies. Emits "YYYY-MM-DDTHH:MM:SSZ".
+ const std::time_t t = std::chrono::system_clock::to_time_t(tp);
+ std::tm tm{};
+#if defined(_WIN32)
+ gmtime_s(&tm, &t);
+#else
+ gmtime_r(&t, &tm);
+#endif
+ char buf[32];
+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm);
+ return std::string(buf);
+ }
+
+ inline void to_json(nlohmann::json& j, const MCPAuditEntry& e)
+ {
+ j = nlohmann::json{
+ {"timestamp", mcpFormatIso8601(e.timestamp)},
+ {"eventId", e.eventId},
+ {"tool", e.tool},
+ {"tier", e.tier},
+ {"client", {
+ {"name", e.client.name},
+ {"version", e.client.version},
+ {"transport", e.client.transport}
+ }},
+ {"result", {
+ {"status", mcpAuditStatusRaw(e.result.status)},
+ {"durationMs", e.result.durationMs}
+ }},
+ {"security", {
+ {"permissionMode", mcpRawString(e.security.permissionMode)}
+ }}
+ };
+ if (e.connectionId.has_value()) j["connectionId"] = *e.connectionId;
+ if (e.connectionType.has_value()) j["connectionType"] = *e.connectionType;
+ if (e.input.sqlPreview.has_value()) j["input"]["sqlPreview"] = *e.input.sqlPreview;
+ if (e.input.paramsCount.has_value()) j["input"]["paramsCount"] = *e.input.paramsCount;
+ if (e.input.inputHash.has_value()) j["input"]["inputHash"] = *e.input.inputHash;
+ if (e.result.rowsAffected.has_value()) j["result"]["rowsAffected"] = *e.result.rowsAffected;
+ if (e.result.rowsReturned.has_value()) j["result"]["rowsReturned"] = *e.result.rowsReturned;
+ if (e.result.bytesReturned.has_value()) j["result"]["bytesReturned"] = *e.result.bytesReturned;
+ if (e.security.userApproved.has_value()) j["security"]["userApproved"] = *e.security.userApproved;
+ if (e.security.approvalSessionId.has_value()) j["security"]["approvalSessionId"] = *e.security.approvalSessionId;
+ if (e.error.has_value()) j["error"] = *e.error;
+ }
+}
diff --git a/windows/Gridex/Models/MCP/MCPConnectionMode.h b/windows/Gridex/Models/MCP/MCPConnectionMode.h
new file mode 100644
index 0000000..3fadf1c
--- /dev/null
+++ b/windows/Gridex/Models/MCP/MCPConnectionMode.h
@@ -0,0 +1,75 @@
+#pragma once
+//
+// MCPConnectionMode.h
+// Gridex
+//
+// MCP access mode for database connections. Mirrors
+// macos/Core/Enums/MCPConnectionMode.swift 1:1 so the on-disk raw
+// strings ("locked" / "read_only" / "read_write") are identical
+// between platforms — this keeps audit JSONL grep-friendly and
+// makes future cloud-sync trivial.
+
+#include <string>
+
+namespace DBModels
+{
+ enum class MCPConnectionMode
+ {
+ Locked = 0,
+ ReadOnly = 1,
+ ReadWrite = 2
+ };
+
+ inline std::wstring mcpDisplayName(MCPConnectionMode mode)
+ {
+ switch (mode)
+ {
+ case MCPConnectionMode::Locked: return L"Locked";
+ case MCPConnectionMode::ReadOnly: return L"Read-only";
+ case MCPConnectionMode::ReadWrite: return L"Read-write";
+ }
+ return L"Unknown";
+ }
+
+ inline std::wstring mcpDescription(MCPConnectionMode mode)
+ {
+ switch (mode)
+ {
+ case MCPConnectionMode::Locked:
+ return L"AI cannot access this connection";
+ case MCPConnectionMode::ReadOnly:
+ return L"AI can query but not modify (recommended for production)";
+ case MCPConnectionMode::ReadWrite:
+ return L"AI can modify with your approval (use for dev only)";
+ }
+ return L"";
+ }
+
+ // Cross-platform raw string used in audit JSONL + REST payloads.
+ // MUST match macOS Swift rawValue ("locked", "read_only", "read_write").
+ inline std::string mcpRawString(MCPConnectionMode mode)
+ {
+ switch (mode)
+ {
+ case MCPConnectionMode::Locked: return "locked";
+ case MCPConnectionMode::ReadOnly: return "read_only";
+ case MCPConnectionMode::ReadWrite: return "read_write";
+ }
+ return "locked";
+ }
+
+ inline MCPConnectionMode mcpModeFromRawString(const std::string& raw)
+ {
+ if (raw == "read_only") return MCPConnectionMode::ReadOnly;
+ if (raw == "read_write") return MCPConnectionMode::ReadWrite;
+ return MCPConnectionMode::Locked;
+ }
+
+ // Per-tier allowance. Matches Swift `allowsTierN` exactly — do
+ // not drift; the permission engine in Phase 2 relies on these.
+ inline bool mcpAllowsTier1(MCPConnectionMode m) { return m != MCPConnectionMode::Locked; }
+ inline bool mcpAllowsTier2(MCPConnectionMode m) { return m != MCPConnectionMode::Locked; }
+ inline bool mcpAllowsTier3(MCPConnectionMode m) { return m == MCPConnectionMode::ReadWrite; }
+ inline bool mcpAllowsTier4(MCPConnectionMode m) { return m == MCPConnectionMode::ReadWrite; }
+ inline bool mcpAllowsTier5(MCPConnectionMode m) { return m != MCPConnectionMode::Locked; }
+}
diff --git a/windows/Gridex/Models/MCP/MCPErrorCode.h b/windows/Gridex/Models/MCP/MCPErrorCode.h
new file mode 100644
index 0000000..5732012
--- /dev/null
+++ b/windows/Gridex/Models/MCP/MCPErrorCode.h
@@ -0,0 +1,26 @@
+#pragma once
+//
+// MCPErrorCode.h
+// Gridex
+//
+// Gridex-specific JSON-RPC error codes. The integer values are part
+// of the MCP client contract and MUST match macOS
+// (macos/Core/Models/MCP/MCPProtocol.swift : MCPErrorCode) exactly.
+// Claude Desktop, Cursor, etc. surface these codes to the user, so
+// renumbering would silently break downstream clients.
+
+namespace DBModels
+{
+ enum class MCPErrorCode : int
+ {
+ PermissionDenied = -32001,
+ ApprovalTimeout = -32002,
+ ApprovalDenied = -32003,
+ ConnectionError = -32004,
+ SyntaxError = -32005,
+ NotFound = -32006,
+ RateLimitExceeded = -32007,
+ ScopeDenied = -32008,
+ QueryTimeout = -32009
+ };
+}
diff --git a/windows/Gridex/Models/MCP/MCPPermissionTier.h b/windows/Gridex/Models/MCP/MCPPermissionTier.h
new file mode 100644
index 0000000..63f4aa5
--- /dev/null
+++ b/windows/Gridex/Models/MCP/MCPPermissionTier.h
@@ -0,0 +1,49 @@
+#pragma once
+//
+// MCPPermissionTier.h
+// Gridex
+//
+// Permission tiers for MCP tools. Mirrors
+// macos/Core/Enums/MCPPermissionTier.swift.
+//
+// Tier numbering is part of the client-facing audit contract — do
+// NOT renumber. New tiers append at the end.
+
+#include <string>
+
+namespace DBModels
+{
+ enum class MCPPermissionTier
+ {
+ Schema = 1, // Schema introspection (read-only, no approval)
+ Read = 2, // Query execution (read, no approval by default)
+ Write = 3, // Data modification (REQUIRES approval)
+ DDL = 4, // Schema change (CRITICAL approval)
+ Advanced = 5 // Reserved for future (EXPLAIN, etc.)
+ };
+
+ inline std::wstring mcpTierDisplayName(MCPPermissionTier t)
+ {
+ switch (t)
+ {
+ case MCPPermissionTier::Schema: return L"Schema";
+ case MCPPermissionTier::Read: return L"Read";
+ case MCPPermissionTier::Write: return L"Write";
+ case MCPPermissionTier::DDL: return L"DDL";
+ case MCPPermissionTier::Advanced: return L"Advanced";
+ }
+ return L"";
+ }
+
+ inline bool mcpTierRequiresApproval(MCPPermissionTier t)
+ {
+ return t == MCPPermissionTier::Write
+ || t == MCPPermissionTier::DDL
+ || t == MCPPermissionTier::Advanced;
+ }
+
+ inline bool mcpTierIsReadOnly(MCPPermissionTier t)
+ {
+ return t == MCPPermissionTier::Schema || t == MCPPermissionTier::Read;
+ }
+}
diff --git a/windows/Gridex/Models/MCP/MCPProtocol.h b/windows/Gridex/Models/MCP/MCPProtocol.h
new file mode 100644
index 0000000..41693a0
--- /dev/null
+++ b/windows/Gridex/Models/MCP/MCPProtocol.h
@@ -0,0 +1,147 @@
+#pragma once
+//
+// MCPProtocol.h
+// Gridex
+//
+// JSON-RPC 2.0 types for MCP. Mirrors the Swift structs in
+// macos/Core/Models/MCP/MCPProtocol.swift. All shapes use
+// nlohmann::json for dynamic fields (params, id, result) — this
+// avoids the hand-rolled JSONValue sum type on Swift side and
+// keeps codec glue trivial.
+//
+// All types live in namespace DBModels and ship ADL-compatible
+// `to_json` / `from_json` so nlohmann's generic `json(req)` and
+// `j.get<JSONRPCRequest>()` round-trip losslessly.
+
+#include <string>
+#include <optional>
+#include <nlohmann/json.hpp>
+#include "MCPErrorCode.h"
+
+namespace DBModels
+{
+ // ── JSON-RPC core ──────────────────────────────────────────
+
+ struct JSONRPCError
+ {
+ int code = 0;
+ std::string message;
+ nlohmann::json data; // optional arbitrary payload
+
+ // Canonical JSON-RPC 2.0 errors (see spec).
+ static JSONRPCError parseError() { return { -32700, "Parse error", nullptr }; }
+ static JSONRPCError invalidRequest() { return { -32600, "Invalid Request", nullptr }; }
+ static JSONRPCError methodNotFound() { return { -32601, "Method not found", nullptr }; }
+ static JSONRPCError invalidParams() { return { -32602, "Invalid params", nullptr }; }
+ static JSONRPCError internalError() { return { -32603, "Internal error", nullptr }; }
+
+ static JSONRPCError fromCode(MCPErrorCode c, const std::string& msg)
+ {
+ return { static_cast<int>(c), msg, nullptr };
+ }
+ };
+
+ inline void to_json(nlohmann::json& j, const JSONRPCError& e)
+ {
+ j = nlohmann::json{{"code", e.code}, {"message", e.message}};
+ if (!e.data.is_null()) j["data"] = e.data;
+ }
+
+ inline void from_json(const nlohmann::json& j, JSONRPCError& e)
+ {
+ e.code = j.value("code", 0);
+ e.message = j.value("message", std::string{});
+ e.data = j.value("data", nlohmann::json{});
+ }
+
+ struct JSONRPCRequest
+ {
+ std::string jsonrpc = "2.0";
+ nlohmann::json id; // int | string | null (notification)
+ std::string method;
+ nlohmann::json params; // object | array | null
+ };
+
+ inline void to_json(nlohmann::json& j, const JSONRPCRequest& r)
+ {
+ j = nlohmann::json{{"jsonrpc", r.jsonrpc}, {"method", r.method}};
+ if (!r.id.is_null()) j["id"] = r.id;
+ if (!r.params.is_null()) j["params"] = r.params;
+ }
+
+ inline void from_json(const nlohmann::json& j, JSONRPCRequest& r)
+ {
+ r.jsonrpc = j.value("jsonrpc", std::string{"2.0"});
+ r.id = j.value("id", nlohmann::json{});
+ r.method = j.value("method", std::string{});
+ r.params = j.value("params", nlohmann::json{});
+ }
+
+ struct JSONRPCResponse
+ {
+ std::string jsonrpc = "2.0";
+ nlohmann::json id; // echoed from request
+ std::optional<nlohmann::json> result; // success
+ std::optional<JSONRPCError> error; // failure (mutually exclusive)
+
+ static JSONRPCResponse ok(const nlohmann::json& id, const nlohmann::json& result)
+ {
+ JSONRPCResponse r;
+ r.id = id;
+ r.result = result;
+ return r;
+ }
+
+ static JSONRPCResponse fail(const nlohmann::json& id, const JSONRPCError& err)
+ {
+ JSONRPCResponse r;
+ r.id = id;
+ r.error = err;
+ return r;
+ }
+ };
+
+ inline void to_json(nlohmann::json& j, const JSONRPCResponse& r)
+ {
+ j = nlohmann::json{{"jsonrpc", r.jsonrpc}, {"id", r.id}};
+ if (r.result.has_value()) j["result"] = *r.result;
+ if (r.error.has_value())
+ {
+ nlohmann::json ej;
+ to_json(ej, *r.error);
+ j["error"] = ej;
+ }
+ }
+
+ inline void from_json(const nlohmann::json& j, JSONRPCResponse& r)
+ {
+ r.jsonrpc = j.value("jsonrpc", std::string{"2.0"});
+ r.id = j.value("id", nlohmann::json{});
+ if (j.contains("result")) r.result = j.at("result");
+ if (j.contains("error"))
+ {
+ JSONRPCError e;
+ from_json(j.at("error"), e);
+ r.error = e;
+ }
+ }
+
+ // ── Client info ────────────────────────────────────────────
+
+ struct MCPClientInfo
+ {
+ std::string name = "unknown";
+ std::string version = "0.0.0";
+ };
+
+ inline void to_json(nlohmann::json& j, const MCPClientInfo& c)
+ {
+ j = nlohmann::json{{"name", c.name}, {"version", c.version}};
+ }
+
+ inline void from_json(const nlohmann::json& j, MCPClientInfo& c)
+ {
+ c.name = j.value("name", std::string{"unknown"});
+ c.version = j.value("version", std::string{"0.0.0"});
+ }
+}
diff --git a/windows/Gridex/Models/MCP/MCPServerInfo.h b/windows/Gridex/Models/MCP/MCPServerInfo.h
new file mode 100644
index 0000000..1636041
--- /dev/null
+++ b/windows/Gridex/Models/MCP/MCPServerInfo.h
@@ -0,0 +1,46 @@
+#pragma once
+//
+// MCPServerInfo.h
+// Gridex
+//
+// Server advertisement returned in `initialize` handshake. Mirrors
+// MCPServerInfo.gridex() in macos/Core/Models/MCP/MCPProtocol.swift.
+// The `protocolVersion` string is dictated by the MCP spec (see
+// https://spec.modelcontextprotocol.io) — do NOT bump without
+// first validating that Claude Desktop / Cursor / etc still accept
+// the new value.
+
+#include <string>
+#include <nlohmann/json.hpp>
+
+namespace DBModels
+{
+ struct MCPServerInfo
+ {
+ std::string name = "gridex";
+ std::string version;
+ std::string protocolVersion = "2024-11-05";
+
+ static MCPServerInfo gridex(const std::string& appVersion)
+ {
+ MCPServerInfo s;
+ s.version = appVersion;
+ return s;
+ }
+ };
+
+ // Capabilities advertised in `initialize` result. We only
+ // implement `tools` right now — advertising `resources` /
+ // `prompts` the way macOS does would be a protocol lie since
+ // we return methodNotFound on their list endpoints, and
+ // Claude CLI drops the connection when the server contradicts
+ // its own capability manifest. Expose tools only; prompts +
+ // resources land when their handlers do.
+ inline nlohmann::json mcpDefaultCapabilities()
+ {
+ return {
+ {"tools", {{"listChanged", true}}},
+ {"logging", nlohmann::json::object()}
+ };
+ }
+}
diff --git a/windows/Gridex/Models/MCP/MCPToolDefinition.h b/windows/Gridex/Models/MCP/MCPToolDefinition.h
new file mode 100644
index 0000000..7dbc9f9
--- /dev/null
+++ b/windows/Gridex/Models/MCP/MCPToolDefinition.h
@@ -0,0 +1,90 @@
+#pragma once
+//
+// MCPToolDefinition.h
+// Gridex
+//
+// Tool metadata + execution result for the MCP tools/list and
+// tools/call protocol methods. Mirrors MCPToolDefinition / MCPContent
+// / MCPToolResult in macos/Core/Models/MCP/MCPProtocol.swift.
+
+#include <string>
+#include <vector>
+#include <optional>
+#include <nlohmann/json.hpp>
+
+namespace DBModels
+{
+ // Emitted by tools/list. `inputSchema` is a JSON Schema object
+ // the AI client uses to validate arguments before calling.
+ struct MCPToolDefinition
+ {
+ std::string name;
+ std::string description;
+ nlohmann::json inputSchema; // JSON Schema object
+ };
+
+ inline void to_json(nlohmann::json& j, const MCPToolDefinition& t)
+ {
+ j = nlohmann::json{
+ {"name", t.name},
+ {"description", t.description},
+ {"inputSchema", t.inputSchema}
+ };
+ }
+
+ // Single content chunk in a tool result. Matches the MCP spec
+ // encoding for type="text" | "image" | "resource" items.
+ struct MCPContent
+ {
+ std::string type = "text"; // "text" | "image" | ...
+ std::optional<std::string> text;
+ std::optional<std::string> data; // base64 for image
+ std::optional<std::string> mimeType; // for image / resource
+ };
+
+ inline void to_json(nlohmann::json& j, const MCPContent& c)
+ {
+ j = nlohmann::json{{"type", c.type}};
+ if (c.text.has_value()) j["text"] = *c.text;
+ if (c.data.has_value()) j["data"] = *c.data;
+ if (c.mimeType.has_value()) j["mimeType"] = *c.mimeType;
+ }
+
+ // Full tool result — one or more content chunks + error flag.
+ // `isError` makes the client surface the text as an AI-visible
+ // error rather than a normal tool success output.
+ struct MCPToolResult
+ {
+ std::vector<MCPContent> content;
+ bool isError = false;
+
+ static MCPToolResult text(const std::string& s, bool err = false)
+ {
+ MCPToolResult r;
+ MCPContent c;
+ c.type = "text";
+ c.text = s;
+ r.content.push_back(std::move(c));
+ r.isError = err;
+ return r;
+ }
+
+ static MCPToolResult error(const std::string& message)
+ {
+ return text(message, true);
+ }
+ };
+
+ inline void to_json(nlohmann::json& j, const MCPToolResult& r)
+ {
+ nlohmann::json arr = nlohmann::json::array();
+ for (const auto& c : r.content)
+ {
+ nlohmann::json cj;
+ to_json(cj, c);
+ arr.push_back(cj);
+ }
+ j = nlohmann::json{{"content", arr}};
+ if (r.isError) j["isError"] = true;
+ }
+}
diff --git a/windows/Gridex/Models/MCP/MCPToolError.h b/windows/Gridex/Models/MCP/MCPToolError.h
new file mode 100644
index 0000000..d109fc2
--- /dev/null
+++ b/windows/Gridex/Models/MCP/MCPToolError.h
@@ -0,0 +1,84 @@
+#pragma once
+//
+// MCPToolError.h
+// Gridex
+//
+// Typed exception thrown by MCP tools. The MCPServer catches these
+// and folds them into MCPToolResult::error(...) so the AI client
+// sees a structured failure message. Mirrors MCPToolError in
+// macos/Services/MCP/Tools/MCPTool.swift.
+//
+// Tools should throw via the static factories rather than
+// constructing directly — this keeps the message format consistent
+// with macOS.
+
+#include <stdexcept>
+#include <string>
+
+namespace DBModels
+{
+ class MCPToolError : public std::runtime_error
+ {
+ public:
+ enum class Kind
+ {
+ ConnectionNotFound,
+ ConnectionNotConnected,
+ TableNotFound,
+ InvalidParameters,
+ PermissionDenied,
+ QueryFailed,
+ RateLimitExceeded
+ };
+
+ Kind kind;
+ int retryAfterSeconds = 0; // only meaningful for RateLimitExceeded
+
+ MCPToolError(Kind k, const std::string& msg, int retryAfter = 0)
+ : std::runtime_error(msg), kind(k), retryAfterSeconds(retryAfter) {}
+
+ // ── Factories — keep messages identical to Swift for UX parity ──
+
+ static MCPToolError connectionNotFound(const std::string& id)
+ {
+ return MCPToolError(Kind::ConnectionNotFound,
+ "Connection '" + id + "' not found. Use list_connections to see available connections.");
+ }
+
+ static MCPToolError connectionNotConnected(const std::string& id)
+ {
+ return MCPToolError(Kind::ConnectionNotConnected,
+ "Connection '" + id + "' is not active. The user needs to connect first.");
+ }
+
+ static MCPToolError tableNotFound(const std::string& name)
+ {
+ return MCPToolError(Kind::TableNotFound,
+ "Table '" + name + "' not found.");
+ }
+
+ static MCPToolError invalidParameters(const std::string& msg)
+ {
+ return MCPToolError(Kind::InvalidParameters,
+ "Invalid parameters: " + msg);
+ }
+
+ static MCPToolError permissionDenied(const std::string& msg)
+ {
+ return MCPToolError(Kind::PermissionDenied, msg);
+ }
+
+ static MCPToolError queryFailed(const std::string& msg)
+ {
+ return MCPToolError(Kind::QueryFailed,
+ "Query failed: " + msg);
+ }
+
+ static MCPToolError rateLimitExceeded(int retryAfter)
+ {
+ return MCPToolError(Kind::RateLimitExceeded,
+ "Rate limit exceeded. Retry after " + std::to_string(retryAfter) + " seconds.",
+ retryAfter);
+ }
+ };
+}
diff --git a/windows/Gridex/Services/Import/DBeaverImporter.cpp b/windows/Gridex/Services/Import/DBeaverImporter.cpp
new file mode 100644
index 0000000..ebb45fb
--- /dev/null
+++ b/windows/Gridex/Services/Import/DBeaverImporter.cpp
@@ -0,0 +1,256 @@
+//
+// DBeaverImporter.cpp
+//
+
+#include "DBeaverImporter.h"
+
+#include <windows.h>
+#include <shlobj.h>
+#include <fstream>
+#include <string>
+#include <unordered_map>
+#include <nlohmann/json.hpp>
+
+namespace DBModels { namespace DBeaverImporter {
+
+namespace {
+ std::wstring appDataDir()
+ {
+ wchar_t* p = nullptr;
+ if (SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p) != S_OK)
+ return {};
+ std::wstring out(p);
+ CoTaskMemFree(p);
+ return out;
+ }
+
+ std::wstring dataSourcesPath()
+ {
+ auto r = appDataDir();
+ if (r.empty()) return {};
+ return r + L"\\DBeaverData\\workspace6\\General\\.dbeaver\\data-sources.json";
+ }
+ std::wstring credentialsPath()
+ {
+ auto r = appDataDir();
+ if (r.empty()) return {};
+ return r + L"\\DBeaverData\\workspace6\\General\\.dbeaver\\credentials-config.json";
+ }
+
+ std::wstring fromUtf8(const std::string& s)
+ {
+ if (s.empty()) return {};
+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);
+ std::wstring out(sz, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &out[0], sz);
+ return out;
+ }
+
+ DatabaseType mapProvider(const std::string& p)
+ {
+ std::string lower; lower.reserve(p.size());
+ for (char c : p) lower.push_back(static_cast<char>(std::tolower((unsigned char)c)));
+ if (lower.find("postgres") != std::string::npos) return DatabaseType::PostgreSQL;
+ if (lower.find("mysql") != std::string::npos || lower.find("maria") != std::string::npos)
+ return DatabaseType::MySQL;
+ if (lower.find("sqlite") != std::string::npos) return DatabaseType::SQLite;
+ if (lower.find("redis") != std::string::npos) return DatabaseType::Redis;
+ if (lower.find("mongo") != std::string::npos) return DatabaseType::MongoDB;
+ if (lower.find("sqlserver") != std::string::npos || lower.find("mssql") != std::string::npos)
+ return DatabaseType::MSSQLServer;
+ return DatabaseType::PostgreSQL;
+ }
+
+ // Base64 decode (stateless, std-only). Accepts the single-line
+ // form DBeaver emits; newlines/whitespace ignored.
+ std::vector<uint8_t> base64Decode(const std::string& s)
+ {
+ int map[256];
+ for (int i = 0; i < 256; ++i) map[i] = -1;
+ const char* cs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ for (int i = 0; i < 64; ++i) map[(unsigned char)cs[i]] = i;
+
+ std::vector<uint8_t> out;
+ uint32_t buf = 0; int bits = 0;
+ for (unsigned char c : s)
+ {
+ if (c == '=' || c == '\n' || c == '\r' || c == ' ' || c == '\t') continue;
+ int v = map[c];
+ if (v < 0) continue;
+ buf = (buf << 6) | v;
+ bits += 6;
+ if (bits >= 8) { bits -= 8; out.push_back(static_cast<uint8_t>((buf >> bits) & 0xFF)); }
+ }
+ return out;
+ }
+
+ // DBeaver ships a fixed 8-byte XOR key for its credentials file.
+ // Constant is reverse-engineered from the upstream Java source.
+ std::string xorDecrypt(const std::vector<uint8_t>& cipher)
+ {
+ static const uint8_t K[8] = { 0xBA, 0xBB, 0x4A, 0x9F, 0x7A, 0xEE, 0x8F, 0xC1 };
+ std::string out(cipher.size(), '\0');
+ for (size_t i = 0; i < cipher.size(); ++i)
+ out[i] = static_cast<char>(cipher[i] ^ K[i % 8]);
+ return out;
+ }
+
+ // key in credentials-config.json is "data-source|<connId>"; we
+ // strip the prefix so lookups match the connection UUID from
+ // data-sources.json.
+ std::unordered_map<std::string, std::pair<std::string, std::string>> loadCredentials()
+ {
+ std::unordered_map<std::string, std::pair<std::string, std::string>> out;
+ const auto path = credentialsPath();
+ if (path.empty() || GetFileAttributesW(path.c_str()) == INVALID_FILE_ATTRIBUTES)
+ return out;
+ std::ifstream in(path, std::ios::binary);
+ if (!in.is_open()) return out;
+ std::string cipher((std::istreambuf_iterator<char>(in)),
+ std::istreambuf_iterator<char>());
+ if (cipher.empty()) return out;
+ auto bytes = base64Decode(cipher);
+ auto json = xorDecrypt(bytes);
+ try
+ {
+ auto j = nlohmann::json::parse(json, nullptr, false);
+ if (j.is_discarded() || !j.is_object()) return out;
+ for (auto it = j.begin(); it != j.end(); ++it)
+ {
+ std::string key = it.key();
+ const std::string prefix = "data-source|";
+ if (key.rfind(prefix, 0) == 0) key.erase(0, prefix.size());
+ if (!it.value().is_object()) continue;
+ const auto& v = it.value();
+ out[key] = {
+ v.value("user", std::string{}),
+ v.value("password", std::string{})
+ };
+ }
+ }
+ catch (...) { out.clear(); }
+ return out;
+ }
+
+ // DBeaver sometimes ships host/port/db inside a bare JDBC URL
+ // rather than discrete fields. Pull each piece with a tiny
+ // substring scanner — std::regex would work but this avoids
+ // the compile-once cost on an already-hot import path.
+ struct JdbcParts { std::string host; std::optional<int> port; std::string db; };
+ JdbcParts parseJdbcUrl(const std::string& url)
+ {
+ JdbcParts p;
+ auto colSlash = url.find("://");
+ if (colSlash == std::string::npos) return p;
+ size_t i = colSlash + 3;
+ size_t endHost = url.find_first_of(":/;?", i);
+ if (endHost == std::string::npos) endHost = url.size();
+ p.host = url.substr(i, endHost - i);
+
+ if (endHost < url.size() && url[endHost] == ':')
+ {
+ size_t j = endHost + 1;
+ std::string numStr;
+ while (j < url.size() && std::isdigit((unsigned char)url[j])) numStr += url[j++];
+ if (!numStr.empty()) { try { p.port = std::stoi(numStr); } catch (...) {} }
+ endHost = j;
+ }
+ if (endHost < url.size() && url[endHost] == '/')
+ {
+ size_t j = endHost + 1;
+ size_t endDb = url.find_first_of("?;", j);
+ if (endDb == std::string::npos) endDb = url.size();
+ p.db = url.substr(j, endDb - j);
+ }
+ return p;
+ }
+}
+
+bool isInstalled()
+{
+ const auto p = dataSourcesPath();
+ return !p.empty() && GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES;
+}
+
+std::vector<ImportedConnection> importConnections()
+{
+ std::vector<ImportedConnection> out;
+ const auto path = dataSourcesPath();
+ if (path.empty()) return out;
+ std::ifstream in(path, std::ios::binary);
+ if (!in.is_open()) return out;
+
+ nlohmann::json root;
+ try { in >> root; } catch (...) { return out; }
+ if (!root.is_object()) return out;
+
+ const auto creds = loadCredentials();
+
+ // Top-level object groups by folder name. Each folder has a
+ // `connections` map keyed by UUID.
+ for (auto fit = root.begin(); fit != root.end(); ++fit)
+ {
+ if (!fit.value().is_object()) continue;
+ const auto& folder = fit.value();
+ if (!folder.contains("connections") || !folder["connections"].is_object()) continue;
+
+ const auto& conns = folder["connections"];
+ for (auto cit = conns.begin(); cit != conns.end(); ++cit)
+ {
+ if (!cit.value().is_object()) continue;
+ const std::string connId = cit.key();
+ const auto& c = cit.value();
+
+ std::string name = c.value("name", std::string{});
+ std::string provider = c.value("provider", std::string{});
+ if (name.empty()) continue;
+
+ const auto& conf = c.contains("configuration") && c["configuration"].is_object()
+ ? c["configuration"] : nlohmann::json::object();
+
+ std::string host = conf.value("host", std::string{});
+ std::string portStr = conf.value("port", std::string{});
+ std::string database = conf.value("database", std::string{});
+ std::string url = conf.value("url", std::string{});
+ std::string sslStr = conf.value("ssl", std::string{});
+ std::string authModel= conf.value("auth-model", std::string{});
+
+ ImportedConnection r;
+ r.id = fromUtf8(connId);
+ r.source = ImportSource::DBeaver;
+ r.name = fromUtf8(name);
+ r.databaseType = mapProvider(provider);
+ r.sslEnabled = (sslStr == "true");
+
+ if (!host.empty()) r.host = fromUtf8(host);
+ if (!portStr.empty()) { try { r.port = static_cast<uint16_t>(std::stoi(portStr)); } catch (...) {} }
+ if (!database.empty()) r.database = fromUtf8(database);
+
+ // Fallback: scrape host/port/db from the bare JDBC URL
+ // when DBeaver doesn't surface the discrete fields.
+ if ((r.host.empty() || !r.port.has_value() || r.database.empty()) && !url.empty())
+ {
+ const auto p = parseJdbcUrl(url);
+ if (r.host.empty() && !p.host.empty()) r.host = fromUtf8(p.host);
+ if (!r.port.has_value() && p.port.has_value())
+ r.port = static_cast<uint16_t>(*p.port);
+ if (r.database.empty() && !p.db.empty()) r.database = fromUtf8(p.db);
+ }
+
+ if (authModel == "native")
+ {
+ auto it = creds.find(connId);
+ if (it != creds.end())
+ {
+ r.username = fromUtf8(it->second.first);
+ r.password = fromUtf8(it->second.second);
+ }
+ }
+
+ out.push_back(std::move(r));
+ }
+ }
+ return out;
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/Import/DBeaverImporter.h b/windows/Gridex/Services/Import/DBeaverImporter.h
new file mode 100644
index 0000000..6c67dec
--- /dev/null
+++ b/windows/Gridex/Services/Import/DBeaverImporter.h
@@ -0,0 +1,20 @@
+#pragma once
+//
+// DBeaverImporter.h
+// Gridex
+//
+// Reads %APPDATA%\DBeaverData\workspace6\General\.dbeaver\
+// data-sources.json and credentials-config.json, returns the
+// connections as ImportedConnection. Mirrors mac DBeaverImporter.
+// The credentials file uses a fixed 8-byte XOR key — same key
+// across mac + Windows installs since DBeaver is Java.
+
+#include <vector>
+#include "../../Models/Import/ImportedConnection.h"
+
+namespace DBModels { namespace DBeaverImporter {
+
+bool isInstalled();
+std::vector<ImportedConnection> importConnections();
+
+}} // namespace
diff --git a/windows/Gridex/Services/Import/DataGripImporter.cpp b/windows/Gridex/Services/Import/DataGripImporter.cpp
new file mode 100644
index 0000000..ff5d3c7
--- /dev/null
+++ b/windows/Gridex/Services/Import/DataGripImporter.cpp
@@ -0,0 +1,251 @@
+//
+// DataGripImporter.cpp
+//
+// Scans %APPDATA%\JetBrains for any directory starting with
+// "DataGrip" (e.g. "DataGrip2024.3"), reads options/dataSources.xml,
+// and yields ImportedConnection rows. Hand-rolls the XML scan —
+// DataGrip's file shape is stable (top-level <data-source name=
+// uuid=>, child <driver>...</driver> + <jdbc-url>...</jdbc-url>)
+// and bringing in MSXML via COM for a few tag extractions would
+// be overkill.
+
+#include "DataGripImporter.h"
+
+#include <windows.h>
+#include <shlobj.h>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <filesystem>
+#include <algorithm>
+
+namespace fs = std::filesystem;
+
+namespace DBModels { namespace DataGripImporter {
+
+namespace {
+ std::wstring jetbrainsDir()
+ {
+ wchar_t* p = nullptr;
+ if (SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p) != S_OK)
+ return {};
+ std::wstring out(p);
+ CoTaskMemFree(p);
+ return out + L"\\JetBrains";
+ }
+
+ // Pick the newest DataGrip* subdir (lexicographic sort works
+ // because JetBrains name-versions monotonically: DataGrip2023.1,
+ // DataGrip2024.2, DataGrip2025.1, ...).
+ std::optional<fs::path> newestDataGripDir()
+ {
+ const auto jb = jetbrainsDir();
+ if (jb.empty()) return std::nullopt;
+ std::error_code ec;
+ if (!fs::exists(jb, ec)) return std::nullopt;
+
+ std::vector<fs::path> hits;
+ for (auto it = fs::directory_iterator(jb, ec);
+ !ec && it != fs::directory_iterator();
+ ++it)
+ {
+ if (!it->is_directory()) continue;
+ const auto name = it->path().filename().wstring();
+ if (name.rfind(L"DataGrip", 0) == 0) hits.push_back(it->path());
+ }
+ if (hits.empty()) return std::nullopt;
+ std::sort(hits.begin(), hits.end(),
+ [](const fs::path& a, const fs::path& b) {
+ return a.filename().wstring() > b.filename().wstring();
+ });
+ return hits.front();
+ }
+
+ std::wstring fromUtf8(const std::string& s)
+ {
+ if (s.empty()) return {};
+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);
+ std::wstring out(sz, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &out[0], sz);
+ return out;
+ }
+
+ std::string toLower(std::string s)
+ {
+ std::transform(s.begin(), s.end(), s.begin(),
+ [](unsigned char c) { return (char)std::tolower(c); });
+ return s;
+ }
+
+ DatabaseType mapDriverUrl(const std::string& driver, const std::string& url)
+ {
+ const std::string combined = toLower(driver + url);
+ if (combined.find("postgres") != std::string::npos) return DatabaseType::PostgreSQL;
+ if (combined.find("mysql") != std::string::npos || combined.find("maria") != std::string::npos)
+ return DatabaseType::MySQL;
+ if (combined.find("sqlite") != std::string::npos) return DatabaseType::SQLite;
+ if (combined.find("redis") != std::string::npos) return DatabaseType::Redis;
+ if (combined.find("mongo") != std::string::npos) return DatabaseType::MongoDB;
+ if (combined.find("sqlserver") != std::string::npos || combined.find("mssql") != std::string::npos)
+ return DatabaseType::MSSQLServer;
+ return DatabaseType::PostgreSQL;
+ }
+
+ // Return substring between tag open and close — cheap and
+ // good enough for the stable DataGrip schema. Returns "" if
+ // either anchor is missing.
+ std::string extractTag(const std::string& s, const std::string& open, const std::string& close,
+ size_t from = 0)
+ {
+ auto o = s.find(open, from);
+ if (o == std::string::npos) return {};
+ o += open.size();
+ auto c = s.find(close, o);
+ if (c == std::string::npos) return {};
+ return s.substr(o, c - o);
+ }
+
+ // Pull an XML attribute value from a single element open tag.
+ // Assumes double-quoted values (JetBrains always double-quotes).
+ std::string extractAttr(const std::string& tag, const std::string& attr)
+ {
+ const std::string needle = attr + "=\"";
+ auto p = tag.find(needle);
+ if (p == std::string::npos) return {};
+ p += needle.size();
+ auto e = tag.find('"', p);
+ if (e == std::string::npos) return {};
+ return tag.substr(p, e - p);
+ }
+
+ struct JdbcParts { std::string host; std::optional<int> port; std::string db; };
+ JdbcParts parseJdbcUrl(const std::string& url)
+ {
+ JdbcParts p;
+ auto colSlash = url.find("://");
+ if (colSlash == std::string::npos) return p;
+ size_t i = colSlash + 3;
+ size_t endHost = url.find_first_of(":/;?", i);
+ if (endHost == std::string::npos) endHost = url.size();
+ p.host = url.substr(i, endHost - i);
+
+ if (endHost < url.size() && url[endHost] == ':')
+ {
+ size_t j = endHost + 1;
+ std::string num;
+ while (j < url.size() && std::isdigit((unsigned char)url[j])) num += url[j++];
+ if (!num.empty()) { try { p.port = std::stoi(num); } catch (...) {} }
+ endHost = j;
+ }
+ if (endHost < url.size() && url[endHost] == '/')
+ {
+ size_t j = endHost + 1;
+ size_t endDb = url.find_first_of("?;", j);
+ if (endDb == std::string::npos) endDb = url.size();
+ p.db = url.substr(j, endDb - j);
+ }
+ return p;
+ }
+
+ // Walk every <data-source ...>...</data-source> block in the
+ // XML, pull name / uuid / driver / url, and emit one row each.
+ std::vector<ImportedConnection> parseXml(const std::string& xml)
+ {
+ std::vector<ImportedConnection> out;
+ size_t pos = 0;
+ while (true)
+ {
+ auto start = xml.find("<data-source", pos);
+ if (start == std::string::npos) break;
+ auto headerEnd = xml.find('>', start);
+ if (headerEnd == std::string::npos) break;
+ auto blockEnd = xml.find("</data-source>", headerEnd);
+ if (blockEnd == std::string::npos) break;
+
+ const std::string header = xml.substr(start, headerEnd - start + 1);
+ const std::string body = xml.substr(headerEnd + 1, blockEnd - (headerEnd + 1));
+
+ const std::string name = extractAttr(header, "name");
+ const std::string uuid = extractAttr(header, "uuid");
+ // driver may be an element (<driver-ref>pg</driver-ref>)
+ // or attribute. Accept either.
+ std::string driver = extractTag(body, "<driver-ref>", "</driver-ref>");
+ if (driver.empty()) driver = extractTag(body, "<jdbc-driver>", "</jdbc-driver>");
+ std::string url = extractTag(body, "<jdbc-url>", "</jdbc-url>");
+
+ if (!name.empty())
+ {
+ ImportedConnection c;
+ c.source = ImportSource::DataGrip;
+ c.id = uuid.empty() ? L"" : fromUtf8(uuid);
+ c.name = fromUtf8(name);
+ c.databaseType = mapDriverUrl(driver, url);
+ c.sslEnabled = url.find("ssl=true") != std::string::npos;
+
+ if (!url.empty())
+ {
+ auto jp = parseJdbcUrl(url);
+ if (!jp.host.empty()) c.host = fromUtf8(jp.host);
+ if (jp.port.has_value()) c.port = static_cast<uint16_t>(*jp.port);
+ if (!jp.db.empty()) c.database = fromUtf8(jp.db);
+ }
+
+ out.push_back(std::move(c));
+ }
+
+ pos = blockEnd + strlen("</data-source>");
+ }
+ return out;
+ }
+
+ std::vector<ImportedConnection> parseFile(const fs::path& path)
+ {
+ std::ifstream in(path, std::ios::binary);
+ if (!in.is_open()) return {};
+ std::stringstream ss; ss << in.rdbuf();
+ return parseXml(ss.str());
+ }
+}
+
+bool isInstalled() { return newestDataGripDir().has_value(); }
+
+std::vector<ImportedConnection> importConnections()
+{
+ std::vector<ImportedConnection> out;
+ auto base = newestDataGripDir();
+ if (!base) return out;
+
+ // Global options/dataSources.xml — shared across projects.
+ {
+ const auto p = *base / L"options" / L"dataSources.xml";
+ std::error_code ec;
+ if (fs::exists(p, ec))
+ {
+ auto rows = parseFile(p);
+ out.insert(out.end(), rows.begin(), rows.end());
+ }
+ }
+ // Per-project .idea/dataSources.xml (best effort; some users
+ // keep connections in project scope rather than IDE-global).
+ {
+ const auto projRoot = *base / L"projects";
+ std::error_code ec;
+ if (fs::exists(projRoot, ec))
+ {
+ for (auto it = fs::directory_iterator(projRoot, ec);
+ !ec && it != fs::directory_iterator(); ++it)
+ {
+ if (!it->is_directory()) continue;
+ const auto p = it->path() / L".idea" / L"dataSources.xml";
+ if (fs::exists(p, ec))
+ {
+ auto rows = parseFile(p);
+ out.insert(out.end(), rows.begin(), rows.end());
+ }
+ }
+ }
+ }
+ return out;
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/Import/DataGripImporter.h b/windows/Gridex/Services/Import/DataGripImporter.h
new file mode 100644
index 0000000..0fa5bc4
--- /dev/null
+++ b/windows/Gridex/Services/Import/DataGripImporter.h
@@ -0,0 +1,19 @@
+#pragma once
+//
+// DataGripImporter.h
+// Gridex
+//
+// Reads %APPDATA%\JetBrains\DataGrip<VERSION>\options\dataSources.xml
+// and project-level .idea/dataSources.xml files. Passwords are kept
+// by IntelliJ's encrypted credential store, not in the XML — we
+// skip them; user re-enters after import.
+
+#include <vector>
+#include "../../Models/Import/ImportedConnection.h"
+
+namespace DBModels { namespace DataGripImporter {
+
+bool isInstalled();
+std::vector<ImportedConnection> importConnections();
+
+}} // namespace
diff --git a/windows/Gridex/Services/Import/NavicatImporter.cpp b/windows/Gridex/Services/Import/NavicatImporter.cpp
new file mode 100644
index 0000000..edc897e
--- /dev/null
+++ b/windows/Gridex/Services/Import/NavicatImporter.cpp
@@ -0,0 +1,316 @@
+//
+// NavicatImporter.cpp
+//
+// Parses .ncx export files. Same XML shape as the mac importer —
+// <Connection ConnType="..."> blocks with <Host>, <Port>, <UserName>,
+// <Password>, <SSL>, SSH_Host/Port/User fields. Passwords are
+// Blowfish-encrypted (key "3DC5CA39"); on Windows we skip decryption
+// because Blowfish isn't in BCrypt and OpenSSL 3.0 keeps it behind
+// the legacy provider — user re-enters after import.
+
+#include "NavicatImporter.h"
+
+#include <windows.h>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <algorithm>
+#include <array>
+
+namespace DBModels { namespace NavicatImporter {
+
+namespace {
+ std::wstring fromUtf8(const std::string& s)
+ {
+ if (s.empty()) return {};
+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);
+ std::wstring out(sz, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &out[0], sz);
+ return out;
+ }
+
+ // Map Navicat's internal connType codes (seen in both older XML
+ // string form and the newer integer form).
+ DatabaseType mapConnType(const std::string& connType)
+ {
+ std::string lower; lower.reserve(connType.size());
+ for (char c : connType) lower.push_back((char)std::tolower((unsigned char)c));
+
+ if (lower.find("postgres") != std::string::npos) return DatabaseType::PostgreSQL;
+ if (lower.find("mysql") != std::string::npos || lower.find("maria") != std::string::npos)
+ return DatabaseType::MySQL;
+ if (lower.find("sqlite") != std::string::npos) return DatabaseType::SQLite;
+ if (lower.find("redis") != std::string::npos) return DatabaseType::Redis;
+ if (lower.find("mongo") != std::string::npos) return DatabaseType::MongoDB;
+ if (lower.find("sqlserver") != std::string::npos || lower.find("mssql") != std::string::npos)
+ return DatabaseType::MSSQLServer;
+ // Legacy numeric codes.
+ if (lower == "1") return DatabaseType::MySQL;
+ if (lower == "2") return DatabaseType::PostgreSQL;
+ if (lower == "3") return DatabaseType::SQLite;
+ if (lower == "7") return DatabaseType::MSSQLServer;
+ if (lower == "8") return DatabaseType::MongoDB;
+ return DatabaseType::PostgreSQL;
+ }
+
+ std::string extractAttr(const std::string& tag, const std::string& attr)
+ {
+ const std::string needle = attr + "=\"";
+ auto p = tag.find(needle);
+ if (p == std::string::npos) return {};
+ p += needle.size();
+ auto e = tag.find('"', p);
+ if (e == std::string::npos) return {};
+ return tag.substr(p, e - p);
+ }
+
+ // Inside a single <Connection>...</Connection> body, read the
+ // text content of a child element by name. Returns empty when
+ // the tag is absent. Handles both open/close (<Foo>bar</Foo>)
+ // and self-closing empty tags (<Foo/>).
+ std::string readChild(const std::string& body, const std::string& tag)
+ {
+ const std::string open = "<" + tag + ">";
+ const std::string close = "</" + tag + ">";
+ auto o = body.find(open);
+ if (o == std::string::npos) return {};
+ o += open.size();
+ auto c = body.find(close, o);
+ if (c == std::string::npos) return {};
+ std::string v = body.substr(o, c - o);
+ // Trim whitespace.
+ while (!v.empty() && std::isspace((unsigned char)v.front())) v.erase(v.begin());
+ while (!v.empty() && std::isspace((unsigned char)v.back())) v.pop_back();
+ return v;
+ }
+
+ std::vector<ImportedConnection> parseXml(const std::string& xml)
+ {
+ std::vector<ImportedConnection> out;
+ size_t pos = 0;
+ while (true)
+ {
+ auto start = xml.find("<Connection", pos);
+ if (start == std::string::npos) break;
+ auto headerEnd = xml.find('>', start);
+ if (headerEnd == std::string::npos) break;
+ auto blockEnd = xml.find("</Connection>", headerEnd);
+ if (blockEnd == std::string::npos) break;
+
+ const std::string header = xml.substr(start, headerEnd - start + 1);
+ const std::string body = xml.substr(headerEnd + 1, blockEnd - (headerEnd + 1));
+
+ std::string name = readChild(body, "ConnectionName");
+ if (name.empty()) name = readChild(body, "Name");
+ if (name.empty()) { pos = blockEnd + 13; continue; }
+
+ std::string connType = extractAttr(header, "ConnType");
+ if (connType.empty()) connType = readChild(body, "ConnType");
+
+ ImportedConnection c;
+ c.source = ImportSource::Navicat;
+ c.name = fromUtf8(name);
+ c.databaseType = mapConnType(connType);
+ c.host = fromUtf8(readChild(body, "Host"));
+ const auto portStr = readChild(body, "Port");
+ if (!portStr.empty())
+ { try { c.port = (uint16_t)std::stoi(portStr); } catch (...) {} }
+ auto db = readChild(body, "DatabaseName");
+ if (db.empty()) db = readChild(body, "InitialDatabase");
+ c.database = fromUtf8(db);
+ c.username = fromUtf8(readChild(body, "UserName"));
+ c.filePath = fromUtf8(readChild(body, "DatabaseFile"));
+
+ const auto sslStr = readChild(body, "SSL");
+ const auto useSslStr = readChild(body, "UseSSL");
+ c.sslEnabled = (sslStr == "true") || (useSslStr == "1");
+
+ c.sshHost = fromUtf8(readChild(body, "SSH_Host"));
+ const auto sshPortStr = readChild(body, "SSH_Port");
+ if (!sshPortStr.empty())
+ { try { c.sshPort = (uint16_t)std::stoi(sshPortStr); } catch (...) {} }
+ c.sshUser = fromUtf8(readChild(body, "SSH_UserName"));
+
+ // Password field is Blowfish-encrypted; skipped on Windows
+ // (see header). Leave c.password empty.
+
+ out.push_back(std::move(c));
+ pos = blockEnd + std::string("</Connection>").size();
+ }
+ return out;
+ }
+}
+
+// ── Registry scan (Windows Navicat) ────────────────────────
+// Navicat Windows persists each connection as a registry subkey
+// under HKCU\Software\PremiumSoft\Navicat<PRODUCT>\Servers\<name>.
+// We walk the known product hives and emit one ImportedConnection
+// per subkey. String values use the `W` / wide variant because
+// Navicat stores non-ASCII names (e.g. host labels in Chinese)
+// verbatim.
+
+namespace {
+ struct NavicatHive {
+ const wchar_t* subKey; // under HKCU
+ DatabaseType dbType;
+ };
+
+ const std::array<NavicatHive, 8>& hives()
+ {
+ // Plain `Navicat\Servers` is the legacy "Navicat for MySQL"
+ // standalone hive — still used on machines that started on
+ // that product before upgrading to Premium. Missing this
+ // cost a user their second MySQL connection during import.
+ static const std::array<NavicatHive, 8> v{{
+ { L"Software\\PremiumSoft\\Navicat\\Servers", DatabaseType::MySQL },
+ { L"Software\\PremiumSoft\\NavicatPG\\Servers", DatabaseType::PostgreSQL },
+ { L"Software\\PremiumSoft\\NavicatMARIADB\\Servers", DatabaseType::MySQL },
+ { L"Software\\PremiumSoft\\NavicatMSSQL\\Servers", DatabaseType::MSSQLServer },
+ { L"Software\\PremiumSoft\\NavicatMONGODB\\Servers", DatabaseType::MongoDB },
+ { L"Software\\PremiumSoft\\NavicatREDIS\\Servers", DatabaseType::Redis },
+ { L"Software\\PremiumSoft\\NavicatSQLite\\Servers", DatabaseType::SQLite },
+ { L"Software\\PremiumSoft\\NavicatPremium\\Servers", DatabaseType::PostgreSQL }
+ }};
+ return v;
+ }
+
+ // Helpers around RegQueryValueExW to unwrap REG_SZ / REG_DWORD.
+ std::wstring regReadString(HKEY h, const wchar_t* name)
+ {
+ DWORD type = 0, cb = 0;
+ if (RegQueryValueExW(h, name, nullptr, &type, nullptr, &cb) != ERROR_SUCCESS
+ || type != REG_SZ || cb == 0) return {};
+ std::wstring out(cb / sizeof(wchar_t), L'\0');
+ if (RegQueryValueExW(h, name, nullptr, nullptr,
+ reinterpret_cast<LPBYTE>(&out[0]), &cb) != ERROR_SUCCESS) return {};
+ while (!out.empty() && out.back() == L'\0') out.pop_back();
+ return out;
+ }
+
+ bool regReadDword(HKEY h, const wchar_t* name, DWORD& out)
+ {
+ DWORD type = 0, cb = sizeof(DWORD);
+ return RegQueryValueExW(h, name, nullptr, &type,
+ reinterpret_cast<LPBYTE>(&out), &cb) == ERROR_SUCCESS
+ && type == REG_DWORD;
+ }
+
+ ImportedConnection readServer(HKEY parent, const std::wstring& name, DatabaseType fallbackType)
+ {
+ ImportedConnection c;
+ c.source = ImportSource::Navicat;
+ c.name = name;
+ c.databaseType = fallbackType;
+
+ HKEY sub = nullptr;
+ if (RegOpenKeyExW(parent, name.c_str(), 0, KEY_READ, &sub) != ERROR_SUCCESS)
+ return c;
+
+ // NavicatPremium\Servers mixes products — prefer the
+ // connection's self-reported type when present.
+ const auto conn = regReadString(sub, L"ConnectionType");
+ if (!conn.empty())
+ {
+ std::wstring lower; lower.reserve(conn.size());
+ for (wchar_t ch : conn) lower.push_back((wchar_t)towlower(ch));
+ if (lower.find(L"postgres") != std::wstring::npos) c.databaseType = DatabaseType::PostgreSQL;
+ else if (lower.find(L"mysql") != std::wstring::npos) c.databaseType = DatabaseType::MySQL;
+ else if (lower.find(L"maria") != std::wstring::npos) c.databaseType = DatabaseType::MySQL;
+ else if (lower.find(L"mssql") != std::wstring::npos) c.databaseType = DatabaseType::MSSQLServer;
+ else if (lower.find(L"mongo") != std::wstring::npos) c.databaseType = DatabaseType::MongoDB;
+ else if (lower.find(L"redis") != std::wstring::npos) c.databaseType = DatabaseType::Redis;
+ else if (lower.find(L"sqlite") != std::wstring::npos) c.databaseType = DatabaseType::SQLite;
+ }
+
+ c.host = regReadString(sub, L"Host");
+ DWORD port = 0;
+ if (regReadDword(sub, L"Port", port) && port != 0)
+ c.port = static_cast<uint16_t>(port);
+
+ c.username = regReadString(sub, L"UserName");
+ c.database = regReadString(sub, L"InitialDatabase");
+ c.filePath = regReadString(sub, L"DatabaseFile");
+
+ DWORD ssl = 0;
+ if (regReadDword(sub, L"UseSSL", ssl) && ssl != 0) c.sslEnabled = true;
+
+ // SSH tunnel — same keys as the .ncx schema.
+ c.sshHost = regReadString(sub, L"SSH_Host");
+ if (c.sshHost.empty()) c.sshHost = regReadString(sub, L"SSH_Server");
+ c.sshUser = regReadString(sub, L"SSH_UserName");
+ DWORD sshPort = 0;
+ if (regReadDword(sub, L"SSH_Port", sshPort) && sshPort != 0)
+ c.sshPort = static_cast<uint16_t>(sshPort);
+
+ // Password is Blowfish-encrypted in Pwd_2 — skipped on
+ // Windows (see header).
+ RegCloseKey(sub);
+ return c;
+ }
+
+ std::vector<ImportedConnection> scanHive(const NavicatHive& h)
+ {
+ std::vector<ImportedConnection> out;
+ HKEY root = nullptr;
+ if (RegOpenKeyExW(HKEY_CURRENT_USER, h.subKey, 0, KEY_READ, &root) != ERROR_SUCCESS)
+ return out;
+
+ wchar_t name[512];
+ DWORD nameLen = 0;
+ DWORD idx = 0;
+ while (true)
+ {
+ nameLen = 512;
+ const LONG rc = RegEnumKeyExW(root, idx, name, &nameLen,
+ nullptr, nullptr, nullptr, nullptr);
+ if (rc == ERROR_NO_MORE_ITEMS) break;
+ if (rc != ERROR_SUCCESS) break;
+ out.push_back(readServer(root, std::wstring(name, nameLen), h.dbType));
+ ++idx;
+ }
+ RegCloseKey(root);
+ return out;
+ }
+}
+
+bool isInstalled()
+{
+ HKEY h = nullptr;
+ if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\PremiumSoft",
+ 0, KEY_READ, &h) == ERROR_SUCCESS)
+ {
+ RegCloseKey(h);
+ return true;
+ }
+ return false;
+}
+
+std::vector<ImportedConnection> importConnections()
+{
+ // Dedupe NavicatPremium overlap — if a server name already
+ // shown from a specialized hive, skip the duplicate we'd pull
+ // from Premium's mixed hive.
+ std::vector<ImportedConnection> out;
+ for (const auto& h : hives())
+ {
+ auto rows = scanHive(h);
+ for (auto& r : rows)
+ {
+ bool dup = false;
+ for (const auto& existing : out)
+ if (existing.name == r.name && existing.host == r.host) { dup = true; break; }
+ if (!dup) out.push_back(std::move(r));
+ }
+ }
+ return out;
+}
+
+std::vector<ImportedConnection> importFromNCX(const std::wstring& ncxPath)
+{
+ std::ifstream in(ncxPath, std::ios::binary);
+ if (!in.is_open()) return {};
+ std::stringstream ss; ss << in.rdbuf();
+ return parseXml(ss.str());
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/Import/NavicatImporter.h b/windows/Gridex/Services/Import/NavicatImporter.h
new file mode 100644
index 0000000..b80057b
--- /dev/null
+++ b/windows/Gridex/Services/Import/NavicatImporter.h
@@ -0,0 +1,37 @@
+#pragma once
+//
+// NavicatImporter.h
+// Gridex
+//
+// Windows Navicat stores every connection in the registry as
+// HKCU\Software\PremiumSoft\Navicat<PRODUCT>\Servers\<name>, one
+// subkey per connection. We scan the documented product hives
+// (Premium / PG / MARIADB / MSSQL / MONGODB / REDIS / SQLite /
+// Oracle / Snowflake / DAMENG) and return every detected entry.
+//
+// importFromNCX() stays as a fallback for users who keep their
+// connections in a .ncx export file instead of letting Navicat
+// persist to registry (some team / enterprise setups do this).
+//
+// Passwords use Blowfish (key "3DC5CA39") which isn't exposed by
+// Windows BCrypt and sits behind OpenSSL 3's legacy provider; we
+// skip decryption — user re-enters after import.
+
+#include <vector>
+#include <string>
+#include "../../Models/Import/ImportedConnection.h"
+
+namespace DBModels { namespace NavicatImporter {
+
+// True when any Navicat registry hive is present.
+bool isInstalled();
+
+// Walk the known Navicat\*\Servers hives and return one row per
+// connection subkey. Passwords stay empty — see header.
+std::vector<ImportedConnection> importConnections();
+
+// Parse a user-picked .ncx export and return its <Connection>
+// entries. Useful when the user's Navicat isn't on this machine.
+std::vector<ImportedConnection> importFromNCX(const std::wstring& ncxPath);
+
+}} // namespace
diff --git a/windows/Gridex/Services/Import/TablePlusImporter.cpp b/windows/Gridex/Services/Import/TablePlusImporter.cpp
new file mode 100644
index 0000000..f3e0bef
--- /dev/null
+++ b/windows/Gridex/Services/Import/TablePlusImporter.cpp
@@ -0,0 +1,180 @@
+//
+// TablePlusImporter.cpp
+//
+// Parses the TablePlus for Windows connections plist.
+// Location: %LOCALAPPDATA%\com.tinyapp.TablePlus\Data\Connections.plist
+// Format: standard Apple XML plist — <dict> blocks with <key> +
+// typed value pairs (<string>, <integer>). We scan linearly rather
+// than using MSXML — schema is stable and the file is small.
+//
+// Passwords are encrypted via TablePlus's .tpmaster key file; not
+// attempted on Windows — user re-enters after import.
+
+#include "TablePlusImporter.h"
+
+#include <windows.h>
+#include <shlobj.h>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <algorithm>
+
+namespace DBModels { namespace TablePlusImporter {
+
+namespace {
+ std::wstring plistPath()
+ {
+ wchar_t* p = nullptr;
+ if (SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &p) != S_OK)
+ return {};
+ std::wstring out(p);
+ CoTaskMemFree(p);
+ return out + L"\\com.tinyapp.TablePlus\\Data\\Connections.plist";
+ }
+
+ std::wstring fromUtf8(const std::string& s)
+ {
+ if (s.empty()) return {};
+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);
+ std::wstring out(sz, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &out[0], sz);
+ return out;
+ }
+
+ DatabaseType mapDriver(const std::string& driver)
+ {
+ std::string lower; lower.reserve(driver.size());
+ for (char c : driver) lower.push_back((char)std::tolower((unsigned char)c));
+ if (lower.find("postgres") != std::string::npos) return DatabaseType::PostgreSQL;
+ if (lower.find("mysql") != std::string::npos || lower.find("maria") != std::string::npos)
+ return DatabaseType::MySQL;
+ if (lower.find("sqlite") != std::string::npos) return DatabaseType::SQLite;
+ if (lower.find("redis") != std::string::npos) return DatabaseType::Redis;
+ if (lower.find("mongo") != std::string::npos) return DatabaseType::MongoDB;
+ if (lower.find("mssql") != std::string::npos || lower.find("sqlserver") != std::string::npos)
+ return DatabaseType::MSSQLServer;
+ return DatabaseType::PostgreSQL;
+ }
+
+ // XML plist scanner: within a `<dict>...</dict>` body, pull
+ // every <key>Name</key> followed by its typed value. We only
+ // need <string> and <integer>; <array>/<data>/<date> are
+ // skipped (TablePlus doesn't store connection fields in them).
+ std::string readStringFor(const std::string& body, const std::string& keyName,
+ size_t bodyStart = 0)
+ {
+ const std::string needle = "<key>" + keyName + "</key>";
+ auto k = body.find(needle, bodyStart);
+ if (k == std::string::npos) return {};
+ auto after = k + needle.size();
+
+ // Look for the next <string>...</string>, or self-closing
+ // <string /> (meaning empty). Skip over any whitespace.
+ auto openStr = body.find("<string", after);
+ if (openStr == std::string::npos) return {};
+ // Self-closing empty tag.
+ if (body.compare(openStr, 9, "<string/>") == 0 ||
+ body.compare(openStr, 10, "<string />") == 0) return {};
+ auto openEnd = body.find('>', openStr);
+ if (openEnd == std::string::npos) return {};
+ auto close = body.find("</string>", openEnd);
+ if (close == std::string::npos) return {};
+ return body.substr(openEnd + 1, close - (openEnd + 1));
+ }
+
+ int readIntFor(const std::string& body, const std::string& keyName)
+ {
+ const std::string needle = "<key>" + keyName + "</key>";
+ auto k = body.find(needle);
+ if (k == std::string::npos) return 0;
+ auto after = k + needle.size();
+ auto openInt = body.find("<integer>", after);
+ if (openInt == std::string::npos) return 0;
+ auto close = body.find("</integer>", openInt);
+ if (close == std::string::npos) return 0;
+ const auto val = body.substr(openInt + 9, close - (openInt + 9));
+ try { return std::stoi(val); } catch (...) { return 0; }
+ }
+
+ std::vector<ImportedConnection> parsePlist(const std::string& xml)
+ {
+ std::vector<ImportedConnection> out;
+ // Each connection lives in a top-level <dict>. Walk them.
+ size_t pos = 0;
+ while (true)
+ {
+ auto start = xml.find("<dict>", pos);
+ if (start == std::string::npos) break;
+ // Find matching </dict> — assume TablePlus doesn't nest
+ // <dict> inside a connection body (confirmed against
+ // the real file; nested structures use <array>).
+ auto end = xml.find("</dict>", start);
+ if (end == std::string::npos) break;
+
+ const std::string body = xml.substr(start, end + 7 - start);
+
+ std::string name = readStringFor(body, "ConnectionName");
+ std::string driver = readStringFor(body, "Driver");
+ if (name.empty() || driver.empty()) { pos = end + 7; continue; }
+
+ ImportedConnection c;
+ c.id = fromUtf8(readStringFor(body, "ID"));
+ c.source = ImportSource::TablePlus;
+ c.name = fromUtf8(name);
+ c.databaseType = mapDriver(driver);
+
+ const auto host = readStringFor(body, "DatabaseHost");
+ if (!host.empty()) c.host = fromUtf8(host);
+
+ const auto portStr = readStringFor(body, "DatabasePort");
+ if (!portStr.empty())
+ { try { c.port = (uint16_t)std::stoi(portStr); } catch (...) {} }
+
+ c.username = fromUtf8(readStringFor(body, "DatabaseUser"));
+ c.database = fromUtf8(readStringFor(body, "DatabaseName"));
+ c.filePath = fromUtf8(readStringFor(body, "DatabasePath"));
+
+ c.sslEnabled = readIntFor(body, "tLSMode") > 0;
+
+ const bool overSSH = readIntFor(body, "isOverSSH") != 0;
+ if (overSSH)
+ {
+ c.sshHost = fromUtf8(readStringFor(body, "ServerAddress"));
+ const auto sp = readStringFor(body, "ServerPort");
+ if (!sp.empty())
+ { try { c.sshPort = (uint16_t)std::stoi(sp); } catch (...) {} }
+ c.sshUser = fromUtf8(readStringFor(body, "ServerUser"));
+ }
+
+ out.push_back(std::move(c));
+ pos = end + 7;
+ }
+ return out;
+ }
+}
+
+bool isInstalled()
+{
+ const auto p = plistPath();
+ return !p.empty() && GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES;
+}
+
+std::vector<ImportedConnection> importConnections()
+{
+ const auto path = plistPath();
+ if (path.empty()) return {};
+ std::ifstream in(path, std::ios::binary);
+ if (!in.is_open()) return {};
+ std::stringstream ss; ss << in.rdbuf();
+ return parsePlist(ss.str());
+}
+
+std::wstring windowsSupportNote()
+{
+ // Parsing works; passwords stay encrypted by TablePlus's
+ // .tpmaster — user re-enters after import.
+ return L"TablePlus import works on Windows. Passwords are encrypted by "
+ L"TablePlus and will need to be re-entered after import.";
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/Import/TablePlusImporter.h b/windows/Gridex/Services/Import/TablePlusImporter.h
new file mode 100644
index 0000000..2e872a1
--- /dev/null
+++ b/windows/Gridex/Services/Import/TablePlusImporter.h
@@ -0,0 +1,27 @@
+#pragma once
+//
+// TablePlusImporter.h
+// Gridex
+//
+// Windows v1 stub. TablePlus on macOS stores connections in a
+// plist under com.tinyapp.TablePlus; the Windows build uses a
+// different encrypted store (SQLite + DPAPI-wrapped passwords)
+// that we haven't reverse-engineered yet. For now we detect
+// installation but return an empty list + surface an "UI note"
+// string so the dialog can explain why.
+
+#include <vector>
+#include <string>
+#include "../../Models/Import/ImportedConnection.h"
+
+namespace DBModels { namespace TablePlusImporter {
+
+bool isInstalled();
+std::vector<ImportedConnection> importConnections();
+
+// Message for the import dialog when the user clicks TablePlus
+// but nothing can be parsed yet. Non-fatal — kept separate from
+// the generic ImportError path so the UI can show a friendly hint.
+std::wstring windowsSupportNote();
+
+}} // namespace
diff --git a/windows/Gridex/Services/MCP/Audit/MCPAuditLogger.cpp b/windows/Gridex/Services/MCP/Audit/MCPAuditLogger.cpp
new file mode 100644
index 0000000..c7bb79a
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Audit/MCPAuditLogger.cpp
@@ -0,0 +1,203 @@
+//
+// MCPAuditLogger.cpp
+//
+// File I/O uses plain std::ofstream/ifstream. Path is under
+// %APPDATA%\Gridex\ — the same folder ConnectionStore uses — so
+// backups sit next to the connections DB.
+
+#include "MCPAuditLogger.h"
+
+#include <windows.h>
+#include <shlobj.h>
+#include <fstream>
+#include <sstream>
+#include <filesystem>
+#include <chrono>
+#include <ctime>
+
+namespace fs = std::filesystem;
+
+namespace DBModels
+{
+ MCPAuditLogger::MCPAuditLogger(int maxSizeMB, int retentionDays)
+ : maxSizeBytes_(maxSizeMB > 0 ? maxSizeMB * 1024 * 1024 : 100 * 1024 * 1024),
+ retentionDays_(retentionDays)
+ {
+ const std::wstring dir = resolveAppDataPath();
+ CreateDirectoryW(dir.c_str(), nullptr);
+ path_ = dir + L"\\mcp-audit.jsonl";
+ purgeOldBackups();
+ }
+
+ std::wstring MCPAuditLogger::resolveAppDataPath()
+ {
+ wchar_t* appData = nullptr;
+ if (SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &appData) != S_OK)
+ return L".";
+ std::wstring p = std::wstring(appData) + L"\\Gridex";
+ CoTaskMemFree(appData);
+ return p;
+ }
+
+ std::wstring MCPAuditLogger::logFilePath() const
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ return path_;
+ }
+
+ std::string MCPAuditLogger::isoTimestampForFilename()
+ {
+ const std::time_t t = std::chrono::system_clock::to_time_t(
+ std::chrono::system_clock::now());
+ std::tm tm{};
+ gmtime_s(&tm, &t);
+ char buf[32];
+ // Colons are invalid in Win32 filenames — use dashes instead.
+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H-%M-%SZ", &tm);
+ return std::string(buf);
+ }
+
+ void MCPAuditLogger::log(const MCPAuditEntry& entry)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ try
+ {
+ rotateIfNeeded();
+
+ nlohmann::json j;
+ to_json(j, entry);
+ std::string line = j.dump() + "\n";
+
+ std::ofstream out(path_, std::ios::app | std::ios::binary);
+ if (!out.is_open()) return;
+ out.write(line.data(), static_cast<std::streamsize>(line.size()));
+ }
+ catch (...) { /* never crash on audit */ }
+ }
+
+ void MCPAuditLogger::rotateIfNeeded()
+ {
+ std::error_code ec;
+ if (!fs::exists(path_, ec)) return;
+ const auto size = fs::file_size(path_, ec);
+ if (ec || static_cast<int64_t>(size) < static_cast<int64_t>(maxSizeBytes_)) return;
+
+ const std::string ts = isoTimestampForFilename();
+ fs::path backup = fs::path(path_).parent_path() /
+ (std::string("mcp-audit-") + ts + ".jsonl");
+ fs::rename(path_, backup, ec);
+ }
+
+ void MCPAuditLogger::purgeOldBackups()
+ {
+ if (retentionDays_ <= 0) return;
+ std::error_code ec;
+ const fs::path dir = fs::path(path_).parent_path();
+ if (!fs::exists(dir, ec)) return;
+
+ const auto cutoff = std::chrono::system_clock::now()
+ - std::chrono::hours(24 * retentionDays_);
+
+ for (auto it = fs::directory_iterator(dir, ec);
+ !ec && it != fs::directory_iterator();
+ ++it)
+ {
+ const auto& p = it->path();
+ const auto name = p.filename().string();
+ // Only touch our own rotated backups.
+ if (name.rfind("mcp-audit-", 0) != 0) continue;
+ if (p.extension() != ".jsonl") continue;
+
+ const auto ft = fs::last_write_time(p, ec);
+ if (ec) continue;
+ // Convert file_time_type → system_clock::time_point
+ // (portable approximation — good enough for day-level retention).
+ const auto sys = std::chrono::system_clock::now()
+ - (fs::file_time_type::clock::now() - ft);
+ if (sys < cutoff) fs::remove(p, ec);
+ }
+ }
+
+ void MCPAuditLogger::close()
+ {
+ // std::ofstream is opened per-log() call, nothing persistent.
+ }
+
+ void MCPAuditLogger::clearAll()
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ std::error_code ec;
+ fs::remove(path_, ec);
+ }
+
+ std::vector<MCPAuditEntry> MCPAuditLogger::recentEntries(int limit)
+ {
+ std::vector<MCPAuditEntry> out;
+ std::lock_guard<std::mutex> lk(mtx_);
+ std::ifstream in(path_, std::ios::binary);
+ if (!in.is_open()) return out;
+
+ // Read all lines (for human-scale logs this is fine — a full
+ // 100MB log would still fit in RAM, and the UI caps at 500).
+ std::vector<std::string> lines;
+ std::string line;
+ while (std::getline(in, line))
+ {
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ if (!line.empty()) lines.push_back(std::move(line));
+ }
+
+ const size_t start = lines.size() > static_cast<size_t>(limit)
+ ? lines.size() - static_cast<size_t>(limit) : 0;
+ for (size_t i = lines.size(); i > start; --i)
+ {
+ try
+ {
+ auto j = nlohmann::json::parse(lines[i - 1]);
+ MCPAuditEntry e;
+ e.tool = j.value("tool", std::string{});
+ e.tier = j.value("tier", 1);
+ e.eventId = j.value("eventId", std::string{});
+ if (j.contains("connectionId") && j["connectionId"].is_string())
+ e.connectionId = j["connectionId"].get<std::string>();
+ if (j.contains("connectionType") && j["connectionType"].is_string())
+ e.connectionType = j["connectionType"].get<std::string>();
+ if (j.contains("error") && j["error"].is_string())
+ e.error = j["error"].get<std::string>();
+
+ if (j.contains("client"))
+ {
+ const auto& c = j["client"];
+ e.client.name = c.value("name", std::string{"unknown"});
+ e.client.version = c.value("version", std::string{"0.0.0"});
+ e.client.transport = c.value("transport", std::string{"stdio"});
+ }
+ if (j.contains("result"))
+ {
+ const auto& r = j["result"];
+ e.result.status = mcpAuditStatusFromRaw(r.value("status", std::string{"success"}));
+ e.result.durationMs = r.value("durationMs", 0);
+ if (r.contains("rowsAffected")) e.result.rowsAffected = r["rowsAffected"].get<int>();
+ if (r.contains("rowsReturned")) e.result.rowsReturned = r["rowsReturned"].get<int>();
+ }
+ if (j.contains("security"))
+ {
+ const auto& s = j["security"];
+ e.security.permissionMode = mcpModeFromRawString(
+ s.value("permissionMode", std::string{"locked"}));
+ if (s.contains("userApproved")) e.security.userApproved = s["userApproved"].get<bool>();
+ }
+ if (j.contains("input"))
+ {
+ const auto& in_ = j["input"];
+ if (in_.contains("sqlPreview")) e.input.sqlPreview = in_["sqlPreview"].get<std::string>();
+ if (in_.contains("paramsCount")) e.input.paramsCount = in_["paramsCount"].get<int>();
+ if (in_.contains("inputHash")) e.input.inputHash = in_["inputHash"].get<std::string>();
+ }
+ out.push_back(std::move(e));
+ }
+ catch (...) { /* skip malformed line */ }
+ }
+ return out;
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Audit/MCPAuditLogger.h b/windows/Gridex/Services/MCP/Audit/MCPAuditLogger.h
new file mode 100644
index 0000000..ae86e5b
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Audit/MCPAuditLogger.h
@@ -0,0 +1,56 @@
+#pragma once
+//
+// MCPAuditLogger.h
+// Gridex
+//
+// Append-only JSONL audit log at %APPDATA%\Gridex\mcp-audit.jsonl.
+// Mirrors macos/Services/MCP/Audit/MCPAuditLogger.swift format 1:1
+// so `jq` over the file works cross-platform.
+//
+// Rotation: when the file reaches `maxSizeMB` the current file is
+// renamed to `mcp-audit-<ISO-timestamp>.jsonl` and a fresh file
+// is started. Retention is enforced at startup (deleting backups
+// older than `retentionDays`; 0 means forever).
+
+#include <string>
+#include <vector>
+#include <mutex>
+#include "../../../Models/MCP/MCPAuditEntry.h"
+
+namespace DBModels
+{
+ class MCPAuditLogger
+ {
+ public:
+ // Sizes in MB, retention in days. 0 retention = keep forever.
+ MCPAuditLogger(int maxSizeMB = 100, int retentionDays = 90);
+
+ // Thread-safe append. Swallows exceptions — audit must
+ // never crash the app.
+ void log(const MCPAuditEntry& entry);
+
+ // Close the underlying handle (called on server shutdown).
+ void close();
+
+ // Tail the last `limit` entries (most recent first). Returns
+ // empty vector on error.
+ std::vector<MCPAuditEntry> recentEntries(int limit = 100);
+
+ // Delete the current log (testing / UI "Clear Log" button).
+ void clearAll();
+
+ // Absolute path of the current log file.
+ std::wstring logFilePath() const;
+
+ private:
+ mutable std::mutex mtx_;
+ std::wstring path_;
+ int maxSizeBytes_;
+ int retentionDays_;
+
+ void rotateIfNeeded();
+ void purgeOldBackups();
+ static std::wstring resolveAppDataPath();
+ static std::string isoTimestampForFilename();
+ };
+}
diff --git a/windows/Gridex/Services/MCP/MCPConnectionPool.cpp b/windows/Gridex/Services/MCP/MCPConnectionPool.cpp
new file mode 100644
index 0000000..28679f4
--- /dev/null
+++ b/windows/Gridex/Services/MCP/MCPConnectionPool.cpp
@@ -0,0 +1,78 @@
+//
+// MCPConnectionPool.cpp
+//
+// This duplicates ConnectionManager::createAdapter intentionally —
+// keeping the pool decoupled avoids a circular include (Services →
+// ConnectionManager → Services again once MCP hooks are added).
+
+#include "MCPConnectionPool.h"
+#include "../../Models/PostgreSQLAdapter.h"
+#include "../../Models/MySQLAdapter.h"
+#include "../../Models/SQLiteAdapter.h"
+#include "../../Models/RedisAdapter.h"
+#include "../../Models/MongoDBAdapter.h"
+#include "../../Models/MSSQLAdapter.h"
+
+namespace DBModels
+{
+ std::shared_ptr<DatabaseAdapter> MCPConnectionPool::createAdapter(DatabaseType t)
+ {
+ switch (t)
+ {
+ case DatabaseType::PostgreSQL: return std::make_shared<PostgreSQLAdapter>();
+ case DatabaseType::MySQL: return std::make_shared<MySQLAdapter>();
+ case DatabaseType::SQLite: return std::make_shared<SQLiteAdapter>();
+ case DatabaseType::Redis: return std::make_shared<RedisAdapter>();
+ case DatabaseType::MongoDB: return std::make_shared<MongoDBAdapter>();
+ case DatabaseType::MSSQLServer:return std::make_shared<MSSQLAdapter>();
+ }
+ throw DatabaseError(DatabaseError::Code::ConnectionFailed,
+ "Unsupported database type");
+ }
+
+ std::shared_ptr<DatabaseAdapter> MCPConnectionPool::acquire(
+ const ConnectionConfig& config, const std::wstring& password)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ auto it = adapters_.find(config.id);
+ if (it != adapters_.end() && it->second && it->second->isConnected())
+ return it->second;
+
+ // Either missing or stale — create fresh and connect.
+ auto adapter = createAdapter(config.databaseType);
+ adapter->connect(config, password);
+ adapters_[config.id] = adapter;
+ return adapter;
+ }
+
+ void MCPConnectionPool::release(const std::wstring& id)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ auto it = adapters_.find(id);
+ if (it != adapters_.end())
+ {
+ try { if (it->second) it->second->disconnect(); } catch (...) {}
+ adapters_.erase(it);
+ }
+ }
+
+ void MCPConnectionPool::releaseAll()
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ for (auto& [_, a] : adapters_)
+ try { if (a) a->disconnect(); } catch (...) {}
+ adapters_.clear();
+ }
+
+ bool MCPConnectionPool::isCached(const std::wstring& id) const
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ return adapters_.count(id) != 0;
+ }
+
+ size_t MCPConnectionPool::cachedCount() const
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ return adapters_.size();
+ }
+}
diff --git a/windows/Gridex/Services/MCP/MCPConnectionPool.h b/windows/Gridex/Services/MCP/MCPConnectionPool.h
new file mode 100644
index 0000000..2c6cbaf
--- /dev/null
+++ b/windows/Gridex/Services/MCP/MCPConnectionPool.h
@@ -0,0 +1,54 @@
+#pragma once
+//
+// MCPConnectionPool.h
+// Gridex
+//
+// Per-MCP adapter cache, separate from ConnectionManager (which
+// only holds the GUI's single active connection). Tools borrow
+// warm adapters from this pool keyed by connectionId — avoids
+// 200-800ms reconnect latency per invocation and preserves
+// Redis/Mongo session state.
+//
+// Thread-safe: invoked from stdio reader thread + HTTP worker
+// threads concurrently.
+
+#include <string>
+#include <memory>
+#include <unordered_map>
+#include <mutex>
+#include "../../Models/DatabaseAdapter.h"
+#include "../../Models/ConnectionConfig.h"
+
+namespace DBModels
+{
+ class MCPConnectionPool
+ {
+ public:
+ // Returns an adapter for `config`, opening a new connection
+ // if one isn't cached. Throws DatabaseError on connect failure.
+ // `password` is already resolved by the caller via CredentialManager.
+ std::shared_ptr<DatabaseAdapter> acquire(
+ const ConnectionConfig& config,
+ const std::wstring& password);
+
+ // Close + drop one cached adapter (e.g. when connection is
+ // deleted from ConnectionStore).
+ void release(const std::wstring& connectionId);
+
+ // Close + drop everything (server shutdown).
+ void releaseAll();
+
+ // Introspection for status UI.
+ bool isCached(const std::wstring& connectionId) const;
+ size_t cachedCount() const;
+
+ private:
+ mutable std::mutex mtx_;
+ std::unordered_map<std::wstring, std::shared_ptr<DatabaseAdapter>> adapters_;
+
+ // Helper: creates the adapter matching `config.databaseType`.
+ // Same switch used by ConnectionManager::createAdapter — we
+ // duplicate here to avoid a circular dep on ConnectionManager.cpp.
+ static std::shared_ptr<DatabaseAdapter> createAdapter(DatabaseType type);
+ };
+}
diff --git a/windows/Gridex/Services/MCP/MCPServer.cpp b/windows/Gridex/Services/MCP/MCPServer.cpp
new file mode 100644
index 0000000..aa1652c
--- /dev/null
+++ b/windows/Gridex/Services/MCP/MCPServer.cpp
@@ -0,0 +1,375 @@
+//
+// MCPServer.cpp
+//
+
+#include "MCPServer.h"
+#include "../../Models/ConnectionStore.h"
+#include "Tools/MCPBuiltinTools.h"
+
+#include <chrono>
+#include <regex>
+
+// For UUID generation (eventId).
+#include <windows.h>
+#include <rpc.h>
+#pragma comment(lib, "Rpcrt4.lib")
+
+namespace DBModels
+{
+ namespace
+ {
+ std::string generateEventId()
+ {
+ UUID u; UuidCreate(&u);
+ char* s = nullptr;
+ UuidToStringA(&u, reinterpret_cast<RPC_CSTR*>(&s));
+ std::string out = s ? s : "";
+ if (s) RpcStringFreeA(reinterpret_cast<RPC_CSTR*>(&s));
+ return out;
+ }
+
+ std::wstring utf8ToWide(const std::string& s)
+ {
+ if (s.empty()) return {};
+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);
+ std::wstring out(sz, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &out[0], sz);
+ return out;
+ }
+
+ std::string wideToUtf8(const std::wstring& s)
+ {
+ if (s.empty()) return {};
+ int sz = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), (int)s.size(),
+ nullptr, 0, nullptr, nullptr);
+ std::string out(sz, '\0');
+ WideCharToMultiByte(CP_UTF8, 0, s.c_str(), (int)s.size(), &out[0], sz, nullptr, nullptr);
+ return out;
+ }
+ }
+
+ MCPServer::~MCPServer() = default;
+
+ MCPServer::MCPServer(AppSettings settings, std::string serverVersion, MCPTransportMode mode)
+ : settings_(std::move(settings)),
+ serverVersion_(std::move(serverVersion)),
+ mode_(mode),
+ rateLimiter_(MCPRateLimiterConfig{
+ settings_.mcpQueriesPerMinute,
+ settings_.mcpQueriesPerHour,
+ settings_.mcpWritesPerMinute,
+ settings_.mcpDdlPerMinute
+ }),
+ auditLogger_(settings_.mcpAuditMaxSizeMB, settings_.mcpAuditRetentionDays)
+ {
+ }
+
+ void MCPServer::start()
+ {
+ if (running_.exchange(true)) return;
+
+ // Load per-connection MCP modes into the permission engine.
+ for (const auto& c : ConnectionStore::Load())
+ permissionEngine_.setMode(c.id, c.mcpMode);
+
+ registerBuiltinTools();
+
+ if (mode_ == MCPTransportMode::Stdio)
+ {
+ stdio_.setRequestHandler([this](const JSONRPCRequest& r){ handleRequest(r); });
+ stdio_.start();
+ }
+ else if (settings_.mcpHttpEnabled)
+ {
+ // HttpOnly mode + toggle is on → bind the HTTP listener.
+ // Defaults: 127.0.0.1:<mcpHttpPort>. Remote binding
+ // (0.0.0.0) only when allowRemoteHTTP is also on.
+ const int port = settings_.mcpHttpPort > 0
+ ? 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.
+ 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 == "prompts/list") return JSONRPCResponse::ok(r.id, nlohmann::json{{"prompts", nlohmann::json::array()}});
+ if (r.method == "resources/list") return JSONRPCResponse::ok(r.id, nlohmann::json{{"resources", nlohmann::json::array()}});
+ if (r.method == "resources/templates/list") return JSONRPCResponse::ok(r.id, nlohmann::json{{"resourceTemplates", nlohmann::json::array()}});
+ 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" || r.method == "notifications/initialized")
+ return JSONRPCResponse::ok(r.id, nullptr);
+ return JSONRPCResponse::fail(r.id, JSONRPCError::methodNotFound());
+ });
+ http_.start(host, port);
+ }
+ // else: HttpOnly mode but HTTP toggle is off — server runs
+ // "warm" (tools registered, audit log primed) without
+ // binding any socket. Flip the toggle on + Start again to
+ // actually listen.
+ }
+
+ void MCPServer::stop()
+ {
+ if (!running_.exchange(false)) return;
+ stdio_.stop();
+ http_.stop();
+ auditLogger_.close();
+ pool_.releaseAll();
+ }
+
+ void MCPServer::setUIContext(void* dq, void* xr)
+ {
+ approvalGate_.setUIContext(dq, xr);
+ }
+
+ // Phase 5 hooks register real tools here. Leaving empty avoids
+ // a forward-include chain on every Tier1/2/3 header until Phase 5
+ // lands — tools will add themselves via
+ // toolRegistry().registerTool(...) from a helper TU.
+ void MCPServer::registerBuiltinTools()
+ {
+ MCPBuiltinTools::registerAll(toolRegistry_);
+ }
+
+ // ── Request dispatch ─────────────────────────────────────
+
+ void MCPServer::handleRequest(const JSONRPCRequest& req)
+ {
+ JSONRPCResponse resp = JSONRPCResponse::fail(req.id, JSONRPCError::methodNotFound());
+ const std::string& m = req.method;
+
+ // Each handler is wrapped in try/catch so a single bad
+ // request (e.g. json serialization failure on a weird
+ // param type) cannot tear down the stdio reader thread.
+ try
+ {
+ if (m == "initialize") resp = handleInitialize(req);
+ // MCP notifications — client fire-and-forget, no response.
+ else if (m == "initialized") return;
+ else if (m == "notifications/initialized") return;
+ else if (m == "tools/list") resp = handleToolsList(req);
+ else if (m == "tools/call") resp = handleToolsCall(req);
+ // Claude CLI probes these even when our initialize
+ // doesn't advertise prompts/resources — return empty
+ // lists so the client treats the server as healthy
+ // instead of disconnecting on methodNotFound.
+ else if (m == "prompts/list")
+ resp = JSONRPCResponse::ok(req.id, nlohmann::json{{"prompts", nlohmann::json::array()}});
+ else if (m == "resources/list")
+ resp = JSONRPCResponse::ok(req.id, nlohmann::json{{"resources", nlohmann::json::array()}});
+ else if (m == "resources/templates/list")
+ resp = JSONRPCResponse::ok(req.id, nlohmann::json{{"resourceTemplates", nlohmann::json::array()}});
+ else if (m == "ping")
+ resp = JSONRPCResponse::ok(req.id, nlohmann::json{{"pong", true}});
+ else if (m == "shutdown")
+ {
+ resp = JSONRPCResponse::ok(req.id, nullptr);
+ sendResponse(resp);
+ stop();
+ return;
+ }
+ }
+ catch (const std::exception& e)
+ {
+ JSONRPCError err{
+ static_cast<int>(JSONRPCError::internalError().code),
+ std::string("handler exception: ") + e.what()
+ };
+ resp = JSONRPCResponse::fail(req.id, err);
+ }
+ catch (...)
+ {
+ resp = JSONRPCResponse::fail(req.id, JSONRPCError::internalError());
+ }
+
+ sendResponse(resp);
+ }
+
+ JSONRPCResponse MCPServer::handleInitialize(const JSONRPCRequest& req)
+ {
+ if (req.params.is_object() && req.params.contains("clientInfo"))
+ {
+ const auto& ci = req.params["clientInfo"];
+ clientInfo_.name = ci.value("name", std::string{"unknown"});
+ clientInfo_.version = ci.value("version", std::string{"0.0.0"});
+ }
+
+ const auto info = MCPServerInfo::gridex(serverVersion_);
+ const nlohmann::json result{
+ {"serverInfo",
+ {{"name", info.name}, {"version", info.version}}},
+ {"protocolVersion", info.protocolVersion},
+ {"capabilities", mcpDefaultCapabilities()}
+ };
+ return JSONRPCResponse::ok(req.id, result);
+ }
+
+ JSONRPCResponse MCPServer::handleToolsList(const JSONRPCRequest& req)
+ {
+ auto defs = toolRegistry_.definitions();
+ nlohmann::json arr = nlohmann::json::array();
+ for (const auto& d : defs)
+ {
+ nlohmann::json dj;
+ to_json(dj, d);
+ arr.push_back(dj);
+ }
+ return JSONRPCResponse::ok(req.id, nlohmann::json{{"tools", arr}});
+ }
+
+ JSONRPCResponse MCPServer::handleToolsCall(const JSONRPCRequest& req)
+ {
+ if (!req.params.is_object() ||
+ !req.params.contains("name") || !req.params["name"].is_string())
+ return JSONRPCResponse::fail(req.id, JSONRPCError::invalidParams());
+
+ const std::string name = req.params["name"].get<std::string>();
+ const nlohmann::json args = req.params.value("arguments", nlohmann::json::object());
+
+ auto tool = toolRegistry_.get(name);
+ if (!tool)
+ {
+ JSONRPCError e;
+ e.code = static_cast<int>(MCPErrorCode::NotFound);
+ e.message = "Tool '" + name + "' not found";
+ return JSONRPCResponse::fail(req.id, e);
+ }
+
+ const auto startTime = std::chrono::steady_clock::now();
+
+ MCPAuditClient auditClient{
+ clientInfo_.name,
+ clientInfo_.version,
+ mode_ == MCPTransportMode::Stdio ? "stdio" : "http"
+ };
+ MCPToolContext ctx{ pool_, permissionEngine_, rateLimiter_,
+ approvalGate_, auditLogger_, auditClient };
+
+ // Best-effort extraction for audit entry fields.
+ std::optional<std::string> connIdStr;
+ std::optional<std::string> connTypeStr;
+ if (args.contains("connection_id") && args["connection_id"].is_string())
+ {
+ connIdStr = args["connection_id"].get<std::string>();
+ // Try to resolve type (non-fatal).
+ try
+ {
+ auto wid = utf8ToWide(*connIdStr);
+ auto configs = ConnectionStore::Load();
+ for (const auto& c : configs)
+ if (c.id == wid)
+ { connTypeStr = wideToUtf8(DatabaseTypeDisplayName(c.databaseType)); break; }
+ }
+ catch (...) {}
+ }
+
+ MCPAuditEntry audit;
+ audit.eventId = generateEventId();
+ audit.client = auditClient;
+ audit.tool = name;
+ audit.tier = static_cast<int>(tool->tier());
+ audit.connectionId = connIdStr;
+ audit.connectionType = connTypeStr;
+
+ if (args.contains("sql") && args["sql"].is_string())
+ {
+ std::optional<int> pc;
+ if (args.contains("params") && args["params"].is_array())
+ pc = static_cast<int>(args["params"].size());
+ audit.input = MCPAuditInput::fromSQL(args["sql"].get<std::string>(), pc);
+ }
+
+ try
+ {
+ auto result = tool->execute(args, ctx);
+ const auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now() - startTime).count();
+ audit.result.durationMs = static_cast<int>(dur);
+ audit.result.status = result.isError
+ ? MCPAuditStatus::Error : MCPAuditStatus::Success;
+
+ // Record mode + usage.
+ if (connIdStr)
+ {
+ const auto wid = utf8ToWide(*connIdStr);
+ audit.security.permissionMode = permissionEngine_.getMode(wid);
+ rateLimiter_.recordUsage(tool->tier(), wid);
+ }
+ auditLogger_.log(audit);
+
+ nlohmann::json rj;
+ to_json(rj, result);
+ return JSONRPCResponse::ok(req.id, rj);
+ }
+ catch (const MCPToolError& e)
+ {
+ const auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now() - startTime).count();
+ const std::string err = sanitizeError(e.what());
+
+ audit.result.durationMs = static_cast<int>(dur);
+ audit.result.status = MCPAuditStatus::Error;
+ audit.error = err;
+ if (connIdStr)
+ audit.security.permissionMode =
+ permissionEngine_.getMode(utf8ToWide(*connIdStr));
+ auditLogger_.log(audit);
+
+ // Tool errors surface as tool result with isError=true
+ // (mac behavior) rather than JSON-RPC errors, so the AI
+ // client sees the message content.
+ auto tr = MCPToolResult::error(err);
+ nlohmann::json rj;
+ to_json(rj, tr);
+ return JSONRPCResponse::ok(req.id, rj);
+ }
+ catch (const std::exception& e)
+ {
+ const auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now() - startTime).count();
+ const std::string err = sanitizeError(e.what());
+
+ audit.result.durationMs = static_cast<int>(dur);
+ audit.result.status = MCPAuditStatus::Error;
+ audit.error = err;
+ auditLogger_.log(audit);
+
+ auto tr = MCPToolResult::error(err);
+ nlohmann::json rj;
+ to_json(rj, tr);
+ return JSONRPCResponse::ok(req.id, rj);
+ }
+ }
+
+ void MCPServer::sendResponse(const JSONRPCResponse& resp)
+ {
+ if (mode_ == MCPTransportMode::Stdio)
+ stdio_.send(resp);
+ // HTTP transport: Phase 4d.
+ }
+
+ std::string MCPServer::sanitizeError(const std::string& msg)
+ {
+ static const std::regex reUsers(R"(/Users/[^/\s]+)");
+ static const std::regex reHome(R"(/home/[^/\s]+)");
+ static const std::regex reWinUser(R"([Cc]:\\Users\\[^\\\s]+)");
+ static const std::regex rePG(R"(postgres://[^\s]+)");
+ static const std::regex reMY(R"(mysql://[^\s]+)");
+ static const std::regex reMG(R"(mongodb://[^\s]+)");
+
+ std::string s = msg;
+ s = std::regex_replace(s, reUsers, "[path]");
+ s = std::regex_replace(s, reHome, "[path]");
+ s = std::regex_replace(s, reWinUser,"[path]");
+ s = std::regex_replace(s, rePG, "[connection]");
+ s = std::regex_replace(s, reMY, "[connection]");
+ s = std::regex_replace(s, reMG, "[connection]");
+ return s;
+ }
+}
diff --git a/windows/Gridex/Services/MCP/MCPServer.h b/windows/Gridex/Services/MCP/MCPServer.h
new file mode 100644
index 0000000..5301e30
--- /dev/null
+++ b/windows/Gridex/Services/MCP/MCPServer.h
@@ -0,0 +1,108 @@
+#pragma once
+//
+// MCPServer.h
+// Gridex
+//
+// Orchestrator. Owns registry + security + audit + pool + transports.
+// Handles the three MCP protocol verbs: initialize, tools/list,
+// tools/call. Mirrors macos/Services/MCP/MCPServer.swift.
+//
+// Transport modes:
+// - Stdio: CLI `--mcp-stdio`. Uses stdin/stdout, no UI.
+// Tier 3 tools auto-deny (no window for ContentDialog).
+// - HttpOnly: GUI mode. HTTP endpoint (Phase 4d, TBD) on 127.0.0.1:port.
+// Tier 3 tools can open the approval dialog on MainWindow.
+
+#include <memory>
+#include <atomic>
+#include <string>
+#include "MCPConnectionPool.h"
+#include "Tools/MCPTool.h"
+#include "Tools/MCPToolRegistry.h"
+#include "Security/MCPPermissionEngine.h"
+#include "Security/MCPRateLimiter.h"
+#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"
+
+namespace DBModels
+{
+ enum class MCPTransportMode
+ {
+ Stdio, // CLI mode — stdin/stdout
+ HttpOnly // GUI mode — HTTP transport only
+ };
+
+ class MCPServer
+ {
+ public:
+ 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();
+
+ // Graceful shutdown — closes transports, flushes audit,
+ // releases pool adapters.
+ void stop();
+
+ bool isRunning() const { return running_.load(); }
+
+ // Expose the subsystems for the UI (MCPWindow needs pool
+ // stats, audit entries, permission modes).
+ MCPPermissionEngine& permissionEngine() { return permissionEngine_; }
+ MCPRateLimiter& rateLimiter() { return rateLimiter_; }
+ MCPAuditLogger& auditLogger() { return auditLogger_; }
+ MCPConnectionPool& pool() { return pool_; }
+ MCPApprovalGate& approvalGate() { return approvalGate_; }
+ MCPToolRegistry& toolRegistry() { return toolRegistry_; }
+
+ // Called by MainWindow once it is activated.
+ void setUIContext(void* dispatcherQueue, void* xamlRoot);
+
+ // Register all built-in tools. Called from start() — made
+ // public so tests can wire up selectively.
+ void registerBuiltinTools();
+
+ private:
+ AppSettings settings_;
+ std::string serverVersion_;
+ MCPTransportMode mode_;
+ std::atomic<bool> running_{false};
+
+ MCPConnectionPool pool_;
+ MCPPermissionEngine permissionEngine_;
+ MCPRateLimiter rateLimiter_;
+ MCPApprovalGate approvalGate_;
+ MCPAuditLogger auditLogger_;
+ MCPToolRegistry toolRegistry_;
+ StdioTransport stdio_;
+ HttpTransport http_;
+
+ MCPClientInfo clientInfo_; // populated on initialize
+
+ // Request dispatch.
+ void handleRequest(const JSONRPCRequest& req);
+ JSONRPCResponse handleInitialize(const JSONRPCRequest& req);
+ JSONRPCResponse handleToolsList(const JSONRPCRequest& req);
+ JSONRPCResponse handleToolsCall(const JSONRPCRequest& req);
+
+ // Sends back via the active transport.
+ void sendResponse(const JSONRPCResponse& resp);
+
+ // Strip filesystem paths / connection strings from error
+ // messages before the client sees them. Matches mac's
+ // sanitizeError.
+ static std::string sanitizeError(const std::string& msg);
+ };
+}
diff --git a/windows/Gridex/Services/MCP/MCPServerHost.cpp b/windows/Gridex/Services/MCP/MCPServerHost.cpp
new file mode 100644
index 0000000..cdf4dc7
--- /dev/null
+++ b/windows/Gridex/Services/MCP/MCPServerHost.cpp
@@ -0,0 +1,49 @@
+//
+// MCPServerHost.cpp
+//
+
+#include "MCPServerHost.h"
+
+namespace DBModels { namespace MCPServerHost {
+
+namespace {
+ std::mutex g_mtx;
+ // 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;
+}
+
+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_shared<MCPServer>(settings, version, mode);
+ return g_server;
+}
+
+std::shared_ptr<MCPServer> instance()
+{
+ std::lock_guard<std::mutex> lk(g_mtx);
+ return g_server;
+}
+
+void start()
+{
+ std::shared_ptr<MCPServer> local;
+ { std::lock_guard<std::mutex> lk(g_mtx); local = g_server; }
+ if (local) local->start();
+}
+
+void stop()
+{
+ 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
new file mode 100644
index 0000000..c839b2d
--- /dev/null
+++ b/windows/Gridex/Services/MCP/MCPServerHost.h
@@ -0,0 +1,37 @@
+#pragma once
+//
+// MCPServerHost.h
+// Gridex
+//
+// Process-wide singleton that owns the MCPServer instance. Created
+// lazily at first start(), kept alive until app exit. Lets
+// MainWindow, MCPPage, HomePage, and the CLI entry point share the
+// same server without passing it through every constructor.
+//
+// Thread-safe: start/stop take an internal mutex.
+
+#include <memory>
+#include <mutex>
+#include "MCPServer.h"
+
+namespace DBModels { namespace MCPServerHost {
+
+// Ensures a server exists (creating on demand with the supplied
+// 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 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();
+
+// Stops + destroys the shared server. Called from app shutdown.
+void stop();
+
+}} // namespace
diff --git a/windows/Gridex/Services/MCP/Security/MCPApprovalGate.cpp b/windows/Gridex/Services/MCP/Security/MCPApprovalGate.cpp
new file mode 100644
index 0000000..572b849
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPApprovalGate.cpp
@@ -0,0 +1,158 @@
+//
+// MCPApprovalGate.cpp
+//
+// Implementation marshals a ContentDialog onto the MainWindow
+// DispatcherQueue. winrt com_ptr handles are stored in opaque
+// void* members of MCPApprovalGate so the header stays free of
+// winrt includes.
+
+#include "MCPApprovalGate.h"
+
+#include <windows.h>
+#include <winrt/Microsoft.UI.Dispatching.h>
+#include <winrt/Microsoft.UI.Xaml.h>
+#include <winrt/Microsoft.UI.Xaml.Controls.h>
+#include <winrt/Windows.Foundation.h>
+#include <atomic>
+#include <memory>
+
+namespace mux = winrt::Microsoft::UI::Xaml;
+namespace mxc = winrt::Microsoft::UI::Xaml::Controls;
+namespace mxd = winrt::Microsoft::UI::Dispatching;
+
+namespace DBModels
+{
+ void MCPApprovalGate::setUIContext(void* dispatcherQueue, void* xamlRoot)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ dispatcher_ = dispatcherQueue;
+ xamlRoot_ = xamlRoot;
+ }
+
+ void MCPApprovalGate::revokeSessionApproval(const std::wstring& connectionId)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ for (auto it = sessionApprovals_.begin(); it != sessionApprovals_.end(); )
+ {
+ if (it->first.first == connectionId) it = sessionApprovals_.erase(it);
+ else ++it;
+ }
+ }
+
+ void MCPApprovalGate::revokeAllSessionApprovals()
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ sessionApprovals_.clear();
+ }
+
+ std::future<bool> MCPApprovalGate::requestApproval(const MCPApprovalRequest& req)
+ {
+ auto promise = std::make_shared<std::promise<bool>>();
+ auto future = promise->get_future();
+
+ const auto key = std::make_pair(req.connectionId, req.tool);
+
+ // Session cache hit?
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ auto it = sessionApprovals_.find(key);
+ if (it != sessionApprovals_.end())
+ {
+ const auto age = std::chrono::system_clock::now() - it->second;
+ if (age < kSessionTTL)
+ {
+ promise->set_value(true);
+ return future;
+ }
+ }
+ }
+
+ // No UI hookup yet (server in headless / pre-window state).
+ // Fail closed — deny rather than hang forever.
+ if (!dispatcher_ || !xamlRoot_)
+ {
+ promise->set_value(false);
+ return future;
+ }
+
+ // Copy winrt handles onto the stack before capturing.
+ auto dispatcher = *reinterpret_cast<mxd::DispatcherQueue*>(&dispatcher_);
+ auto xamlRoot = *reinterpret_cast<mux::XamlRoot*>(&xamlRoot_);
+
+ auto resolved = std::make_shared<std::atomic<bool>>(false);
+
+ auto self = this;
+ auto enqueued = dispatcher.TryEnqueue(
+ [self, req, xamlRoot, promise, resolved, key]()
+ {
+ try
+ {
+ mxc::ContentDialog dlg;
+ dlg.Title(winrt::box_value(winrt::hstring(
+ req.clientName + L" wants to:")));
+
+ const std::wstring body =
+ req.description + L"\n\n" +
+ req.details + L"\n\n" +
+ L"Connection: " + (req.connectionId.size() > 8
+ ? req.connectionId.substr(0, 8) + L"..."
+ : req.connectionId);
+
+ dlg.Content(winrt::box_value(winrt::hstring(body)));
+ dlg.CloseButtonText(L"Deny");
+ dlg.PrimaryButtonText(L"Approve Once");
+ dlg.SecondaryButtonText(L"Approve for Session");
+ dlg.DefaultButton(mxc::ContentDialogButton::Close);
+ dlg.XamlRoot(xamlRoot);
+
+ auto op = dlg.ShowAsync();
+ op.Completed(
+ [self, promise, resolved, key](
+ auto const& asyncOp,
+ winrt::Windows::Foundation::AsyncStatus status)
+ {
+ if (resolved->exchange(true)) return;
+
+ bool approved = false;
+ bool sessionApproval = false;
+ if (status == winrt::Windows::Foundation::AsyncStatus::Completed)
+ {
+ try
+ {
+ const auto r = asyncOp.GetResults();
+ if (r == mxc::ContentDialogResult::Primary)
+ approved = true;
+ else if (r == mxc::ContentDialogResult::Secondary)
+ {
+ approved = true;
+ sessionApproval = true;
+ }
+ }
+ catch (...) {}
+ }
+
+ if (sessionApproval)
+ {
+ std::lock_guard<std::mutex> lk(self->mtx_);
+ self->sessionApprovals_[key] =
+ std::chrono::system_clock::now();
+ }
+
+ promise->set_value(approved);
+ });
+ }
+ catch (...)
+ {
+ if (!resolved->exchange(true))
+ promise->set_value(false);
+ }
+ });
+
+ if (!enqueued)
+ {
+ // Dispatcher already shut down.
+ promise->set_value(false);
+ }
+ return future;
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPApprovalGate.h b/windows/Gridex/Services/MCP/Security/MCPApprovalGate.h
new file mode 100644
index 0000000..7515ba2
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPApprovalGate.h
@@ -0,0 +1,83 @@
+#pragma once
+//
+// MCPApprovalGate.h
+// Gridex
+//
+// Presents a ContentDialog on the MainWindow XAML root and returns
+// the user's verdict via std::future<bool>. Mirrors
+// macos/Services/MCP/Security/MCPApprovalGate.swift but uses Win32
+// threading primitives instead of Swift actors.
+//
+// The tool layer calls `requestApproval(...).get()` on a worker
+// thread (HTTP/stdio request handler). The dialog is marshalled
+// onto the UI thread via DispatcherQueue::TryEnqueue.
+
+#include <string>
+#include <future>
+#include <chrono>
+#include <mutex>
+#include <unordered_map>
+#include <utility>
+
+// Forward-declare winrt types so this header stays usable in
+// non-winrt TUs. Full types pulled in by the .cpp.
+namespace winrt::Microsoft::UI::Dispatching { struct DispatcherQueue; }
+namespace winrt::Microsoft::UI::Xaml { struct XamlRoot; }
+
+namespace DBModels
+{
+ struct MCPApprovalRequest
+ {
+ std::wstring tool; // tool name
+ std::wstring description; // "Insert 3 rows into 'users'"
+ std::wstring details; // multi-line body — SQL + row count
+ std::wstring connectionId;
+ std::wstring clientName; // shown as "<client> wants to:"
+ int timeoutSeconds = 60;
+ };
+
+ class MCPApprovalGate
+ {
+ public:
+ MCPApprovalGate() = default;
+
+ // Set once from MainWindow after the window is activated.
+ // Approvals requested before this is set auto-deny with a
+ // logged warning (the server may be running headless via
+ // --mcp-stdio CLI mode, in which case Tier 3 tools are
+ // expected to be unavailable — documented in Setup tab).
+ void setUIContext(void* dispatcherQueue, void* xamlRoot);
+
+ std::future<bool> requestApproval(const MCPApprovalRequest& req);
+
+ void revokeSessionApproval(const std::wstring& connectionId);
+ void revokeAllSessionApprovals();
+
+ private:
+ // Session cache key = (connectionId, tool). 30-minute TTL
+ // matches macOS.
+ using SessionKey = std::pair<std::wstring, std::wstring>;
+ struct SessionKeyHash
+ {
+ size_t operator()(const SessionKey& k) const noexcept
+ {
+ const auto h1 = std::hash<std::wstring>{}(k.first);
+ const auto h2 = std::hash<std::wstring>{}(k.second);
+ return h1 ^ (h2 << 1);
+ }
+ };
+
+ mutable std::mutex mtx_;
+ std::unordered_map<SessionKey,
+ std::chrono::system_clock::time_point,
+ SessionKeyHash> sessionApprovals_;
+
+ // UI thread hook — opaque void* here, winrt::com_ptr<...>
+ // on the impl side to avoid dragging winrt headers into
+ // every consumer.
+ void* dispatcher_ = nullptr;
+ void* xamlRoot_ = nullptr;
+
+ static constexpr std::chrono::seconds kSessionTTL{30 * 60};
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPIdentifierValidator.cpp b/windows/Gridex/Services/MCP/Security/MCPIdentifierValidator.cpp
new file mode 100644
index 0000000..9767c93
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPIdentifierValidator.cpp
@@ -0,0 +1,61 @@
+//
+// MCPIdentifierValidator.cpp
+//
+
+#include "MCPIdentifierValidator.h"
+#include "../../../Models/MCP/MCPToolError.h"
+
+namespace DBModels { namespace MCPIdentifierValidator {
+
+bool isValid(const std::string& identifier)
+{
+ if (identifier.empty() || identifier.size() > static_cast<size_t>(kMaxLength))
+ return false;
+
+ for (size_t i = 0; i < identifier.size(); ++i)
+ {
+ const unsigned char c = static_cast<unsigned char>(identifier[i]);
+ const bool isLetter = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';
+ const bool isDigit = c >= '0' && c <= '9';
+ if (i == 0)
+ {
+ if (!isLetter) return false;
+ }
+ else
+ {
+ if (!isLetter && !isDigit) return false;
+ }
+ }
+ return true;
+}
+
+void validate(const std::string& identifier, const std::string& name)
+{
+ if (!isValid(identifier))
+ {
+ throw MCPToolError::invalidParameters(
+ name + " '" + identifier + "' contains invalid characters. "
+ "Allowed: letters, digits, underscore; must start with a letter or underscore; max "
+ + std::to_string(kMaxLength) + " chars.");
+ }
+}
+
+TableSchema extractTableAndSchema(const nlohmann::json& params)
+{
+ TableSchema ts;
+ if (!params.contains("table_name") || !params["table_name"].is_string())
+ throw MCPToolError::invalidParameters("table_name is required");
+
+ ts.table = params["table_name"].get<std::string>();
+ validate(ts.table, "table_name");
+
+ if (params.contains("schema") && params["schema"].is_string())
+ {
+ auto s = params["schema"].get<std::string>();
+ validate(s, "schema");
+ ts.schema = s;
+ }
+ return ts;
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/MCP/Security/MCPIdentifierValidator.h b/windows/Gridex/Services/MCP/Security/MCPIdentifierValidator.h
new file mode 100644
index 0000000..80a8a2c
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPIdentifierValidator.h
@@ -0,0 +1,39 @@
+#pragma once
+//
+// MCPIdentifierValidator.h
+// Gridex
+//
+// Allowlist check for SQL identifiers (table / column / schema
+// names) received from MCP clients. Defense-in-depth: even when
+// the identifier later hits `quoteSqlIdentifier`, anything outside
+// a strict ASCII shape is rejected before reaching a driver.
+//
+// Port of macos/Services/MCP/Security/MCPIdentifierValidator.swift.
+
+#include <string>
+#include <optional>
+#include <nlohmann/json.hpp>
+
+namespace DBModels
+{
+ namespace MCPIdentifierValidator
+ {
+ constexpr int kMaxLength = 128;
+
+ // ASCII: first char [A-Za-z_], rest [A-Za-z0-9_], length 1..128.
+ bool isValid(const std::string& identifier);
+
+ // Throws MCPToolError::InvalidParameters on failure.
+ void validate(const std::string& identifier, const std::string& name = "identifier");
+
+ // Shared extraction used by the write tools. Pulls
+ // `table_name` (required) and `schema` (optional) from the
+ // JSON params, validating both. Returns (table, schema_or_null).
+ struct TableSchema
+ {
+ std::string table;
+ std::optional<std::string> schema;
+ };
+ TableSchema extractTableAndSchema(const nlohmann::json& params);
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPPermissionEngine.cpp b/windows/Gridex/Services/MCP/Security/MCPPermissionEngine.cpp
new file mode 100644
index 0000000..514534a
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPPermissionEngine.cpp
@@ -0,0 +1,200 @@
+//
+// MCPPermissionEngine.cpp
+//
+// Notes on porting from Swift:
+// * `actor` → `std::mutex`-guarded members.
+// * NSRegularExpression → `std::regex`. ECMAScript flavor accepts
+// `\b` word anchors; tested empirically on MSVC.
+// * Whitespace helpers use <cctype> isspace to avoid std::isspace
+// locale overloads that choke on char >= 0x80.
+
+#include "MCPPermissionEngine.h"
+#include "MCPSQLSanitizer.h"
+#include <regex>
+#include <algorithm>
+#include <cctype>
+#include <unordered_set>
+
+namespace DBModels
+{
+ // Static — these allocations happen once at first call.
+ namespace
+ {
+ const std::vector<std::string>& readOnlyPrefixes()
+ {
+ static const std::vector<std::string> v{
+ "SELECT", "SHOW", "EXPLAIN", "DESCRIBE", "DESC", "WITH"
+ };
+ return v;
+ }
+
+ // Must match mac's MCPPermissionEngine.dangerousKeywords exactly
+ // — drift here is a security bug.
+ const std::regex& dangerousKeywordRegex()
+ {
+ static const std::regex re(
+ R"(\b(INSERT|UPDATE|DELETE|MERGE|UPSERT|DROP|CREATE|ALTER|TRUNCATE|RENAME|)"
+ R"(GRANT|REVOKE|CALL|EXEC|EXECUTE|DO|NEXTVAL|SETVAL|LO_IMPORT|LO_EXPORT|)"
+ R"(PG_READ_SERVER_FILES|PG_WRITE_SERVER_FILES|PG_READ_BINARY_FILE|PG_LS_DIR|)"
+ R"(DBLINK|DBLINK_EXEC|COPY|VACUUM|ANALYZE|REINDEX|CLUSTER|REFRESH|LOCK|UNLOCK|)"
+ R"(SET|RESET|BEGIN|COMMIT|ROLLBACK|SAVEPOINT)\b)",
+ std::regex::icase | std::regex::ECMAScript);
+ return re;
+ }
+
+ std::string trim(const std::string& s)
+ {
+ size_t a = 0, b = s.size();
+ while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;
+ while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;
+ return s.substr(a, b - a);
+ }
+
+ std::string upper(std::string s)
+ {
+ std::transform(s.begin(), s.end(), s.begin(),
+ [](unsigned char c) { return static_cast<char>(std::toupper(c)); });
+ return s;
+ }
+
+ bool startsWith(const std::string& s, const std::string& prefix)
+ {
+ return s.size() >= prefix.size() &&
+ std::equal(prefix.begin(), prefix.end(), s.begin());
+ }
+ }
+
+ // ── Mode bookkeeping ─────────────────────────────────────
+
+ void MCPPermissionEngine::setMode(const std::wstring& id, MCPConnectionMode mode)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ modes_[id] = mode;
+ }
+
+ MCPConnectionMode MCPPermissionEngine::getMode(const std::wstring& id) const
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ auto it = modes_.find(id);
+ return it != modes_.end() ? it->second : MCPConnectionMode::Locked;
+ }
+
+ void MCPPermissionEngine::removeMode(const std::wstring& id)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ modes_.erase(id);
+ }
+
+ // ── Permission check ─────────────────────────────────────
+
+ MCPPermissionResult MCPPermissionEngine::checkPermission(
+ MCPPermissionTier tier, const std::wstring& id) const
+ {
+ return checkPermission(tier, getMode(id));
+ }
+
+ MCPPermissionResult MCPPermissionEngine::checkPermission(
+ MCPPermissionTier tier, MCPConnectionMode mode) const
+ {
+ switch (tier)
+ {
+ case MCPPermissionTier::Schema:
+ return mcpAllowsTier1(mode)
+ ? MCPPermissionResult::allowed()
+ : MCPPermissionResult::denied("Connection is locked. MCP access is disabled.");
+
+ case MCPPermissionTier::Read:
+ return mcpAllowsTier2(mode)
+ ? MCPPermissionResult::allowed()
+ : MCPPermissionResult::denied("Connection is locked. MCP access is disabled.");
+
+ case MCPPermissionTier::Write:
+ if (!mcpAllowsTier3(mode))
+ return MCPPermissionResult::denied(
+ "This operation requires read-write mode. Ask the user to enable it in Connection Settings > MCP Access.");
+ return MCPPermissionResult::requiresApproval();
+
+ case MCPPermissionTier::DDL:
+ if (!mcpAllowsTier4(mode))
+ return MCPPermissionResult::denied(
+ "DDL operations require read-write mode. Ask the user to enable it in Connection Settings > MCP Access.");
+ return MCPPermissionResult::requiresApproval();
+
+ case MCPPermissionTier::Advanced:
+ return mcpAllowsTier5(mode)
+ ? MCPPermissionResult::allowed()
+ : MCPPermissionResult::denied("Connection is locked. MCP access is disabled.");
+ }
+ return MCPPermissionResult::denied("Unknown tier");
+ }
+
+ // ── Read-only SQL validator ──────────────────────────────
+
+ MCPPermissionResult MCPPermissionEngine::validateReadOnlyQuery(const std::string& sql) const
+ {
+ const std::string code = MCPSQLSanitizer::stripCommentsAndStrings(sql);
+ const std::string trimmedUpper = upper(trim(code));
+
+ std::string withoutTrailingSemi = trimmedUpper;
+ if (!withoutTrailingSemi.empty() && withoutTrailingSemi.back() == ';')
+ {
+ withoutTrailingSemi.pop_back();
+ withoutTrailingSemi = trim(withoutTrailingSemi);
+ }
+ if (withoutTrailingSemi.find(';') != std::string::npos)
+ return MCPPermissionResult::denied("Multiple statements are not allowed in read-only mode.");
+
+ bool ok = false;
+ for (const auto& p : readOnlyPrefixes())
+ if (startsWith(trimmedUpper, p)) { ok = true; break; }
+ if (!ok)
+ return MCPPermissionResult::denied("Only SELECT queries are allowed in read-only mode. This query appears to modify data.");
+
+ std::smatch m;
+ if (std::regex_search(code, m, dangerousKeywordRegex()))
+ {
+ const std::string hit = upper(m.str());
+ return MCPPermissionResult::denied(
+ "Query contains '" + hit + "' which is not allowed in read-only mode.");
+ }
+
+ return MCPPermissionResult::allowed();
+ }
+
+ // ── WHERE clause validator ───────────────────────────────
+
+ MCPPermissionResult MCPPermissionEngine::validateWhereClause(const std::string& whereClause) const
+ {
+ if (whereClause.empty())
+ return MCPPermissionResult::denied(
+ "WHERE clause is required for UPDATE/DELETE operations. Bare UPDATE/DELETE without WHERE is not allowed.");
+
+ const std::string trimmed = trim(whereClause);
+ if (trimmed.empty())
+ return MCPPermissionResult::denied("WHERE clause is required for UPDATE/DELETE operations.");
+
+ if (trimmed.find(';') != std::string::npos)
+ return MCPPermissionResult::denied("WHERE clause must not contain ';' — statement terminators are forbidden.");
+ if (trimmed.find("--") != std::string::npos)
+ return MCPPermissionResult::denied("WHERE clause must not contain '--' — SQL line comments are forbidden.");
+ if (trimmed.find("/*") != std::string::npos || trimmed.find("*/") != std::string::npos)
+ return MCPPermissionResult::denied("WHERE clause must not contain '/*' or '*/' — SQL block comments are forbidden.");
+
+ // Trivial predicate check: uppercase, strip ALL whitespace.
+ std::string compact;
+ compact.reserve(trimmed.size());
+ for (char c : trimmed)
+ if (!std::isspace(static_cast<unsigned char>(c)))
+ compact.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(c))));
+
+ static const std::unordered_set<std::string> trivial{
+ "1=1", "TRUE", "1", "'1'='1'",
+ "1<>0", "0=0", "2>1", "TRUE=TRUE", "NULLISNULL"
+ };
+ if (trivial.count(compact) != 0)
+ return MCPPermissionResult::denied(
+ "Trivial WHERE clause '" + trimmed + "' is not allowed. Provide a meaningful predicate.");
+
+ return MCPPermissionResult::allowed();
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPPermissionEngine.h b/windows/Gridex/Services/MCP/Security/MCPPermissionEngine.h
new file mode 100644
index 0000000..caf628a
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPPermissionEngine.h
@@ -0,0 +1,56 @@
+#pragma once
+//
+// MCPPermissionEngine.h
+// Gridex
+//
+// Thread-safe per-connection permission gate. Mirrors
+// macos/Services/MCP/Security/MCPPermissionEngine.swift.
+//
+// Two primary responsibilities:
+// 1. Map connectionId → MCPConnectionMode, combined with tier to
+// emit Allowed | RequiresApproval | Denied.
+// 2. Syntactic validators for SELECT-only enforcement
+// (validateReadOnlyQuery) and UPDATE/DELETE WHERE clauses
+// (validateWhereClause).
+
+#include <string>
+#include <unordered_map>
+#include <mutex>
+#include "../../../Models/MCP/MCPConnectionMode.h"
+#include "../../../Models/MCP/MCPPermissionTier.h"
+#include "MCPPermissionResult.h"
+
+namespace DBModels
+{
+ class MCPPermissionEngine
+ {
+ public:
+ // Mode bookkeeping. `connectionId` is the same wstring id
+ // used by ConnectionConfig / ConnectionStore.
+ void setMode(const std::wstring& connectionId, MCPConnectionMode mode);
+ MCPConnectionMode getMode(const std::wstring& connectionId) const;
+ void removeMode(const std::wstring& connectionId);
+
+ // Core gate. Takes a snapshot of the mode and runs the
+ // Swift decision table.
+ MCPPermissionResult checkPermission(MCPPermissionTier tier,
+ const std::wstring& connectionId) const;
+ MCPPermissionResult checkPermission(MCPPermissionTier tier,
+ MCPConnectionMode mode) const;
+
+ // SELECT-only enforcement for Tier 2 queries in read-only
+ // mode. Runs MCPSQLSanitizer first, then:
+ // - rejects multi-statement (`;` anywhere except trailing)
+ // - requires prefix ∈ {SELECT, SHOW, EXPLAIN, DESCRIBE, DESC, WITH}
+ // - blocks 30+ dangerous keywords via regex
+ MCPPermissionResult validateReadOnlyQuery(const std::string& sql) const;
+
+ // Mandatory WHERE validator for Tier 3 write tools.
+ // Rejects bare clauses, `;`, SQL comments, and trivial tautologies.
+ MCPPermissionResult validateWhereClause(const std::string& whereClause) const;
+
+ private:
+ mutable std::mutex mtx_;
+ std::unordered_map<std::wstring, MCPConnectionMode> modes_;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPPermissionResult.h b/windows/Gridex/Services/MCP/Security/MCPPermissionResult.h
new file mode 100644
index 0000000..69e2bb1
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPPermissionResult.h
@@ -0,0 +1,40 @@
+#pragma once
+//
+// MCPPermissionResult.h
+// Gridex
+//
+// Tagged union returned by MCPPermissionEngine::checkPermission.
+// Mirrors macos enum MCPPermissionResult { .allowed, .requiresApproval, .denied(String) }.
+
+#include <string>
+
+namespace DBModels
+{
+ struct MCPPermissionResult
+ {
+ enum class Kind { Allowed, RequiresApproval, Denied };
+ Kind kind = Kind::Allowed;
+ std::string message; // populated only when kind == Denied
+
+ static MCPPermissionResult allowed()
+ {
+ return { Kind::Allowed, {} };
+ }
+ static MCPPermissionResult requiresApproval()
+ {
+ return { Kind::RequiresApproval, {} };
+ }
+ static MCPPermissionResult denied(std::string msg)
+ {
+ return { Kind::Denied, std::move(msg) };
+ }
+
+ bool isAllowed() const { return kind == Kind::Allowed; }
+ bool requiresUserApproval() const { return kind == Kind::RequiresApproval; }
+ // Returns nullptr when no error message (Allowed or RequiresApproval).
+ const std::string* errorMessage() const
+ {
+ return kind == Kind::Denied ? &message : nullptr;
+ }
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPRateLimiter.cpp b/windows/Gridex/Services/MCP/Security/MCPRateLimiter.cpp
new file mode 100644
index 0000000..84bd859
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPRateLimiter.cpp
@@ -0,0 +1,157 @@
+//
+// MCPRateLimiter.cpp
+//
+
+#include "MCPRateLimiter.h"
+#include <algorithm>
+
+namespace DBModels
+{
+ using TimePoint = std::chrono::system_clock::time_point;
+
+ // ── RateBucket ───────────────────────────────────────────
+
+ int MCPRateLimiter::RateBucket::countInWindow(TimePoint now, int windowSeconds) const
+ {
+ const auto cutoff = now - std::chrono::seconds(windowSeconds);
+ int n = 0;
+ for (const auto& t : stamps) if (t > cutoff) ++n;
+ return n;
+ }
+
+ TimePoint MCPRateLimiter::RateBucket::oldestInWindow(TimePoint now, int windowSeconds) const
+ {
+ const auto cutoff = now - std::chrono::seconds(windowSeconds);
+ TimePoint best{};
+ bool have = false;
+ for (const auto& t : stamps)
+ {
+ if (t > cutoff && (!have || t < best)) { best = t; have = true; }
+ }
+ return have ? best : now;
+ }
+
+ void MCPRateLimiter::RateBucket::cleanup(TimePoint now, int maxAgeSeconds)
+ {
+ const auto cutoff = now - std::chrono::seconds(maxAgeSeconds);
+ stamps.erase(
+ std::remove_if(stamps.begin(), stamps.end(),
+ [cutoff](const TimePoint& t) { return t <= cutoff; }),
+ stamps.end());
+ }
+
+ // ── Public API ───────────────────────────────────────────
+
+ void MCPRateLimiter::setConfig(const MCPRateLimiterConfig& c)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ cfg_ = c;
+ }
+
+ MCPRateLimitResult MCPRateLimiter::checkLimit(
+ MCPPermissionTier tier, const std::wstring& id)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ const auto now = std::chrono::system_clock::now();
+ switch (tier)
+ {
+ case MCPPermissionTier::Schema:
+ case MCPPermissionTier::Read:
+ case MCPPermissionTier::Advanced:
+ return checkQuery(id, now);
+ case MCPPermissionTier::Write:
+ return checkWrite(id, now);
+ case MCPPermissionTier::DDL:
+ return checkDDL(id, now);
+ }
+ return { true, 0 };
+ }
+
+ void MCPRateLimiter::recordUsage(MCPPermissionTier tier, const std::wstring& id)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ const auto now = std::chrono::system_clock::now();
+ auto record = [now](auto& map, const std::wstring& key, int maxAge)
+ {
+ auto& bucket = map[key];
+ bucket.record(now);
+ bucket.cleanup(now, maxAge);
+ };
+ switch (tier)
+ {
+ case MCPPermissionTier::Schema:
+ case MCPPermissionTier::Read:
+ case MCPPermissionTier::Advanced:
+ record(queryBuckets_, id, 3600); break;
+ case MCPPermissionTier::Write:
+ record(writeBuckets_, id, 60); break;
+ case MCPPermissionTier::DDL:
+ record(ddlBuckets_, id, 60); break;
+ }
+ }
+
+ void MCPRateLimiter::resetLimits(const std::wstring& id)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ queryBuckets_.erase(id);
+ writeBuckets_.erase(id);
+ ddlBuckets_.erase(id);
+ }
+
+ void MCPRateLimiter::resetAllLimits()
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ queryBuckets_.clear();
+ writeBuckets_.clear();
+ ddlBuckets_.clear();
+ }
+
+ // ── Internal: per-tier check ─────────────────────────────
+ // (callers hold mtx_)
+
+ MCPRateLimitResult MCPRateLimiter::checkQuery(const std::wstring& id, TimePoint now)
+ {
+ auto& b = queryBuckets_[id];
+ const int minuteCount = b.countInWindow(now, 60);
+ if (minuteCount >= cfg_.queriesPerMinute)
+ {
+ const auto oldest = b.oldestInWindow(now, 60);
+ const int retry = 60 - static_cast<int>(std::chrono::duration_cast<std::chrono::seconds>(now - oldest).count());
+ return { false, std::max(1, retry) };
+ }
+ const int hourCount = b.countInWindow(now, 3600);
+ if (hourCount >= cfg_.queriesPerHour)
+ {
+ const auto oldest = b.oldestInWindow(now, 3600);
+ const int retry = 3600 - static_cast<int>(std::chrono::duration_cast<std::chrono::seconds>(now - oldest).count());
+ return { false, std::max(1, retry) };
+ }
+ return { true, 0 };
+ }
+
+ MCPRateLimitResult MCPRateLimiter::checkWrite(const std::wstring& id, TimePoint now)
+ {
+ auto& b = writeBuckets_[id];
+ const int n = b.countInWindow(now, 60);
+ if (n >= cfg_.writesPerMinute)
+ {
+ const auto oldest = b.oldestInWindow(now, 60);
+ const int retry = 60 - static_cast<int>(std::chrono::duration_cast<std::chrono::seconds>(now - oldest).count());
+ return { false, std::max(1, retry) };
+ }
+ return { true, 0 };
+ }
+
+ MCPRateLimitResult MCPRateLimiter::checkDDL(const std::wstring& id, TimePoint now)
+ {
+ auto& b = ddlBuckets_[id];
+ const int n = b.countInWindow(now, 60);
+ if (n >= cfg_.ddlPerMinute)
+ {
+ const auto oldest = b.oldestInWindow(now, 60);
+ const int retry = 60 - static_cast<int>(std::chrono::duration_cast<std::chrono::seconds>(now - oldest).count());
+ return { false, std::max(1, retry) };
+ }
+ return { true, 0 };
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPRateLimiter.h b/windows/Gridex/Services/MCP/Security/MCPRateLimiter.h
new file mode 100644
index 0000000..6df2c4f
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPRateLimiter.h
@@ -0,0 +1,73 @@
+#pragma once
+//
+// MCPRateLimiter.h
+// Gridex
+//
+// Per-connection sliding-window rate limiter. Mirrors
+// macos/Services/MCP/Security/MCPRateLimiter.swift.
+//
+// Three independent buckets (query / write / DDL) keyed by
+// connection id. Limits are injected from AppSettings at
+// MCPServer startup (no runtime reconfiguration in v1).
+
+#include <string>
+#include <vector>
+#include <unordered_map>
+#include <mutex>
+#include <chrono>
+#include "../../../Models/MCP/MCPPermissionTier.h"
+
+namespace DBModels
+{
+ struct MCPRateLimitResult
+ {
+ bool allowed = true;
+ int retryAfterSeconds = 0;
+ };
+
+ struct MCPRateLimiterConfig
+ {
+ int queriesPerMinute = 60;
+ int queriesPerHour = 1000;
+ int writesPerMinute = 10;
+ int ddlPerMinute = 1;
+ };
+
+ class MCPRateLimiter
+ {
+ public:
+ explicit MCPRateLimiter(MCPRateLimiterConfig cfg = {}) : cfg_(cfg) {}
+
+ void setConfig(const MCPRateLimiterConfig& cfg);
+
+ MCPRateLimitResult checkLimit(MCPPermissionTier tier,
+ const std::wstring& connectionId);
+ void recordUsage(MCPPermissionTier tier,
+ const std::wstring& connectionId);
+
+ void resetLimits(const std::wstring& connectionId);
+ void resetAllLimits();
+
+ private:
+ using TimePoint = std::chrono::system_clock::time_point;
+
+ struct RateBucket
+ {
+ std::vector<TimePoint> stamps;
+ void record(TimePoint now) { stamps.push_back(now); }
+ int countInWindow(TimePoint now, int windowSeconds) const;
+ TimePoint oldestInWindow(TimePoint now, int windowSeconds) const;
+ void cleanup(TimePoint now, int maxAgeSeconds);
+ };
+
+ mutable std::mutex mtx_;
+ MCPRateLimiterConfig cfg_;
+ std::unordered_map<std::wstring, RateBucket> queryBuckets_;
+ std::unordered_map<std::wstring, RateBucket> writeBuckets_;
+ std::unordered_map<std::wstring, RateBucket> ddlBuckets_;
+
+ MCPRateLimitResult checkQuery(const std::wstring& id, TimePoint now);
+ MCPRateLimitResult checkWrite(const std::wstring& id, TimePoint now);
+ MCPRateLimitResult checkDDL(const std::wstring& id, TimePoint now);
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPRowCountEstimator.cpp b/windows/Gridex/Services/MCP/Security/MCPRowCountEstimator.cpp
new file mode 100644
index 0000000..3696f9d
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPRowCountEstimator.cpp
@@ -0,0 +1,49 @@
+//
+// MCPRowCountEstimator.cpp
+//
+
+#include "MCPRowCountEstimator.h"
+#include <stdexcept>
+
+namespace DBModels { namespace MCPRowCountEstimator {
+
+static bool isSQLDatabase(DatabaseType t)
+{
+ // Redis / MongoDB have no SQL COUNT(*) equivalent in this shape.
+ return t == DatabaseType::PostgreSQL ||
+ t == DatabaseType::MySQL ||
+ t == DatabaseType::SQLite ||
+ t == DatabaseType::MSSQLServer;
+}
+
+int estimate(const std::shared_ptr<DatabaseAdapter>& adapter,
+ const std::wstring& qualifiedTable,
+ const std::wstring& whereClause,
+ const ConnectionConfig& config)
+{
+ if (!adapter || !isSQLDatabase(config.databaseType))
+ return 0;
+
+ const std::wstring sql =
+ L"SELECT COUNT(*) AS cnt FROM " + qualifiedTable +
+ L" WHERE " + whereClause;
+
+ try
+ {
+ QueryResult r = adapter->execute(sql);
+ if (!r.success || r.rows.empty() || r.columnNames.empty())
+ return 0;
+ const auto& row = r.rows[0];
+ // Row is unordered_map<wstring,wstring> keyed by column name.
+ const auto it = row.find(r.columnNames[0]);
+ if (it == row.end()) return 0;
+ const std::wstring& val = it->second;
+ try { return std::stoi(val); } catch (...) { return 0; }
+ }
+ catch (...)
+ {
+ return 0;
+ }
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/MCP/Security/MCPRowCountEstimator.h b/windows/Gridex/Services/MCP/Security/MCPRowCountEstimator.h
new file mode 100644
index 0000000..3515c55
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPRowCountEstimator.h
@@ -0,0 +1,31 @@
+#pragma once
+//
+// MCPRowCountEstimator.h
+// Gridex
+//
+// Best-effort "SELECT COUNT(*) ..." estimate used by write tools
+// to show an affected-rows number in the approval dialog. Mirrors
+// macos/Services/MCP/Security/MCPRowCountEstimator.swift.
+//
+// Swallows every error and returns 0 — this is a UX aid, not a
+// correctness check. Callers MUST still validate the WHERE clause
+// via MCPPermissionEngine::validateWhereClause BEFORE calling.
+
+#include <string>
+#include <memory>
+#include "../../../Models/DatabaseAdapter.h"
+#include "../../../Models/ConnectionConfig.h"
+
+namespace DBModels
+{
+ namespace MCPRowCountEstimator
+ {
+ // `qualifiedTable` must already be quoted (caller used
+ // `adapter->quoteSqlIdentifier`). `whereClause` is untrusted
+ // but gated by validateWhereClause upstream.
+ int estimate(const std::shared_ptr<DatabaseAdapter>& adapter,
+ const std::wstring& qualifiedTable,
+ const std::wstring& whereClause,
+ const ConnectionConfig& config);
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Security/MCPSQLSanitizer.cpp b/windows/Gridex/Services/MCP/Security/MCPSQLSanitizer.cpp
new file mode 100644
index 0000000..f9627e2
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPSQLSanitizer.cpp
@@ -0,0 +1,74 @@
+//
+// MCPSQLSanitizer.cpp
+//
+
+#include "MCPSQLSanitizer.h"
+
+namespace DBModels { namespace MCPSQLSanitizer {
+
+std::string stripCommentsAndStrings(const std::string& sql)
+{
+ std::string result;
+ result.reserve(sql.size());
+ const size_t n = sql.size();
+ size_t i = 0;
+
+ while (i < n)
+ {
+ const char c = sql[i];
+ const char next = (i + 1 < n) ? sql[i + 1] : '\0';
+
+ // -- line comment: consume until newline
+ if (c == '-' && next == '-')
+ {
+ while (i < n && sql[i] != '\n') ++i;
+ continue;
+ }
+
+ // /* block comment */
+ if (c == '/' && next == '*')
+ {
+ i += 2;
+ while (i < n)
+ {
+ if (sql[i] == '*' && i + 1 < n && sql[i + 1] == '/')
+ {
+ i += 2;
+ break;
+ }
+ ++i;
+ }
+ continue;
+ }
+
+ // 'single-quoted literal' with '' escape support
+ if (c == '\'')
+ {
+ ++i; // skip opening quote
+ while (i < n)
+ {
+ if (sql[i] == '\'')
+ {
+ if (i + 1 < n && sql[i + 1] == '\'')
+ {
+ // escaped '' inside literal — keep scanning
+ i += 2;
+ continue;
+ }
+ ++i; // consume closing quote
+ break;
+ }
+ ++i;
+ }
+ result.push_back(' ');
+ continue;
+ }
+
+ result.push_back(c);
+ ++i;
+ }
+
+ return result;
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/MCP/Security/MCPSQLSanitizer.h b/windows/Gridex/Services/MCP/Security/MCPSQLSanitizer.h
new file mode 100644
index 0000000..7c9fc29
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Security/MCPSQLSanitizer.h
@@ -0,0 +1,27 @@
+#pragma once
+//
+// MCPSQLSanitizer.h
+// Gridex
+//
+// Strips SQL line comments, block comments, and string literals so
+// syntactic checks (prefix check, dangerous-keyword regex) operate
+// on code-only content. NEVER use the sanitized string for
+// execution — it is destructive (literals turned into single space).
+//
+// Port of macos/Services/MCP/Security/MCPSQLSanitizer.swift.
+
+#include <string>
+
+namespace DBModels
+{
+ namespace MCPSQLSanitizer
+ {
+ // Returns `sql` with:
+ // -- line comments removed
+ // /* block comments */ removed
+ // 'single-quoted literals' collapsed to a single space
+ //
+ // Handles escaped `''` inside a literal correctly.
+ std::string stripCommentsAndStrings(const std::string& sql);
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.cpp b/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.cpp
new file mode 100644
index 0000000..8e9dc61
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.cpp
@@ -0,0 +1,48 @@
+//
+// MCPBuiltinTools.cpp
+//
+// All Phase 5 read/schema tools. Tier-3 write tools (insert_rows,
+// update_rows, delete_rows, execute_write_query) land in Round 1B.
+
+#include "MCPBuiltinTools.h"
+#include "Tier1/ListConnectionsTool.h"
+#include "Tier1/ListTablesTool.h"
+#include "Tier1/DescribeTableTool.h"
+#include "Tier1/ListSchemasTool.h"
+#include "Tier1/ListRelationshipsTool.h"
+#include "Tier1/GetSampleRowsTool.h"
+#include "Tier2/QueryTool.h"
+#include "Tier2/ExplainQueryTool.h"
+#include "Tier2/SearchAcrossTablesTool.h"
+#include "Tier3/InsertRowsTool.h"
+#include "Tier3/UpdateRowsTool.h"
+#include "Tier3/DeleteRowsTool.h"
+#include "Tier3/ExecuteWriteQueryTool.h"
+
+namespace DBModels { namespace MCPBuiltinTools {
+
+void registerAll(MCPToolRegistry& r)
+{
+ // Tier 1 — schema introspection (available in any non-Locked mode).
+ r.registerTool(std::make_shared<ListConnectionsTool>());
+ r.registerTool(std::make_shared<ListTablesTool>());
+ r.registerTool(std::make_shared<DescribeTableTool>());
+ r.registerTool(std::make_shared<ListSchemasTool>());
+ r.registerTool(std::make_shared<ListRelationshipsTool>());
+ r.registerTool(std::make_shared<GetSampleRowsTool>());
+
+ // Tier 2 — read queries (ReadOnly allowed, ReadWrite too).
+ r.registerTool(std::make_shared<QueryTool>());
+ r.registerTool(std::make_shared<ExplainQueryTool>());
+ r.registerTool(std::make_shared<SearchAcrossTablesTool>());
+
+ // Tier 3 — write tools. ReadWrite mode only; each call goes
+ // through MCPApprovalGate (ContentDialog on the MainWindow
+ // XamlRoot) before the adapter sees the SQL.
+ r.registerTool(std::make_shared<InsertRowsTool>());
+ r.registerTool(std::make_shared<UpdateRowsTool>());
+ r.registerTool(std::make_shared<DeleteRowsTool>());
+ r.registerTool(std::make_shared<ExecuteWriteQueryTool>());
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.h b/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.h
new file mode 100644
index 0000000..bc460df
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.h
@@ -0,0 +1,19 @@
+#pragma once
+//
+// MCPBuiltinTools.h
+// Gridex
+//
+// Single entry point that registers every shipped MCP tool into
+// an MCPToolRegistry. Keeps MCPServer.cpp free of per-tool
+// includes — when Phase 5 expands beyond 4 tools, just grow the
+// cpp here.
+
+#include "MCPToolRegistry.h"
+
+namespace DBModels
+{
+ namespace MCPBuiltinTools
+ {
+ void registerAll(MCPToolRegistry& registry);
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/MCPTool.cpp b/windows/Gridex/Services/MCP/Tools/MCPTool.cpp
new file mode 100644
index 0000000..d6d4ff7
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/MCPTool.cpp
@@ -0,0 +1,76 @@
+//
+// MCPTool.cpp
+//
+
+#include "MCPTool.h"
+#include "../../../Models/ConnectionStore.h"
+#include "../../../Models/MCP/MCPAuditEntry.h"
+#include <algorithm>
+#include <windows.h>
+
+namespace DBModels
+{
+ std::wstring MCPTool::extractConnectionId(const nlohmann::json& params)
+ {
+ if (!params.contains("connection_id") || !params["connection_id"].is_string())
+ throw MCPToolError::invalidParameters("connection_id is required");
+ 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>
+ MCPToolContext::getAdapter(const std::wstring& connectionId) const
+ {
+ // Look up the config from the connection store. Linear scan
+ // is fine — typical users have <50 connections.
+ auto configs = ConnectionStore::Load();
+ auto it = std::find_if(configs.begin(), configs.end(),
+ [&](const ConnectionConfig& c) { return c.id == connectionId; });
+ if (it == configs.end())
+ {
+ std::string narrow(connectionId.begin(), connectionId.end());
+ throw MCPToolError::connectionNotFound(narrow);
+ }
+
+ // Password comes from ConnectionStore — it DPAPI-decrypts the
+ // `password_enc` column into ConnectionConfig::password during
+ // Load(). CredentialManager (Windows Credential Vault) isn't
+ // wired in this codebase yet; looking there would always
+ // return empty and the adapter would hit
+ // 'fe_sendauth: no password supplied' (observed against
+ // PostgreSQL).
+ auto& ncPool = const_cast<MCPConnectionPool&>(pool);
+ auto adapter = ncPool.acquire(*it, it->password);
+ return { adapter, *it };
+ }
+
+ bool MCPToolContext::requestApproval(
+ const std::wstring& toolName,
+ const std::wstring& description,
+ const std::wstring& details,
+ const std::wstring& connectionId,
+ const std::wstring& clientName,
+ int timeoutSeconds) const
+ {
+ MCPApprovalRequest req;
+ req.tool = toolName;
+ req.description = description;
+ req.details = details;
+ req.connectionId = connectionId;
+ req.clientName = clientName;
+ req.timeoutSeconds = timeoutSeconds;
+ auto& nc = const_cast<MCPApprovalGate&>(approvalGate);
+ auto future = nc.requestApproval(req);
+ // Block the worker thread — caller is on a stdio/http worker,
+ // not the UI thread, so this is safe.
+ return future.get();
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/MCPTool.h b/windows/Gridex/Services/MCP/Tools/MCPTool.h
new file mode 100644
index 0000000..f7a82df
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/MCPTool.h
@@ -0,0 +1,88 @@
+#pragma once
+//
+// MCPTool.h
+// Gridex
+//
+// Tool interface + context bundle passed at execute() time. The
+// MCPServer builds one MCPToolContext per request and hands it to
+// the tool. Tools throw MCPToolError on failure; the server folds
+// them into MCPToolResult::error for the client.
+
+#include <string>
+#include <memory>
+#include <nlohmann/json.hpp>
+#include "../../../Models/MCP/MCPToolDefinition.h"
+#include "../../../Models/MCP/MCPPermissionTier.h"
+#include "../../../Models/MCP/MCPToolError.h"
+#include "../../../Models/DatabaseAdapter.h"
+#include "../../../Models/ConnectionConfig.h"
+#include "../Security/MCPPermissionEngine.h"
+#include "../Security/MCPRateLimiter.h"
+#include "../Security/MCPApprovalGate.h"
+#include "../Audit/MCPAuditLogger.h"
+#include "../MCPConnectionPool.h"
+
+namespace DBModels
+{
+ // Forward-declared to break circularity with ConnectionStore.h.
+ // (Audit client is plain data.)
+ struct MCPAuditClient;
+
+ // Bundle of shared services made available to every tool.
+ // Members are non-owning references — the MCPServer owns them.
+ struct MCPToolContext
+ {
+ MCPConnectionPool& pool;
+ MCPPermissionEngine& permissionEngine;
+ MCPRateLimiter& rateLimiter;
+ MCPApprovalGate& approvalGate;
+ MCPAuditLogger& auditLogger;
+ MCPAuditClient client; // by-value; copied per-request
+
+ // Helper: looks up `connection_id` in JSON params, finds
+ // the matching ConnectionConfig, opens the adapter via the
+ // pool, returns (adapter, config).
+ // Throws MCPToolError::connectionNotFound if id is unknown.
+ std::pair<std::shared_ptr<DatabaseAdapter>, ConnectionConfig>
+ getAdapter(const std::wstring& connectionId) const;
+
+ MCPPermissionResult checkPermission(MCPPermissionTier tier,
+ const std::wstring& id) const
+ {
+ return permissionEngine.checkPermission(tier, id);
+ }
+
+ // Convenience — request approval and BLOCK the caller on
+ // the resulting future. Tools are invoked from worker
+ // threads, so blocking here is safe.
+ bool requestApproval(const std::wstring& tool,
+ const std::wstring& description,
+ const std::wstring& details,
+ const std::wstring& connectionId,
+ const std::wstring& clientName,
+ int timeoutSeconds = 60) const;
+ };
+
+ // Pure-virtual tool interface. All tool implementations inherit
+ // this + define name/description/tier/inputSchema + execute.
+ class MCPTool
+ {
+ public:
+ virtual ~MCPTool() = default;
+ virtual std::string name() const = 0;
+ virtual std::string description() const = 0;
+ virtual MCPPermissionTier tier() const = 0;
+ virtual nlohmann::json inputSchema() const = 0;
+ virtual MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& context) = 0;
+
+ MCPToolDefinition definition() const
+ {
+ return { name(), description(), inputSchema() };
+ }
+
+ // Helper: extract `connection_id` from JSON params and
+ // return it as wstring (the store's native id type).
+ static std::wstring extractConnectionId(const nlohmann::json& params);
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/MCPToolHelpers.h b/windows/Gridex/Services/MCP/Tools/MCPToolHelpers.h
new file mode 100644
index 0000000..2b3d9e7
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/MCPToolHelpers.h
@@ -0,0 +1,33 @@
+#pragma once
+//
+// MCPToolHelpers.h
+// Gridex
+//
+// Inline helpers shared by every MCP tool implementation. Kept
+// header-only to avoid a separate TU for string conversion.
+
+#include <string>
+#include <windows.h>
+
+namespace DBModels { namespace MCPToolHelpers {
+
+inline std::string toUtf8(const std::wstring& w)
+{
+ if (w.empty()) return {};
+ int sz = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(),
+ nullptr, 0, nullptr, nullptr);
+ std::string out(sz, '\0');
+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), &out[0], sz, nullptr, nullptr);
+ return out;
+}
+
+inline std::wstring fromUtf8(const std::string& s)
+{
+ if (s.empty()) return {};
+ int sz = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);
+ std::wstring out(sz, L'\0');
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), &out[0], sz);
+ return out;
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/MCP/Tools/MCPToolRegistry.cpp b/windows/Gridex/Services/MCP/Tools/MCPToolRegistry.cpp
new file mode 100644
index 0000000..887376a
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/MCPToolRegistry.cpp
@@ -0,0 +1,38 @@
+//
+// MCPToolRegistry.cpp
+//
+
+#include "MCPToolRegistry.h"
+
+namespace DBModels
+{
+ MCPToolRegistry::MCPToolRegistry() = default;
+
+ void MCPToolRegistry::registerTool(std::shared_ptr<MCPTool> tool)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ if (tool) tools_[tool->name()] = std::move(tool);
+ }
+
+ void MCPToolRegistry::unregisterTool(const std::string& name)
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ tools_.erase(name);
+ }
+
+ std::shared_ptr<MCPTool> MCPToolRegistry::get(const std::string& name) const
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ auto it = tools_.find(name);
+ return it != tools_.end() ? it->second : nullptr;
+ }
+
+ std::vector<MCPToolDefinition> MCPToolRegistry::definitions() const
+ {
+ std::lock_guard<std::mutex> lk(mtx_);
+ std::vector<MCPToolDefinition> out;
+ out.reserve(tools_.size());
+ for (const auto& [_, t] : tools_) out.push_back(t->definition());
+ return out;
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/MCPToolRegistry.h b/windows/Gridex/Services/MCP/Tools/MCPToolRegistry.h
new file mode 100644
index 0000000..ad5de91
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/MCPToolRegistry.h
@@ -0,0 +1,37 @@
+#pragma once
+//
+// MCPToolRegistry.h
+// Gridex
+//
+// Name → MCPTool mapping, populated at MCPServer startup with
+// all 13 tools (6 schema / 3 read / 4 write). Mirrors
+// macos/Services/MCP/Tools/MCPToolRegistry.swift.
+
+#include <string>
+#include <memory>
+#include <unordered_map>
+#include <vector>
+#include <mutex>
+#include "MCPTool.h"
+
+namespace DBModels
+{
+ class MCPToolRegistry
+ {
+ public:
+ // Registers built-in tools (Phase 5 populates).
+ MCPToolRegistry();
+
+ void registerTool(std::shared_ptr<MCPTool> tool);
+ void unregisterTool(const std::string& name);
+
+ std::shared_ptr<MCPTool> get(const std::string& name) const;
+
+ // All tool definitions for tools/list response.
+ std::vector<MCPToolDefinition> definitions() const;
+
+ private:
+ mutable std::mutex mtx_;
+ std::unordered_map<std::string, std::shared_ptr<MCPTool>> tools_;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/DescribeTableTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier1/DescribeTableTool.cpp
new file mode 100644
index 0000000..6b53c59
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/DescribeTableTool.cpp
@@ -0,0 +1,86 @@
+//
+// DescribeTableTool.cpp
+//
+
+#include "DescribeTableTool.h"
+#include "../MCPToolHelpers.h"
+#include "../../Security/MCPIdentifierValidator.h"
+
+namespace DBModels
+{
+ MCPToolResult DescribeTableTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto ts = MCPIdentifierValidator::extractTableAndSchema(params);
+
+ const std::wstring table = MCPToolHelpers::fromUtf8(ts.table);
+ const std::wstring schema = ts.schema.has_value()
+ ? MCPToolHelpers::fromUtf8(*ts.schema) : std::wstring{};
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+
+ auto columns = adapter->describeTable(table, schema);
+ auto indexes = adapter->listIndexes(table, schema);
+ auto foreignKeys= adapter->listForeignKeys(table, schema);
+
+ nlohmann::json result;
+ result["name"] = ts.table;
+ if (!schema.empty()) result["schema"] = *ts.schema;
+ result["database_type"] = MCPToolHelpers::toUtf8(
+ DatabaseTypeDisplayName(config.databaseType));
+
+ nlohmann::json cols = nlohmann::json::array();
+ nlohmann::json pkCols = nlohmann::json::array();
+ for (const auto& c : columns)
+ {
+ nlohmann::json cj = {
+ {"name", MCPToolHelpers::toUtf8(c.name)},
+ {"type", MCPToolHelpers::toUtf8(c.dataType)},
+ {"nullable", c.nullable}
+ };
+ if (c.isPrimaryKey) { cj["primary_key"] = true; pkCols.push_back(MCPToolHelpers::toUtf8(c.name)); }
+ if (!c.defaultValue.empty()) cj["default"] = MCPToolHelpers::toUtf8(c.defaultValue);
+ if (!c.comment.empty()) cj["comment"] = MCPToolHelpers::toUtf8(c.comment);
+ cols.push_back(std::move(cj));
+ }
+ result["columns"] = std::move(cols);
+ if (!pkCols.empty()) result["primary_key"] = std::move(pkCols);
+
+ if (!indexes.empty())
+ {
+ nlohmann::json idxs = nlohmann::json::array();
+ for (const auto& i : indexes)
+ {
+ idxs.push_back({
+ {"name", MCPToolHelpers::toUtf8(i.name)},
+ {"columns", MCPToolHelpers::toUtf8(i.columns)},
+ {"unique", i.isUnique},
+ {"type", MCPToolHelpers::toUtf8(i.algorithm.empty() ? L"btree" : i.algorithm)}
+ });
+ }
+ result["indexes"] = std::move(idxs);
+ }
+
+ if (!foreignKeys.empty())
+ {
+ nlohmann::json fks = nlohmann::json::array();
+ for (const auto& f : foreignKeys)
+ {
+ fks.push_back({
+ {"name", MCPToolHelpers::toUtf8(f.name)},
+ {"column", MCPToolHelpers::toUtf8(f.column)},
+ {"references_table", MCPToolHelpers::toUtf8(f.referencedTable)},
+ {"references_column", MCPToolHelpers::toUtf8(f.referencedColumn)}
+ });
+ }
+ result["foreign_keys"] = std::move(fks);
+ }
+
+ return MCPToolResult::text(result.dump(2));
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/DescribeTableTool.h b/windows/Gridex/Services/MCP/Tools/Tier1/DescribeTableTool.h
new file mode 100644
index 0000000..a6d69ed
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/DescribeTableTool.h
@@ -0,0 +1,38 @@
+#pragma once
+//
+// DescribeTableTool.h
+// Gridex
+//
+// Detailed table structure: columns, PK, FKs, indexes. Mirrors
+// macos DescribeTableTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class DescribeTableTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "describe_table"; }
+ std::string description() const override
+ {
+ return "Get detailed structure of a table including columns, data "
+ "types, indexes, primary keys, foreign keys, and constraints.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"table_name", {{"type", "string"}, {"description", "Name of the table to describe"}}},
+ {"schema", {{"type", "string"}, {"description", "Optional schema name"}}}
+ }},
+ {"required", {"connection_id", "table_name"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/GetSampleRowsTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier1/GetSampleRowsTool.cpp
new file mode 100644
index 0000000..ef606a1
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/GetSampleRowsTool.cpp
@@ -0,0 +1,70 @@
+//
+// GetSampleRowsTool.cpp
+//
+
+#include "GetSampleRowsTool.h"
+#include "../MCPToolHelpers.h"
+#include <algorithm>
+
+namespace DBModels
+{
+ MCPToolResult GetSampleRowsTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ if (!params.contains("table_name") || !params["table_name"].is_string())
+ throw MCPToolError::invalidParameters("table_name is required");
+ const auto tableUtf8 = params["table_name"].get<std::string>();
+ const std::wstring tableW = MCPToolHelpers::fromUtf8(tableUtf8);
+
+ const std::wstring schemaW = (params.contains("schema") && params["schema"].is_string())
+ ? MCPToolHelpers::fromUtf8(params["schema"].get<std::string>()) : std::wstring{};
+
+ int limit = 10;
+ if (params.contains("limit") && params["limit"].is_number_integer())
+ limit = (std::min)(100, (std::max)(1, params["limit"].get<int>()));
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+
+ // fetchRows signature: (table, schema, limit, offset, orderBy, ascending).
+ QueryResult r = adapter->fetchRows(tableW, schemaW, limit, 0, L"", true);
+ if (!r.success)
+ throw MCPToolError::queryFailed(MCPToolHelpers::toUtf8(r.error));
+
+ if (r.rows.empty())
+ return MCPToolResult::text("Table '" + tableUtf8 + "' is empty.");
+
+ // Columns header summary.
+ std::string cols = "Columns: ";
+ for (size_t i = 0; i < r.columnNames.size(); ++i)
+ {
+ if (i) cols += ", ";
+ cols += MCPToolHelpers::toUtf8(r.columnNames[i]);
+ if (i < r.columnTypes.size())
+ cols += " (" + MCPToolHelpers::toUtf8(r.columnTypes[i]) + ")";
+ }
+
+ nlohmann::json rows = nlohmann::json::array();
+ for (const auto& row : r.rows)
+ {
+ nlohmann::json o = nlohmann::json::object();
+ for (const auto& cname : r.columnNames)
+ {
+ auto it = row.find(cname);
+ const std::wstring v = (it != row.end()) ? it->second : L"";
+ o[MCPToolHelpers::toUtf8(cname)] =
+ isNullCell(v) ? nlohmann::json(nullptr)
+ : nlohmann::json(MCPToolHelpers::toUtf8(v));
+ }
+ rows.push_back(std::move(o));
+ }
+
+ return MCPToolResult::text(
+ "Sample " + std::to_string(r.rows.size()) + " row(s) from '" +
+ tableUtf8 + "':\n" + cols + "\n\n" + rows.dump(2));
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/GetSampleRowsTool.h b/windows/Gridex/Services/MCP/Tools/Tier1/GetSampleRowsTool.h
new file mode 100644
index 0000000..91941a7
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/GetSampleRowsTool.h
@@ -0,0 +1,38 @@
+#pragma once
+//
+// GetSampleRowsTool.h — Return up to N rows from a table so the
+// AI can understand the data shape. Mirrors macOS
+// GetSampleRowsTool.swift. Defaults to 10, hard-caps at 100.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class GetSampleRowsTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "get_sample_rows"; }
+ std::string description() const override
+ {
+ return "Get sample rows from a table so the AI can see the "
+ "data shape. Default limit 10, max 100.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"table_name", {{"type", "string"}, {"description", "Name of the table"}}},
+ {"schema", {{"type", "string"}, {"description", "Optional schema"}}},
+ {"limit", {{"type", "integer"}, {"default", 10},
+ {"minimum", 1}, {"maximum", 100}}}
+ }},
+ {"required", {"connection_id", "table_name"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/ListConnectionsTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier1/ListConnectionsTool.cpp
new file mode 100644
index 0000000..33f394b
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/ListConnectionsTool.cpp
@@ -0,0 +1,40 @@
+//
+// ListConnectionsTool.cpp
+//
+
+#include "ListConnectionsTool.h"
+#include "../MCPToolHelpers.h"
+#include "../../../../Models/ConnectionStore.h"
+
+namespace DBModels
+{
+ MCPToolResult ListConnectionsTool::execute(const nlohmann::json&, MCPToolContext& ctx)
+ {
+ const auto configs = ConnectionStore::Load();
+ nlohmann::json arr = nlohmann::json::array();
+
+ for (const auto& c : configs)
+ {
+ // Hide Locked rows entirely — mac parity.
+ const auto mode = ctx.permissionEngine.getMode(c.id);
+ if (mode == MCPConnectionMode::Locked) continue;
+
+ nlohmann::json entry = {
+ {"id", MCPToolHelpers::toUtf8(c.id)},
+ {"name", MCPToolHelpers::toUtf8(c.name)},
+ {"type", MCPToolHelpers::toUtf8(DatabaseTypeDisplayName(c.databaseType))},
+ {"host", MCPToolHelpers::toUtf8(c.host)},
+ {"database", MCPToolHelpers::toUtf8(c.database)},
+ {"mcp_mode", mcpRawString(mode)}
+ };
+ arr.push_back(std::move(entry));
+ }
+
+ if (arr.empty())
+ return MCPToolResult::text(
+ "No connections available for MCP access. All connections are "
+ "either locked or none exist.");
+
+ return MCPToolResult::text(arr.dump(2));
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/ListConnectionsTool.h b/windows/Gridex/Services/MCP/Tools/Tier1/ListConnectionsTool.h
new file mode 100644
index 0000000..ec23971
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/ListConnectionsTool.h
@@ -0,0 +1,34 @@
+#pragma once
+//
+// ListConnectionsTool.h
+// Gridex
+//
+// Returns every non-Locked connection visible to the AI client.
+// Mirrors macos Tier1/ListConnectionsTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class ListConnectionsTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "list_connections"; }
+ std::string description() const override
+ {
+ return "List all configured database connections that MCP can access. "
+ "Locked connections are omitted. Returns id, name, type, host, "
+ "and per-connection mcp_mode.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", nlohmann::json::object()}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/ListRelationshipsTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier1/ListRelationshipsTool.cpp
new file mode 100644
index 0000000..55fe51c
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/ListRelationshipsTool.cpp
@@ -0,0 +1,67 @@
+//
+// ListRelationshipsTool.cpp
+//
+
+#include "ListRelationshipsTool.h"
+#include "../MCPToolHelpers.h"
+
+namespace DBModels
+{
+ MCPToolResult ListRelationshipsTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ if (!params.contains("table_name") || !params["table_name"].is_string())
+ throw MCPToolError::invalidParameters("table_name is required");
+ const auto tableUtf8 = params["table_name"].get<std::string>();
+ const std::wstring tableW = MCPToolHelpers::fromUtf8(tableUtf8);
+
+ const std::wstring schemaW = (params.contains("schema") && params["schema"].is_string())
+ ? MCPToolHelpers::fromUtf8(params["schema"].get<std::string>()) : std::wstring{};
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+
+ nlohmann::json result;
+ result["table"] = tableUtf8;
+
+ // Outgoing: this table's FKs pointing at others.
+ nlohmann::json out = nlohmann::json::array();
+ for (const auto& fk : adapter->listForeignKeys(tableW, schemaW))
+ {
+ out.push_back({
+ {"name", MCPToolHelpers::toUtf8(fk.name)},
+ {"columns", MCPToolHelpers::toUtf8(fk.column)},
+ {"references_table", MCPToolHelpers::toUtf8(fk.referencedTable)},
+ {"references_columns",MCPToolHelpers::toUtf8(fk.referencedColumn)}
+ });
+ }
+ result["outgoing"] = out.empty() ? nlohmann::json("None") : out;
+
+ // Incoming: walk all tables and grab FKs whose target is this
+ // table. Linear in total-tables * avg-FKs-per-table; acceptable
+ // for typical schemas, and the MCP call is one-shot.
+ nlohmann::json in = nlohmann::json::array();
+ for (const auto& t : adapter->listTables(schemaW))
+ {
+ if (t.name == tableW) continue;
+ for (const auto& fk : adapter->listForeignKeys(t.name, schemaW))
+ {
+ if (fk.referencedTable == tableW)
+ {
+ in.push_back({
+ {"from_table", MCPToolHelpers::toUtf8(t.name)},
+ {"from_columns", MCPToolHelpers::toUtf8(fk.column)},
+ {"to_columns", MCPToolHelpers::toUtf8(fk.referencedColumn)}
+ });
+ }
+ }
+ }
+ result["incoming"] = in.empty() ? nlohmann::json("None") : in;
+
+ return MCPToolResult::text(result.dump(2));
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/ListRelationshipsTool.h b/windows/Gridex/Services/MCP/Tools/Tier1/ListRelationshipsTool.h
new file mode 100644
index 0000000..566ffe5
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/ListRelationshipsTool.h
@@ -0,0 +1,40 @@
+#pragma once
+//
+// ListRelationshipsTool.h — FK graph for a table: outgoing (this
+// table references others) + incoming (others reference this).
+// Mirrors macOS ListRelationshipsTool.swift.
+//
+// Incoming is O(N_tables * M_FKs) — we scan every table's FK set.
+// Fine for <200 tables; above that, add a schema filter param.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class ListRelationshipsTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "list_relationships"; }
+ std::string description() const override
+ {
+ return "List foreign-key relationships for a table. Returns both "
+ "outgoing (this -> other) and incoming (other -> this) "
+ "references.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"table_name", {{"type", "string"}, {"description", "Name of the table"}}},
+ {"schema", {{"type", "string"}, {"description", "Optional schema"}}}
+ }},
+ {"required", {"connection_id", "table_name"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/ListSchemasTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier1/ListSchemasTool.cpp
new file mode 100644
index 0000000..4be8098
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/ListSchemasTool.cpp
@@ -0,0 +1,45 @@
+//
+// ListSchemasTool.cpp
+//
+
+#include "ListSchemasTool.h"
+#include "../MCPToolHelpers.h"
+
+namespace DBModels
+{
+ static bool supportsSchemas(DatabaseType t)
+ {
+ return t == DatabaseType::PostgreSQL || t == DatabaseType::MSSQLServer;
+ }
+
+ MCPToolResult ListSchemasTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+
+ nlohmann::json arr = nlohmann::json::array();
+ std::wstring kind = L"Schemas";
+ if (supportsSchemas(config.databaseType))
+ {
+ for (const auto& s : adapter->listSchemas())
+ arr.push_back(MCPToolHelpers::toUtf8(s));
+ }
+ else
+ {
+ kind = L"Databases";
+ for (const auto& d : adapter->listDatabases())
+ arr.push_back(MCPToolHelpers::toUtf8(d));
+ }
+
+ if (arr.empty())
+ return MCPToolResult::text("No " + MCPToolHelpers::toUtf8(kind) + " found.");
+
+ return MCPToolResult::text(
+ MCPToolHelpers::toUtf8(kind) + ": " + arr.dump());
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/ListSchemasTool.h b/windows/Gridex/Services/MCP/Tools/Tier1/ListSchemasTool.h
new file mode 100644
index 0000000..271da2e
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/ListSchemasTool.h
@@ -0,0 +1,34 @@
+#pragma once
+//
+// ListSchemasTool.h — List schemas (Postgres/MSSQL) or databases
+// (MySQL / Redis) for a connection. Mirrors
+// macos/Services/MCP/Tools/Tier1/ListSchemasTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class ListSchemasTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "list_schemas"; }
+ std::string description() const override
+ {
+ return "List schemas (PostgreSQL / MSSQL) or databases "
+ "(MySQL / MongoDB) available on a connection.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}}
+ }},
+ {"required", {"connection_id"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/ListTablesTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier1/ListTablesTool.cpp
new file mode 100644
index 0000000..ec46903
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/ListTablesTool.cpp
@@ -0,0 +1,49 @@
+//
+// ListTablesTool.cpp
+//
+
+#include "ListTablesTool.h"
+#include "../MCPToolHelpers.h"
+
+namespace DBModels
+{
+ MCPToolResult ListTablesTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ std::wstring schema;
+ if (params.contains("schema") && params["schema"].is_string())
+ schema = MCPToolHelpers::fromUtf8(params["schema"].get<std::string>());
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+ auto tables = adapter->listTables(schema);
+
+ nlohmann::json arr = nlohmann::json::array();
+ for (const auto& t : tables)
+ {
+ nlohmann::json e = {
+ {"name", MCPToolHelpers::toUtf8(t.name)},
+ {"type", MCPToolHelpers::toUtf8(t.type.empty() ? L"table" : t.type)}
+ };
+ if (!t.schema.empty())
+ e["schema"] = MCPToolHelpers::toUtf8(t.schema);
+ if (t.estimatedRows > 0)
+ e["estimated_rows"] = t.estimatedRows;
+ arr.push_back(std::move(e));
+ }
+
+ if (arr.empty())
+ {
+ std::string suffix = schema.empty()
+ ? ""
+ : " in schema '" + MCPToolHelpers::toUtf8(schema) + "'";
+ return MCPToolResult::text("No tables found" + suffix + ".");
+ }
+ return MCPToolResult::text(
+ "Found " + std::to_string(arr.size()) + " table(s):\n" + arr.dump(2));
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier1/ListTablesTool.h b/windows/Gridex/Services/MCP/Tools/Tier1/ListTablesTool.h
new file mode 100644
index 0000000..d4aa5f5
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier1/ListTablesTool.h
@@ -0,0 +1,37 @@
+#pragma once
+//
+// ListTablesTool.h
+// Gridex
+//
+// List tables in a connection's specified schema (or all schemas if
+// omitted). Mirrors macos ListTablesTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class ListTablesTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "list_tables"; }
+ std::string description() const override
+ {
+ return "List all tables in a database connection. Returns table "
+ "names, schemas, and approximate row counts.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Schema; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"schema", {{"type", "string"}, {"description", "Optional schema/database filter"}}}
+ }},
+ {"required", {"connection_id"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier2/ExplainQueryTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier2/ExplainQueryTool.cpp
new file mode 100644
index 0000000..3321f32
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier2/ExplainQueryTool.cpp
@@ -0,0 +1,79 @@
+//
+// ExplainQueryTool.cpp
+//
+
+#include "ExplainQueryTool.h"
+#include "../MCPToolHelpers.h"
+
+namespace DBModels
+{
+ MCPToolResult ExplainQueryTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ if (!params.contains("sql") || !params["sql"].is_string())
+ throw MCPToolError::invalidParameters("sql is required");
+ const auto sqlUtf8 = params["sql"].get<std::string>();
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+ const std::wstring sqlW = MCPToolHelpers::fromUtf8(sqlUtf8);
+
+ std::wstring explainSQL;
+ switch (config.databaseType)
+ {
+ case DatabaseType::PostgreSQL:
+ explainSQL = L"EXPLAIN (ANALYZE false, COSTS true, FORMAT TEXT) " + sqlW;
+ break;
+ case DatabaseType::MySQL:
+ explainSQL = L"EXPLAIN " + sqlW;
+ break;
+ case DatabaseType::SQLite:
+ explainSQL = L"EXPLAIN QUERY PLAN " + sqlW;
+ break;
+ case DatabaseType::MSSQLServer:
+ // SET SHOWPLAN_TEXT is a session flag — bracket the
+ // query with it. Multi-statement; the adapter passes
+ // this through to the driver unchanged.
+ explainSQL = L"SET SHOWPLAN_TEXT ON; " + sqlW + L"; SET SHOWPLAN_TEXT OFF";
+ break;
+ default:
+ return MCPToolResult::error(
+ "EXPLAIN is not supported for " +
+ MCPToolHelpers::toUtf8(DatabaseTypeDisplayName(config.databaseType)) +
+ " connections.");
+ }
+
+ QueryResult r;
+ try { r = adapter->execute(explainSQL); }
+ catch (const std::exception& e)
+ { throw MCPToolError::queryFailed(e.what()); }
+ if (!r.success) throw MCPToolError::queryFailed(MCPToolHelpers::toUtf8(r.error));
+
+ std::string out = "Query Plan for: " + sqlUtf8 + "\n\n";
+ if (r.rows.empty())
+ {
+ out += "No plan information available.";
+ }
+ else
+ {
+ for (const auto& row : r.rows)
+ {
+ bool first = true;
+ for (const auto& cname : r.columnNames)
+ {
+ auto it = row.find(cname);
+ if (it == row.end()) continue;
+ if (!first) out += " | ";
+ first = false;
+ out += MCPToolHelpers::toUtf8(it->second);
+ }
+ out += "\n";
+ }
+ }
+ return MCPToolResult::text(out);
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier2/ExplainQueryTool.h b/windows/Gridex/Services/MCP/Tools/Tier2/ExplainQueryTool.h
new file mode 100644
index 0000000..26bd531
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier2/ExplainQueryTool.h
@@ -0,0 +1,36 @@
+#pragma once
+//
+// ExplainQueryTool.h — Return the EXPLAIN plan for a SQL query
+// without executing it. Mirrors macOS ExplainQueryTool.swift.
+// Dialect-specific prefix: EXPLAIN for PG/MySQL, EXPLAIN QUERY PLAN
+// for SQLite, SHOWPLAN_TEXT for MSSQL. Redis/Mongo return an error.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class ExplainQueryTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "explain_query"; }
+ std::string description() const override
+ {
+ return "Get the EXPLAIN plan for a SQL query without executing "
+ "it. Helps the AI reason about performance.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Read; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"sql", {{"type", "string"}, {"description", "SQL query to explain"}}}
+ }},
+ {"required", {"connection_id", "sql"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.cpp
new file mode 100644
index 0000000..a4cd9d1
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.cpp
@@ -0,0 +1,124 @@
+//
+// QueryTool.cpp
+//
+
+#include "QueryTool.h"
+#include "../MCPToolHelpers.h"
+#include <algorithm>
+
+namespace DBModels
+{
+ // 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;
+ }
+
+ MCPToolResult QueryTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ if (!params.contains("sql") || !params["sql"].is_string())
+ throw MCPToolError::invalidParameters("sql is required");
+ const std::string sqlUtf8 = params["sql"].get<std::string>();
+
+ int rowLimit = 1000;
+ if (params.contains("row_limit") && params["row_limit"].is_number_integer())
+ rowLimit = std::clamp(params["row_limit"].get<int>(), 1, 10000);
+
+ // Base permission.
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ // Read-only SELECT check if mode == ReadOnly.
+ const auto mode = ctx.permissionEngine.getMode(connId);
+ if (mode == MCPConnectionMode::ReadOnly)
+ {
+ auto v = ctx.permissionEngine.validateReadOnlyQuery(sqlUtf8);
+ if (const auto* m = v.errorMessage())
+ throw MCPToolError::permissionDenied(*m);
+ }
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+
+ // Append LIMIT if absent and target is SQL. Keep the raw
+ // sql untouched otherwise (Redis/Mongo adapters carry their
+ // own shape).
+ std::wstring sqlW = MCPToolHelpers::fromUtf8(sqlUtf8);
+ 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;
+ while (!trimmed.empty() && (trimmed.back() == L' ' ||
+ trimmed.back() == L';' || trimmed.back() == L'\n'))
+ trimmed.pop_back();
+ sqlW = trimmed + L" LIMIT " + std::to_wstring(rowLimit);
+ }
+ }
+
+ QueryResult r;
+ try { r = adapter->execute(sqlW); }
+ catch (const std::exception& e)
+ { throw MCPToolError::queryFailed(e.what()); }
+
+ if (!r.success)
+ throw MCPToolError::queryFailed(MCPToolHelpers::toUtf8(r.error));
+
+ nlohmann::json response;
+ response["success"] = true;
+ response["row_count"] = static_cast<int>(r.rows.size());
+ response["execution_time_ms"] = static_cast<int>(r.executionTimeMs);
+
+ nlohmann::json cols = nlohmann::json::array();
+ for (size_t i = 0; i < r.columnNames.size(); ++i)
+ {
+ nlohmann::json c{
+ {"name", MCPToolHelpers::toUtf8(r.columnNames[i])}
+ };
+ if (i < r.columnTypes.size())
+ c["type"] = MCPToolHelpers::toUtf8(r.columnTypes[i]);
+ cols.push_back(std::move(c));
+ }
+ response["columns"] = std::move(cols);
+
+ nlohmann::json rows = nlohmann::json::array();
+ // Parenthesize to defeat windows.h `min` macro in consumers.
+ const int cap = (std::min)(static_cast<int>(r.rows.size()), rowLimit);
+ for (int i = 0; i < cap; ++i)
+ {
+ nlohmann::json rj = nlohmann::json::object();
+ for (const auto& cname : r.columnNames)
+ {
+ auto it = r.rows[i].find(cname);
+ const std::wstring v = (it != r.rows[i].end()) ? it->second : L"";
+ rj[MCPToolHelpers::toUtf8(cname)] =
+ isNullCell(v) ? nlohmann::json(nullptr)
+ : nlohmann::json(MCPToolHelpers::toUtf8(v));
+ }
+ rows.push_back(std::move(rj));
+ }
+ response["rows"] = std::move(rows);
+
+ if (static_cast<int>(r.rows.size()) > rowLimit)
+ {
+ response["truncated"] = true;
+ response["message"] = "Results truncated to " + std::to_string(rowLimit) + " rows";
+ }
+
+ return MCPToolResult::text(response.dump(2));
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.h b/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.h
new file mode 100644
index 0000000..f0bb4dd
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier2/QueryTool.h
@@ -0,0 +1,44 @@
+#pragma once
+//
+// QueryTool.h
+// Gridex
+//
+// Execute a SQL query. In read-only mode, only SELECT is allowed —
+// enforced via MCPPermissionEngine::validateReadOnlyQuery. Mirrors
+// macos Tier2/QueryTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class QueryTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "query"; }
+ std::string description() const override
+ {
+ return "Execute a SQL query. In read-only mode, only SELECT statements "
+ "are allowed. Returns rows with metadata (column types, row "
+ "count, execution time).";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Read; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"sql", {{"type", "string"}, {"description", "SQL query to execute"}}},
+ {"row_limit", {
+ {"type", "integer"},
+ {"description", "Maximum rows to return (default 1000, max 10000)"},
+ {"default", 1000}, {"maximum", 10000}
+ }}
+ }},
+ {"required", {"connection_id", "sql"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.cpp
new file mode 100644
index 0000000..36a70b0
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.cpp
@@ -0,0 +1,87 @@
+//
+// SearchAcrossTablesTool.cpp
+//
+
+#include "SearchAcrossTablesTool.h"
+#include "../MCPToolHelpers.h"
+#include <algorithm>
+
+namespace DBModels
+{
+ namespace
+ {
+ std::wstring toLower(std::wstring s)
+ {
+ std::transform(s.begin(), s.end(), s.begin(), ::towlower);
+ return s;
+ }
+ bool containsCI(const std::wstring& hay, const std::wstring& needle)
+ {
+ return toLower(hay).find(toLower(needle)) != std::wstring::npos;
+ }
+ }
+
+ MCPToolResult SearchAcrossTablesTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ if (!params.contains("keyword") || !params["keyword"].is_string())
+ throw MCPToolError::invalidParameters("keyword is required");
+ const auto kwUtf8 = params["keyword"].get<std::string>();
+ const std::wstring kwW = MCPToolHelpers::fromUtf8(kwUtf8);
+
+ const std::wstring schemaW = (params.contains("schema") && params["schema"].is_string())
+ ? MCPToolHelpers::fromUtf8(params["schema"].get<std::string>()) : std::wstring{};
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+
+ nlohmann::json matches = nlohmann::json::array();
+ for (const auto& t : adapter->listTables(schemaW))
+ {
+ if (containsCI(t.name, kwW))
+ matches.push_back({
+ {"type", "table"},
+ {"table", MCPToolHelpers::toUtf8(t.name)},
+ {"match", MCPToolHelpers::toUtf8(t.name)}
+ });
+
+ if (!t.comment.empty() && containsCI(t.comment, kwW))
+ matches.push_back({
+ {"type", "table_comment"},
+ {"table", MCPToolHelpers::toUtf8(t.name)},
+ {"comment", MCPToolHelpers::toUtf8(t.comment)}
+ });
+
+ // describeTable can be slow per-table, but Tier-2 read
+ // sits behind a rate limiter — fine for exploration.
+ for (const auto& col : adapter->describeTable(t.name, schemaW))
+ {
+ if (containsCI(col.name, kwW))
+ matches.push_back({
+ {"type", "column"},
+ {"table", MCPToolHelpers::toUtf8(t.name)},
+ {"column", MCPToolHelpers::toUtf8(col.name)},
+ {"data_type", MCPToolHelpers::toUtf8(col.dataType)}
+ });
+ if (!col.comment.empty() && containsCI(col.comment, kwW))
+ matches.push_back({
+ {"type", "column_comment"},
+ {"table", MCPToolHelpers::toUtf8(t.name)},
+ {"column", MCPToolHelpers::toUtf8(col.name)},
+ {"comment", MCPToolHelpers::toUtf8(col.comment)}
+ });
+ }
+ }
+
+ if (matches.empty())
+ return MCPToolResult::text("No matches found for '" + kwUtf8 + "'.");
+
+ return MCPToolResult::text(
+ "Found " + std::to_string(matches.size()) +
+ " match(es) for '" + kwUtf8 + "':\n" + matches.dump(2));
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.h b/windows/Gridex/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.h
new file mode 100644
index 0000000..8e545ab
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier2/SearchAcrossTablesTool.h
@@ -0,0 +1,38 @@
+#pragma once
+//
+// SearchAcrossTablesTool.h — Keyword search over table names,
+// column names, and column comments in a connection. Mirrors
+// macOS SearchAcrossTablesTool.swift. Useful for the AI to
+// discover relevant data.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class SearchAcrossTablesTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "search_across_tables"; }
+ std::string description() const override
+ {
+ return "Search a keyword across table names, column names, "
+ "and column/table comments. Useful when the AI is "
+ "exploring an unfamiliar schema.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Read; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"keyword", {{"type", "string"}, {"description", "Keyword to search for"}}},
+ {"schema", {{"type", "string"}, {"description", "Optional schema filter"}}}
+ }},
+ {"required", {"connection_id", "keyword"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier3/DeleteRowsTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier3/DeleteRowsTool.cpp
new file mode 100644
index 0000000..0adc53d
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier3/DeleteRowsTool.cpp
@@ -0,0 +1,75 @@
+//
+// DeleteRowsTool.cpp
+//
+
+#include "DeleteRowsTool.h"
+#include "../MCPToolHelpers.h"
+#include "../../Security/MCPIdentifierValidator.h"
+#include "../../Security/MCPRowCountEstimator.h"
+
+namespace DBModels
+{
+ MCPToolResult DeleteRowsTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+ auto ts = MCPIdentifierValidator::extractTableAndSchema(params);
+
+ if (!params.contains("where") || !params["where"].is_string())
+ throw MCPToolError::invalidParameters(
+ "where is required. Bare DELETE without WHERE is not allowed.");
+ const auto whereUtf8 = params["where"].get<std::string>();
+
+ {
+ const auto v = ctx.permissionEngine.validateWhereClause(whereUtf8);
+ if (const auto* msg = v.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+ }
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+ const std::wstring tableW = MCPToolHelpers::fromUtf8(ts.table);
+ const std::wstring schemaW = ts.schema.has_value()
+ ? MCPToolHelpers::fromUtf8(*ts.schema) : std::wstring{};
+ const std::wstring whereW = MCPToolHelpers::fromUtf8(whereUtf8);
+
+ std::wstring qTable;
+ try
+ {
+ qTable = (schemaW.empty())
+ ? adapter->quoteSqlIdentifier(tableW)
+ : adapter->quoteSqlIdentifier(schemaW) + L"." + adapter->quoteSqlIdentifier(tableW);
+ }
+ catch (...) { qTable = tableW; }
+
+ const std::wstring sql = L"DELETE FROM " + qTable + L" WHERE " + whereW;
+
+ if (perm.requiresUserApproval())
+ {
+ const int est = MCPRowCountEstimator::estimate(
+ adapter, qTable, whereW, config);
+ const std::wstring details =
+ L"SQL:\n" + sql +
+ L"\n\nEstimated rows to delete: " + std::to_wstring(est) +
+ L"\n\n⚠ This operation cannot be undone!";
+ const auto clientW = MCPToolHelpers::fromUtf8(
+ ctx.client.name.empty() ? std::string{"AI client"} : ctx.client.name);
+ const bool ok = ctx.requestApproval(
+ MCPToolHelpers::fromUtf8(this->name()),
+ L"Delete rows from '" + tableW + L"' where " + whereW,
+ details, connId, clientW);
+ if (!ok) throw MCPToolError::permissionDenied("User denied the operation.");
+ }
+
+ QueryResult r;
+ try { r = adapter->execute(sql); }
+ catch (const std::exception& e)
+ { throw MCPToolError::queryFailed(e.what()); }
+ if (!r.success) throw MCPToolError::queryFailed(MCPToolHelpers::toUtf8(r.error));
+
+ return MCPToolResult::text(
+ "Deleted " + std::to_string(r.totalRows) + " row(s) from '" + ts.table + "'.");
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier3/DeleteRowsTool.h b/windows/Gridex/Services/MCP/Tools/Tier3/DeleteRowsTool.h
new file mode 100644
index 0000000..2004142
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier3/DeleteRowsTool.h
@@ -0,0 +1,38 @@
+#pragma once
+//
+// DeleteRowsTool.h — DELETE rows matching a WHERE clause.
+// Requires approval (Tier 3). WHERE is mandatory — bare DELETE
+// is always rejected. Mirrors macOS DeleteRowsTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class DeleteRowsTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "delete_rows"; }
+ std::string description() const override
+ {
+ return "Delete rows matching a WHERE clause. Requires user "
+ "approval. WHERE is MANDATORY.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Write; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"table_name", {{"type", "string"}, {"description", "Table to delete from"}}},
+ {"schema", {{"type", "string"}, {"description", "Optional schema"}}},
+ {"where", {{"type", "string"},
+ {"description", "WHERE clause (required). Must not contain ';', '--', '/*', '*/'."}}}
+ }},
+ {"required", {"connection_id", "table_name", "where"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.cpp
new file mode 100644
index 0000000..0e955bf
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.cpp
@@ -0,0 +1,117 @@
+//
+// ExecuteWriteQueryTool.cpp
+//
+
+#include "ExecuteWriteQueryTool.h"
+#include "../MCPToolHelpers.h"
+#include "../../Security/MCPSQLSanitizer.h"
+#include <algorithm>
+#include <regex>
+
+namespace DBModels
+{
+ namespace
+ {
+ std::string trim(const std::string& s)
+ {
+ size_t a = 0, b = s.size();
+ while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;
+ while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;
+ return s.substr(a, b - a);
+ }
+ std::string upper(std::string s)
+ {
+ std::transform(s.begin(), s.end(), s.begin(),
+ [](unsigned char c){ return static_cast<char>(std::toupper(c)); });
+ return s;
+ }
+ bool startsWith(const std::string& s, const std::string& prefix)
+ {
+ return s.size() >= prefix.size() &&
+ std::equal(prefix.begin(), prefix.end(), s.begin());
+ }
+ }
+
+ MCPToolResult ExecuteWriteQueryTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+
+ if (!params.contains("sql") || !params["sql"].is_string())
+ throw MCPToolError::invalidParameters("sql is required");
+ const auto sqlUtf8 = params["sql"].get<std::string>();
+
+ // Sanitize + multi-statement guard. Run syntactic checks
+ // against a comment/literal-stripped copy so payloads
+ // hidden inside comments or strings cannot fool them.
+ const std::string codeOnly = MCPSQLSanitizer::stripCommentsAndStrings(sqlUtf8);
+ const std::string trimmedUpper = upper(trim(codeOnly));
+
+ std::string withoutTrailingSemi = trimmedUpper;
+ if (!withoutTrailingSemi.empty() && withoutTrailingSemi.back() == ';')
+ {
+ withoutTrailingSemi.pop_back();
+ withoutTrailingSemi = trim(withoutTrailingSemi);
+ }
+ if (withoutTrailingSemi.find(';') != std::string::npos)
+ throw MCPToolError::invalidParameters(
+ "Multiple statements are not allowed. Send one statement at a time.");
+
+ if (startsWith(trimmedUpper, "SELECT") || startsWith(trimmedUpper, "WITH"))
+ throw MCPToolError::invalidParameters(
+ "Use the 'query' tool for SELECT / WITH statements. "
+ "execute_write_query is for write operations only.");
+
+ // UPDATE/DELETE must contain WHERE and the WHERE clause
+ // must pass the permission-engine guard (no `;`, no
+ // comments, no trivial `1=1`).
+ if (startsWith(trimmedUpper, "UPDATE") || startsWith(trimmedUpper, "DELETE"))
+ {
+ static const std::regex whereRe(R"(\bWHERE\b)", std::regex::icase);
+ if (!std::regex_search(trimmedUpper, whereRe))
+ throw MCPToolError::permissionDenied(
+ "UPDATE/DELETE without WHERE clause is not allowed.");
+
+ // Extract the WHERE tail from the sanitized SQL to feed
+ // the WHERE validator. Case-insensitive search in the
+ // sanitized text, slice everything after it.
+ std::smatch m;
+ if (std::regex_search(codeOnly, m, whereRe))
+ {
+ const auto whereTail = trim(std::string(
+ m.suffix().first, m.suffix().second));
+ const auto v = ctx.permissionEngine.validateWhereClause(whereTail);
+ if (const auto* msg = v.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+ }
+ }
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto [adapter, _] = ctx.getAdapter(connId);
+
+ if (perm.requiresUserApproval())
+ {
+ const auto clientW = MCPToolHelpers::fromUtf8(
+ ctx.client.name.empty() ? std::string{"AI client"} : ctx.client.name);
+ const std::wstring details = L"SQL:\n" + MCPToolHelpers::fromUtf8(sqlUtf8);
+ const bool ok = ctx.requestApproval(
+ MCPToolHelpers::fromUtf8(this->name()),
+ L"Execute write query",
+ details, connId, clientW);
+ if (!ok) throw MCPToolError::permissionDenied("User denied the operation.");
+ }
+
+ QueryResult r;
+ try { r = adapter->execute(MCPToolHelpers::fromUtf8(sqlUtf8)); }
+ catch (const std::exception& e)
+ { throw MCPToolError::queryFailed(e.what()); }
+ if (!r.success) throw MCPToolError::queryFailed(MCPToolHelpers::toUtf8(r.error));
+
+ std::string resp = "Query executed successfully.";
+ if (r.totalRows > 0)
+ resp += " " + std::to_string(r.totalRows) + " row(s) affected.";
+ return MCPToolResult::text(resp);
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.h b/windows/Gridex/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.h
new file mode 100644
index 0000000..16b3ed5
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier3/ExecuteWriteQueryTool.h
@@ -0,0 +1,37 @@
+#pragma once
+//
+// ExecuteWriteQueryTool.h — Run one arbitrary write SQL statement
+// (INSERT / UPDATE / DELETE). Requires approval. Multi-statement
+// input is rejected; SELECT / WITH are redirected at the query
+// tool. Mirrors macOS ExecuteWriteQueryTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class ExecuteWriteQueryTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "execute_write_query"; }
+ std::string description() const override
+ {
+ return "Execute one write SQL statement (INSERT/UPDATE/DELETE). "
+ "Requires user approval. Multi-statement input is rejected; "
+ "use the 'query' tool for SELECT / WITH.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Write; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"sql", {{"type", "string"}, {"description", "A single write SQL statement"}}}
+ }},
+ {"required", {"connection_id", "sql"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier3/InsertRowsTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier3/InsertRowsTool.cpp
new file mode 100644
index 0000000..ccda000
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier3/InsertRowsTool.cpp
@@ -0,0 +1,107 @@
+//
+// InsertRowsTool.cpp
+//
+
+#include "InsertRowsTool.h"
+#include "../MCPToolHelpers.h"
+#include "../../Security/MCPIdentifierValidator.h"
+
+namespace DBModels
+{
+ namespace
+ {
+ // Convert a JSON value to the wstring form expected by
+ // TableRow. Nulls become the SQL-NULL sentinel so the
+ // adapter emits `DEFAULT` / `NULL` rather than the literal
+ // string "null".
+ std::wstring jsonToCell(const nlohmann::json& v)
+ {
+ if (v.is_null()) return nullValue();
+ if (v.is_boolean()) return v.get<bool>() ? L"true" : L"false";
+ if (v.is_number_integer()) return std::to_wstring(v.get<int64_t>());
+ if (v.is_number_float()) return std::to_wstring(v.get<double>());
+ if (v.is_string()) return MCPToolHelpers::fromUtf8(v.get<std::string>());
+ // Array/object — serialize to JSON text and let the adapter
+ // store it as-is (useful for Postgres json/jsonb columns).
+ return MCPToolHelpers::fromUtf8(v.dump());
+ }
+
+ std::string clientNameFromContext(const MCPToolContext& ctx)
+ {
+ return ctx.client.name.empty() ? std::string{"AI client"} : ctx.client.name;
+ }
+ }
+
+ MCPToolResult InsertRowsTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+ auto ts = MCPIdentifierValidator::extractTableAndSchema(params);
+
+ if (!params.contains("rows") || !params["rows"].is_array() || params["rows"].empty())
+ throw MCPToolError::invalidParameters("rows must be a non-empty array");
+
+ const auto& rowsJson = params["rows"];
+
+ // Permission + approval (Tier 3 always requires approval in RW mode).
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ if (perm.requiresUserApproval())
+ {
+ // Preview first 3 rows for the dialog body.
+ std::wstring preview;
+ const int previewCap = (std::min<int>)(3, static_cast<int>(rowsJson.size()));
+ for (int i = 0; i < previewCap; ++i)
+ {
+ preview += L" " + MCPToolHelpers::fromUtf8(rowsJson[i].dump()) + L"\n";
+ }
+ if (static_cast<int>(rowsJson.size()) > previewCap)
+ preview += L" … and " +
+ std::to_wstring(rowsJson.size() - previewCap) + L" more\n";
+
+ const std::wstring tableW = MCPToolHelpers::fromUtf8(ts.table);
+ const std::wstring desc =
+ L"Insert " + std::to_wstring(rowsJson.size()) +
+ L" row(s) into '" + tableW + L"'";
+ const std::wstring details = L"Preview:\n" + preview;
+
+ const auto clientW = MCPToolHelpers::fromUtf8(clientNameFromContext(ctx));
+ const bool ok = ctx.requestApproval(
+ MCPToolHelpers::fromUtf8(this->name()),
+ desc, details, connId, clientW);
+ if (!ok) throw MCPToolError::permissionDenied("User denied the operation.");
+ }
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+ const std::wstring tableW = MCPToolHelpers::fromUtf8(ts.table);
+ const std::wstring schemaW = ts.schema.has_value()
+ ? MCPToolHelpers::fromUtf8(*ts.schema) : std::wstring{};
+
+ int inserted = 0;
+ for (const auto& rowJson : rowsJson)
+ {
+ if (!rowJson.is_object()) continue;
+ TableRow row;
+ for (auto it = rowJson.begin(); it != rowJson.end(); ++it)
+ {
+ const std::wstring key = MCPToolHelpers::fromUtf8(it.key());
+ row[key] = jsonToCell(it.value());
+ }
+ try
+ {
+ auto r = adapter->insertRow(tableW, schemaW, row);
+ if (r.success) ++inserted;
+ else
+ throw MCPToolError::queryFailed(MCPToolHelpers::toUtf8(r.error));
+ }
+ catch (const std::exception& e)
+ {
+ throw MCPToolError::queryFailed(e.what());
+ }
+ }
+
+ return MCPToolResult::text(
+ "Inserted " + std::to_string(inserted) + " row(s) into '" + ts.table + "'.");
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier3/InsertRowsTool.h b/windows/Gridex/Services/MCP/Tools/Tier3/InsertRowsTool.h
new file mode 100644
index 0000000..bf84343
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier3/InsertRowsTool.h
@@ -0,0 +1,38 @@
+#pragma once
+//
+// InsertRowsTool.h — Insert one or more rows into a table.
+// Requires approval (Tier 3). Mirrors macOS InsertRowsTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class InsertRowsTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "insert_rows"; }
+ std::string description() const override
+ {
+ return "Insert one or more rows into a table. Requires user "
+ "approval (Tier 3). Returns the number of rows inserted.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Write; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"table_name", {{"type", "string"}, {"description", "Table to insert into"}}},
+ {"schema", {{"type", "string"}, {"description", "Optional schema"}}},
+ {"rows", {{"type", "array"},
+ {"description", "Array of row objects (column -> value)"},
+ {"items", {{"type", "object"}}}}}
+ }},
+ {"required", {"connection_id", "table_name", "rows"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier3/UpdateRowsTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier3/UpdateRowsTool.cpp
new file mode 100644
index 0000000..2339b73
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier3/UpdateRowsTool.cpp
@@ -0,0 +1,129 @@
+//
+// UpdateRowsTool.cpp
+//
+
+#include "UpdateRowsTool.h"
+#include "../MCPToolHelpers.h"
+#include "../../Security/MCPIdentifierValidator.h"
+#include "../../Security/MCPRowCountEstimator.h"
+
+namespace DBModels
+{
+ namespace
+ {
+ // Format a JSON value for direct SQL embedding in the SET
+ // clause. Uses the adapter's quoteSqlLiteral for strings so
+ // dialect-specific escaping (e.g. Postgres E-strings) is
+ // respected. Booleans emit `true/false` for Postgres and
+ // `1/0` everywhere else.
+ std::wstring formatValue(const nlohmann::json& v,
+ const std::shared_ptr<DatabaseAdapter>& adapter,
+ DatabaseType dbType)
+ {
+ if (v.is_null()) return L"NULL";
+ if (v.is_boolean())
+ {
+ const bool b = v.get<bool>();
+ return (dbType == DatabaseType::PostgreSQL)
+ ? (b ? L"true" : L"false")
+ : (b ? L"1" : L"0");
+ }
+ if (v.is_number_integer()) return std::to_wstring(v.get<int64_t>());
+ if (v.is_number_float()) return std::to_wstring(v.get<double>());
+ const std::wstring s = v.is_string()
+ ? MCPToolHelpers::fromUtf8(v.get<std::string>())
+ : MCPToolHelpers::fromUtf8(v.dump());
+ try { return adapter->quoteSqlLiteral(s); }
+ catch (...)
+ {
+ // Fallback — basic single-quote doubling.
+ std::wstring q = L"'";
+ for (wchar_t c : s) { if (c == L'\'') q += L"''"; else q += c; }
+ q += L"'";
+ return q;
+ }
+ }
+ }
+
+ MCPToolResult UpdateRowsTool::execute(const nlohmann::json& params, MCPToolContext& ctx)
+ {
+ const auto connId = MCPTool::extractConnectionId(params);
+ auto ts = MCPIdentifierValidator::extractTableAndSchema(params);
+
+ if (!params.contains("set") || !params["set"].is_object() || params["set"].empty())
+ throw MCPToolError::invalidParameters("set must be a non-empty object");
+ for (auto it = params["set"].begin(); it != params["set"].end(); ++it)
+ MCPIdentifierValidator::validate(it.key(), "column name");
+
+ if (!params.contains("where") || !params["where"].is_string())
+ throw MCPToolError::invalidParameters(
+ "where is required. Bare UPDATE without WHERE is not allowed.");
+ const auto whereUtf8 = params["where"].get<std::string>();
+
+ // WHERE-clause guard via permission engine.
+ {
+ const auto v = ctx.permissionEngine.validateWhereClause(whereUtf8);
+ if (const auto* msg = v.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+ }
+
+ const auto perm = ctx.checkPermission(tier(), connId);
+ if (const auto* msg = perm.errorMessage())
+ throw MCPToolError::permissionDenied(*msg);
+
+ auto [adapter, config] = ctx.getAdapter(connId);
+ const std::wstring tableW = MCPToolHelpers::fromUtf8(ts.table);
+ const std::wstring schemaW = ts.schema.has_value()
+ ? MCPToolHelpers::fromUtf8(*ts.schema) : std::wstring{};
+ const std::wstring whereW = MCPToolHelpers::fromUtf8(whereUtf8);
+
+ // Qualified table (dialect-aware via adapter's own quoter).
+ std::wstring qTable;
+ try
+ {
+ qTable = (schemaW.empty())
+ ? adapter->quoteSqlIdentifier(tableW)
+ : adapter->quoteSqlIdentifier(schemaW) + L"." + adapter->quoteSqlIdentifier(tableW);
+ }
+ catch (...) { qTable = tableW; /* fallback — most drivers accept bare */ }
+
+ // Build SET clause.
+ std::wstring setClause;
+ bool first = true;
+ for (auto it = params["set"].begin(); it != params["set"].end(); ++it)
+ {
+ if (!first) setClause += L", ";
+ first = false;
+ std::wstring col;
+ try { col = adapter->quoteSqlIdentifier(MCPToolHelpers::fromUtf8(it.key())); }
+ catch (...) { col = MCPToolHelpers::fromUtf8(it.key()); }
+ setClause += col + L" = " + formatValue(it.value(), adapter, config.databaseType);
+ }
+
+ const std::wstring sql = L"UPDATE " + qTable + L" SET " + setClause + L" WHERE " + whereW;
+
+ if (perm.requiresUserApproval())
+ {
+ const int est = MCPRowCountEstimator::estimate(
+ adapter, qTable, whereW, config);
+ const std::wstring details =
+ L"SQL:\n" + sql + L"\n\nEstimated rows affected: " + std::to_wstring(est);
+ const auto clientW = MCPToolHelpers::fromUtf8(
+ ctx.client.name.empty() ? std::string{"AI client"} : ctx.client.name);
+ const bool ok = ctx.requestApproval(
+ MCPToolHelpers::fromUtf8(this->name()),
+ L"Update rows in '" + tableW + L"' where " + whereW,
+ details, connId, clientW);
+ if (!ok) throw MCPToolError::permissionDenied("User denied the operation.");
+ }
+
+ QueryResult r;
+ try { r = adapter->execute(sql); }
+ catch (const std::exception& e)
+ { throw MCPToolError::queryFailed(e.what()); }
+ if (!r.success) throw MCPToolError::queryFailed(MCPToolHelpers::toUtf8(r.error));
+
+ return MCPToolResult::text(
+ "Updated " + std::to_string(r.totalRows) + " row(s) in '" + ts.table + "'.");
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Tools/Tier3/UpdateRowsTool.h b/windows/Gridex/Services/MCP/Tools/Tier3/UpdateRowsTool.h
new file mode 100644
index 0000000..c880a53
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Tools/Tier3/UpdateRowsTool.h
@@ -0,0 +1,40 @@
+#pragma once
+//
+// UpdateRowsTool.h — UPDATE rows matching a WHERE clause.
+// Requires approval (Tier 3). WHERE is mandatory — bare UPDATE
+// is always rejected. Mirrors macOS UpdateRowsTool.swift.
+
+#include "../MCPTool.h"
+
+namespace DBModels
+{
+ class UpdateRowsTool : public MCPTool
+ {
+ public:
+ std::string name() const override { return "update_rows"; }
+ std::string description() const override
+ {
+ return "Update rows matching a WHERE clause. Requires user "
+ "approval. WHERE is MANDATORY — bare UPDATE is rejected.";
+ }
+ MCPPermissionTier tier() const override { return MCPPermissionTier::Write; }
+ nlohmann::json inputSchema() const override
+ {
+ return {
+ {"type", "object"},
+ {"properties", {
+ {"connection_id", {{"type", "string"}, {"description", "Connection identifier"}}},
+ {"table_name", {{"type", "string"}, {"description", "Table to update"}}},
+ {"schema", {{"type", "string"}, {"description", "Optional schema"}}},
+ {"set", {{"type", "object"},
+ {"description", "Column -> value pairs to update"}}},
+ {"where", {{"type", "string"},
+ {"description", "WHERE clause (required). Must not contain ';', '--', '/*', '*/'."}}}
+ }},
+ {"required", {"connection_id", "table_name", "set", "where"}}
+ };
+ }
+ MCPToolResult execute(const nlohmann::json& params,
+ MCPToolContext& ctx) override;
+ };
+}
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
new file mode 100644
index 0000000..38aed48
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Transport/StdioTransport.cpp
@@ -0,0 +1,191 @@
+//
+// StdioTransport.cpp
+//
+// 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. 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"
+
+#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.
+// Flipped on while Claude Desktop integration is stabilizing —
+// the log at %APPDATA%\Gridex\mcp-stdio-debug.log is the only
+// thing we have for post-mortem diagnosis of stdio crashes.
+static constexpr bool kDebug = true;
+
+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();
+ if (reader_.joinable()) reader_.join();
+ }
+
+ void StdioTransport::start()
+ {
+ if (running_.exchange(true)) return;
+ reader_ = std::thread([this]() { readLoop(); });
+ }
+
+ void StdioTransport::stop()
+ {
+ running_.store(false);
+ }
+
+ 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())
+ {
+ line.clear();
+ if (!readLine(in, line))
+ { dbg("readLoop: EOF"); break; }
+ if (line.empty()) continue;
+ 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& e)
+ {
+ dbg(std::string("readLoop parse/handler std::exception: ") + e.what());
+ try
+ {
+ auto resp = JSONRPCResponse::fail(nullptr, JSONRPCError::parseError());
+ send(resp);
+ } catch (...) {}
+ }
+ catch (...)
+ {
+ // SEH or non-std exception — catch-all so reader
+ // thread can never call std::terminate (which Debug
+ // CRT shows as abort() + popup).
+ dbg("readLoop unknown exception, sending internalError");
+ try
+ {
+ auto resp = JSONRPCResponse::fail(
+ nullptr, JSONRPCError::internalError());
+ send(resp);
+ } catch (...) {}
+ }
+ }
+ running_.store(false);
+ }
+
+ void StdioTransport::send(const JSONRPCResponse& response)
+ {
+ nlohmann::json j;
+ to_json(j, response);
+ const std::string line = j.dump() + "\n";
+
+ std::lock_guard<std::mutex> lk(writeMtx_);
+ 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,
+ const nlohmann::json& params)
+ {
+ JSONRPCRequest notif;
+ notif.method = method;
+ notif.params = params;
+ nlohmann::json j;
+ to_json(j, notif);
+ const std::string line = j.dump() + "\n";
+
+ std::lock_guard<std::mutex> lk(writeMtx_);
+ HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
+ if (out == INVALID_HANDLE_VALUE || out == nullptr) return;
+ writeAll(out, line);
+ }
+}
diff --git a/windows/Gridex/Services/MCP/Transport/StdioTransport.h b/windows/Gridex/Services/MCP/Transport/StdioTransport.h
new file mode 100644
index 0000000..1398c0a
--- /dev/null
+++ b/windows/Gridex/Services/MCP/Transport/StdioTransport.h
@@ -0,0 +1,59 @@
+#pragma once
+//
+// StdioTransport.h
+// Gridex
+//
+// Newline-delimited JSON-RPC over stdin/stdout for the
+// `--mcp-stdio` CLI mode. One request per line. Mirrors
+// macos/Services/MCP/Transport/StdioTransport.swift.
+//
+// Reads on a dedicated background thread and dispatches parsed
+// requests via a callback. Writes are serialized on a separate
+// mutex — call send() from any thread.
+
+#include <string>
+#include <atomic>
+#include <thread>
+#include <mutex>
+#include <functional>
+#include "../../../Models/MCP/MCPProtocol.h"
+
+namespace DBModels
+{
+ class StdioTransport
+ {
+ public:
+ // Callback invoked for each valid JSON-RPC request. Runs on
+ // the reader thread; the implementation is expected to
+ // handle its own synchronization (or dispatch to a worker).
+ using RequestHandler = std::function<void(const JSONRPCRequest&)>;
+
+ StdioTransport() = default;
+ ~StdioTransport();
+
+ void setRequestHandler(RequestHandler h) { handler_ = std::move(h); }
+
+ // Starts the reader thread. Returns immediately.
+ void start();
+
+ // Signals the reader to stop. The process exits naturally
+ // when stdin closes (EOF) so this is mainly for shutdown.
+ void stop();
+
+ // Thread-safe. Writes one JSON-RPC response + trailing
+ // newline to stdout and flushes.
+ void send(const JSONRPCResponse& response);
+
+ // Push a JSON-RPC notification (id=null) — e.g. progress.
+ void sendNotification(const std::string& method,
+ const nlohmann::json& params);
+
+ private:
+ std::atomic<bool> running_{false};
+ std::thread reader_;
+ std::mutex writeMtx_;
+ RequestHandler handler_;
+
+ void readLoop();
+ };
+}
diff --git a/windows/Gridex/Services/TrayIconService.cpp b/windows/Gridex/Services/TrayIconService.cpp
new file mode 100644
index 0000000..b34d901
--- /dev/null
+++ b/windows/Gridex/Services/TrayIconService.cpp
@@ -0,0 +1,184 @@
+//
+// TrayIconService.cpp
+//
+// Subclasses MainHwnd so Shell_NotifyIcon callbacks land in the
+// existing message loop. Hooks WM_APP+1 (tray notify),
+// WM_COMMAND (menu), WM_CLOSE (divert to hide instead of quit).
+
+#include "TrayIconService.h"
+#include "MCP/MCPServerHost.h"
+#include "../Models/AppSettings.h"
+#include <commctrl.h>
+#include <shellapi.h>
+#include <string>
+#include <mutex>
+#include <chrono>
+#pragma comment(lib, "Comctl32.lib")
+
+namespace DBModels { namespace TrayIconService {
+
+namespace {
+ constexpr UINT kTrayMessage = WM_APP + 1;
+ constexpr UINT_PTR kSubclassId = 1;
+
+ constexpr UINT kMenuOpen = 40001;
+ constexpr UINT kMenuToggle= 40002;
+ constexpr UINT kMenuQuit = 40003;
+
+ std::mutex g_mtx;
+ bool g_installed = false;
+ HWND g_hwnd = nullptr;
+ NOTIFYICONDATAW g_nid{};
+
+ HICON loadAppIcon()
+ {
+ // Same icon as the taskbar — the EXE's first resource.
+ HICON h = LoadIconW(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(1));
+ if (!h) h = LoadIconW(nullptr, IDI_APPLICATION);
+ return h;
+ }
+
+ std::wstring tooltip()
+ {
+ const bool running = []{
+ auto srv = MCPServerHost::instance();
+ return srv && srv->isRunning();
+ }();
+ return running
+ ? L"Gridex — MCP Server running"
+ : L"Gridex — MCP Server stopped";
+ }
+
+ void showMenu(HWND hwnd)
+ {
+ HMENU m = CreatePopupMenu();
+ if (!m) return;
+ AppendMenuW(m, MF_STRING, kMenuOpen, L"Open Gridex");
+ AppendMenuW(m, MF_SEPARATOR, 0, nullptr);
+
+ const bool running = []{
+ auto srv = MCPServerHost::instance();
+ return srv && srv->isRunning();
+ }();
+ AppendMenuW(m, MF_STRING, kMenuToggle,
+ running ? L"Stop MCP Server" : L"Start MCP Server");
+
+ AppendMenuW(m, MF_SEPARATOR, 0, nullptr);
+ AppendMenuW(m, MF_STRING, kMenuQuit, L"Quit Gridex");
+
+ POINT pt; GetCursorPos(&pt);
+ // Required so the menu dismisses when clicking elsewhere.
+ SetForegroundWindow(hwnd);
+ TrackPopupMenu(m, TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, nullptr);
+ DestroyMenu(m);
+ }
+
+ LRESULT CALLBACK Proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp,
+ UINT_PTR /*id*/, DWORD_PTR /*ref*/)
+ {
+ if (msg == kTrayMessage)
+ {
+ const UINT ev = LOWORD(lp);
+ if (ev == WM_LBUTTONDBLCLK || ev == WM_LBUTTONUP)
+ {
+ ShowWindow(hwnd, SW_SHOW);
+ SetForegroundWindow(hwnd);
+ return 0;
+ }
+ if (ev == WM_RBUTTONUP || ev == WM_CONTEXTMENU)
+ {
+ showMenu(hwnd);
+ return 0;
+ }
+ }
+ else if (msg == WM_COMMAND && HIWORD(wp) == 0)
+ {
+ const UINT id = LOWORD(wp);
+ if (id == kMenuOpen)
+ {
+ ShowWindow(hwnd, SW_SHOW);
+ SetForegroundWindow(hwnd);
+ return 0;
+ }
+ if (id == kMenuToggle)
+ {
+ auto srv = MCPServerHost::instance();
+ auto s = AppSettings::Load();
+ if (srv && srv->isRunning())
+ {
+ MCPServerHost::stop();
+ s.mcpEnabled = false;
+ s.mcpStartTime = 0;
+ }
+ else
+ {
+ // GUI mode — HttpOnly; mirrors MCPPage::StartStop.
+ std::wstring w(L"dev");
+ std::string ver;
+ for (wchar_t c : w) ver.push_back(static_cast<char>(c & 0x7F));
+ MCPServerHost::ensureCreated(s, ver, MCPTransportMode::HttpOnly);
+ MCPServerHost::start();
+ s.mcpEnabled = true;
+ s.mcpStartTime = static_cast<int64_t>(
+ std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch()).count());
+ }
+ s.Save();
+ Refresh();
+ return 0;
+ }
+ if (id == kMenuQuit)
+ {
+ MCPServerHost::stop();
+ PostQuitMessage(0);
+ ExitProcess(0);
+ return 0;
+ }
+ }
+ return DefSubclassProc(hwnd, msg, wp, lp);
+ }
+}
+
+void Initialize(HWND mainHwnd)
+{
+ std::lock_guard<std::mutex> lk(g_mtx);
+ if (g_installed || !mainHwnd) return;
+ g_hwnd = mainHwnd;
+
+ SetWindowSubclass(mainHwnd, Proc, 1, 0);
+
+ g_nid = {};
+ g_nid.cbSize = sizeof(g_nid);
+ g_nid.hWnd = mainHwnd;
+ g_nid.uID = 1;
+ g_nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
+ g_nid.uCallbackMessage = kTrayMessage;
+ g_nid.hIcon = loadAppIcon();
+ const auto tip = tooltip();
+ wcsncpy_s(g_nid.szTip, tip.c_str(), _TRUNCATE);
+
+ Shell_NotifyIconW(NIM_ADD, &g_nid);
+ g_installed = true;
+}
+
+void Shutdown()
+{
+ std::lock_guard<std::mutex> lk(g_mtx);
+ if (!g_installed) return;
+ Shell_NotifyIconW(NIM_DELETE, &g_nid);
+ if (g_hwnd) RemoveWindowSubclass(g_hwnd, Proc, 1);
+ g_installed = false;
+ g_hwnd = nullptr;
+}
+
+void Refresh()
+{
+ std::lock_guard<std::mutex> lk(g_mtx);
+ if (!g_installed) return;
+ const auto tip = tooltip();
+ wcsncpy_s(g_nid.szTip, tip.c_str(), _TRUNCATE);
+ g_nid.uFlags = NIF_TIP;
+ Shell_NotifyIconW(NIM_MODIFY, &g_nid);
+}
+
+}} // namespace
diff --git a/windows/Gridex/Services/TrayIconService.h b/windows/Gridex/Services/TrayIconService.h
new file mode 100644
index 0000000..5d55246
--- /dev/null
+++ b/windows/Gridex/Services/TrayIconService.h
@@ -0,0 +1,33 @@
+#pragma once
+//
+// TrayIconService.h
+// Gridex
+//
+// Lightweight Shell_NotifyIconW wrapper. Uses MainHwnd as the
+// message target (subclassed) so we don't need a second message
+// pump. Exposes the right-click menu (Open Gridex / Start-Stop
+// MCP / Quit) and tooltips reflecting current MCP state.
+//
+// Lifetime: TrayIconService::Initialize once after MainWindow is
+// activated, TrayIconService::Shutdown on process exit. Safe to
+// call repeatedly.
+
+#include <windows.h>
+#include <string>
+
+namespace DBModels
+{
+ namespace TrayIconService
+ {
+ // Install the icon; hooks MainHwnd's WndProc for tray
+ // callback + right-click menu. No-op if already installed.
+ void Initialize(HWND mainHwnd);
+
+ // Remove the icon + restore the original WndProc.
+ void Shutdown();
+
+ // Refresh tooltip + icon after server state changes.
+ // Called from MCPPage::StartStop_Click.
+ void Refresh();
+ }
+}
diff --git a/windows/Gridex/SidebarPanel.cpp b/windows/Gridex/SidebarPanel.cpp
index f5e0ba7..c84c742 100644
--- a/windows/Gridex/SidebarPanel.cpp
+++ b/windows/Gridex/SidebarPanel.cpp
@@ -446,14 +446,22 @@ namespace winrt::Gridex::implementation
{ if (OnImportTable) OnImportTable(exportName, exportSchema); });
contextMenu.Items().Append(importItem);
- // Delete Table — destructive. Only offered for real tables
- // (not views) since DROP VIEW needs a different code path.
- // Host shows a confirmation dialog before actually running
- // DROP TABLE.
+ // Truncate + Delete — destructive. Only offered for
+ // real tables (not views) since views can't be truncated
+ // and DROP VIEW needs a different code path. Host shows
+ // a confirmation dialog before running the statement.
if (item.type == DBModels::SidebarItemType::Table)
{
contextMenu.Items().Append(muxc::MenuFlyoutSeparator());
+ muxc::MenuFlyoutItem truncateItem;
+ truncateItem.Text(L"Truncate Table...");
+ truncateItem.Icon(muxc::FontIcon());
+ truncateItem.Icon().as<muxc::FontIcon>().Glyph(L"\xE74D"); // eraser-ish; trash is close enough
+ truncateItem.Click([this, exportName, exportSchema](auto&&, auto&&)
+ { if (OnTruncateTable) OnTruncateTable(exportName, exportSchema); });
+ contextMenu.Items().Append(truncateItem);
+
muxc::MenuFlyoutItem deleteItem;
deleteItem.Text(L"Delete Table...");
deleteItem.Icon(muxc::FontIcon());
diff --git a/windows/Gridex/SidebarPanel.h b/windows/Gridex/SidebarPanel.h
index b121214..7567ff7 100644
--- a/windows/Gridex/SidebarPanel.h
+++ b/windows/Gridex/SidebarPanel.h
@@ -28,6 +28,9 @@ namespace winrt::Gridex::implementation
// Callbacks for add/delete table buttons
std::function<void()> OnAddTable;
std::function<void(const std::wstring& tableName, const std::wstring& schema)> OnDeleteTable;
+ // Truncate — same signature as OnDeleteTable. Host confirms
+ // + emits TRUNCATE TABLE (or DELETE FROM on SQLite).
+ std::function<void(const std::wstring& tableName, const std::wstring& schema)> OnTruncateTable;
// Callback for export table (tableName, schema, format: "csv"/"json"/"sql")
std::function<void(const std::wstring& tableName, const std::wstring& schema,
diff --git a/windows/Gridex/WorkspacePage.cpp b/windows/Gridex/WorkspacePage.cpp
index db1ba7c..7c82e54 100644
--- a/windows/Gridex/WorkspacePage.cpp
+++ b/windows/Gridex/WorkspacePage.cpp
@@ -609,6 +609,106 @@ namespace winrt::Gridex::implementation
});
};
+ // Sidebar truncate table — confirm then TRUNCATE (DELETE on SQLite).
+ // Wipes all rows, keeps the schema. Identical confirmation UX to
+ // OnDeleteTable; only the SQL emitted differs, and the tab-close
+ // snapshot trick is skipped (the tab stays valid, it just shows
+ // zero rows after the refresh).
+ Sidebar().as<SidebarPanel>()->OnTruncateTable = [this](const std::wstring& tableName, const std::wstring& schema)
+ {
+ if (!connMgr_.isConnected() || tableName.empty()) return;
+
+ muxc::ContentDialog dlg;
+ dlg.Title(winrt::box_value(winrt::hstring(L"Truncate Table")));
+ dlg.Content(winrt::box_value(winrt::hstring(
+ L"Wipe all rows from \"" + (schema.empty() ? L"" : schema + L"\".\"") + tableName + L"\"?\n\n"
+ L"The schema stays; this is NOT reversible.")));
+ dlg.PrimaryButtonText(L"Truncate");
+ dlg.CloseButtonText(L"Cancel");
+ dlg.DefaultButton(muxc::ContentDialogButton::Close);
+ dlg.XamlRoot(this->XamlRoot());
+
+ auto op = dlg.ShowAsync();
+ op.Completed([this, tableName, schema](auto&& asyncOp, auto&&)
+ {
+ if (asyncOp.GetResults() != muxc::ContentDialogResult::Primary) return;
+ this->DispatcherQueue().TryEnqueue([this, tableName, schema]()
+ {
+ auto adapter = connMgr_.getActiveAdapter();
+ if (!adapter) return;
+ try
+ {
+ const auto dbType = state_.connection.databaseType;
+ // Quote identifiers per dialect (same pattern as
+ // the Drop handler below).
+ std::wstring qt, qs;
+ if (dbType == DBModels::DatabaseType::MySQL)
+ {
+ qt = L"`" + tableName + L"`";
+ if (!schema.empty()) qs = L"`" + schema + L"`.";
+ }
+ else if (dbType == DBModels::DatabaseType::SQLite)
+ {
+ qt = L"\"" + tableName + L"\""; // no schemas
+ }
+ else // Postgres / MSSQL / anything SQL-ish
+ {
+ qt = L"\"" + tableName + L"\"";
+ if (!schema.empty()) qs = L"\"" + schema + L"\".";
+ }
+
+ // SQLite has no TRUNCATE — bare DELETE is the
+ // documented equivalent and the engine runs it
+ // with the fast "truncate optimization" when the
+ // table has no FK dependencies.
+ std::wstring sql = (dbType == DBModels::DatabaseType::SQLite)
+ ? (L"DELETE FROM " + qt)
+ : (L"TRUNCATE TABLE " + qs + qt);
+
+ auto result = adapter->execute(sql);
+ LogQuery(result);
+ if (result.success)
+ {
+ LoadSidebarFromDB(); // refresh row counts
+ // If a DataGrid tab is open on this table,
+ // refetch so the grid reflects the wipe.
+ for (const auto& t : state_.tabs)
+ {
+ if (t.type == DBModels::TabType::DataGrid &&
+ t.tableName == tableName &&
+ t.schema == schema &&
+ t.id == state_.activeTabId)
+ {
+ SwitchContentView();
+ break;
+ }
+ }
+ }
+ else
+ {
+ muxc::ContentDialog errDlg;
+ errDlg.Title(winrt::box_value(winrt::hstring(L"Truncate Failed")));
+ errDlg.Content(winrt::box_value(winrt::hstring(result.error)));
+ errDlg.CloseButtonText(L"OK");
+ errDlg.XamlRoot(this->XamlRoot());
+ errDlg.ShowAsync();
+ }
+ }
+ catch (const std::exception& e)
+ {
+ muxc::ContentDialog errDlg;
+ errDlg.Title(winrt::box_value(winrt::hstring(L"Truncate Failed")));
+ errDlg.Content(winrt::box_value(winrt::hstring(
+ std::wstring(L"Unexpected error: ") + std::wstring(
+ std::string(e.what()).begin(), std::string(e.what()).end()))));
+ errDlg.CloseButtonText(L"OK");
+ errDlg.XamlRoot(this->XamlRoot());
+ errDlg.ShowAsync();
+ }
+ });
+ });
+ };
+
// Sidebar delete table — confirm then DROP
Sidebar().as<SidebarPanel>()->OnDeleteTable = [this](const std::wstring& tableName, const std::wstring& schema)
{
diff --git a/windows/README.md b/windows/README.md
index cb2971b..a0fe881 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -66,29 +66,29 @@ windows/scripts/
**Git Bash / MSYS2**:
```bash
cd /e/dev/be/vura
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.4"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.5"
```
**PowerShell (5.1 / 7+)**:
```powershell
cd E:\dev\be\vura
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.4"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.5"
```
**CMD**:
```cmd
cd /d E:\dev\be\vura
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.4"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.5"
```
Script sẽ:
1. Cài/update `vpk` global tool (skip nếu đã có)
-2. Build `Gridex.exe` unpackaged, stamp version `0.1.4` vào About section
-3. Pack thành `Setup.exe` qua Velopack với metadata version `0.1.4`
+2. Build `Gridex.exe` unpackaged, stamp version `0.1.5` vào About section
+3. Pack thành `Setup.exe` qua Velopack với metadata version `0.1.5`
**Output**: `windows/Releases/`
- `Gridex-stable-Setup.exe` — installer user-facing
-- `Gridex-0.1.4-stable-full.nupkg` — package Velopack
+- `Gridex-0.1.5-stable-full.nupkg` — package Velopack
- `releases.stable.json`, `RELEASES-stable` — feed manifests
- `Gridex-stable-Portable.zip` — bản portable
@@ -140,7 +140,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\install-vp
powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1
# Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1 -Version "0.1.4-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpackaged.ps1 -Version "0.1.5-test"
```
**PowerShell**:
@@ -149,7 +149,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-unpa
powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1
# Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.4-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.5-test"
```
**CMD**:
@@ -158,7 +158,7 @@ REM Dev build — About section hiện "0.0.0-dev"
powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1
REM Build với version cụ thể — About section hiện đúng string
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.4-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-unpackaged.ps1 -Version "0.1.5-test"
```
Chạy trực tiếp exe để test nhanh mà không cần cài installer:
@@ -177,17 +177,17 @@ Chạy trực tiếp exe để test nhanh mà không cần cài installer:
**Git Bash / MSYS2**:
```bash
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/pack-velopack.ps1 -Version "0.1.4-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/pack-velopack.ps1 -Version "0.1.5-test"
```
**PowerShell**:
```powershell
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.4-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.5-test"
```
**CMD**:
```cmd
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.4-test"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velopack.ps1 -Version "0.1.5-test"
```
**Lưu ý**: `-Version` truyền vào `pack-velopack.ps1` **phải khớp** với `-Version` truyền vào `build-unpackaged.ps1`, nếu không thì Velopack sẽ in một số, còn About section của app sẽ in số khác. Dùng `build-and-pack.ps1` ở trên để tránh trường hợp này.
@@ -196,10 +196,10 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\pack-velop
- `windows/Gridex/GridexVersion.h` — include unconditional file generated
- `windows/Gridex/GridexVersion.generated.h` — **auto-generated, gitignored**, do `build-unpackaged.ps1` ghi mỗi lần chạy
- - Có `-Version` → `#define GRIDEX_VERSION L"0.1.4"`
+ - Có `-Version` → `#define GRIDEX_VERSION L"0.1.5"`
- Không `-Version` → `#define GRIDEX_VERSION L"0.0.0-dev"`
- `windows/Gridex/SettingsPage.xaml.cpp` — đọc `GRIDEX_VERSION` và set vào `VersionText` text block
-- CI workflow `.github/workflows/windows-release.yml` tự parse version từ git tag (`v0.1.4` → `0.1.4`) và forward sang script
+- CI workflow `.github/workflows/windows-release.yml` tự parse version từ git tag (`v0.1.5` → `0.1.5`) và forward sang script
Build script chỉ rewrite `GridexVersion.generated.h` khi nội dung khác → không force recompile vô ích.
@@ -209,17 +209,17 @@ Mặc định Velopack dùng channel `stable`. Nếu muốn phát hành kênh ri
**Git Bash / MSYS2**:
```bash
-powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.4-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File ./windows/scripts/build-and-pack.ps1 -Version "0.1.5-beta.1" -Channel "beta"
```
**PowerShell**:
```powershell
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.4-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.5-beta.1" -Channel "beta"
```
**CMD**:
```cmd
-powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.4-beta.1" -Channel "beta"
+powershell -NoProfile -ExecutionPolicy Bypass -File .\windows\scripts\build-and-pack.ps1 -Version "0.1.5-beta.1" -Channel "beta"
```
Output sẽ là `Gridex-beta-Setup.exe` + `releases.beta.json` — auto-updater phân luồng theo channel.
@@ -253,7 +253,7 @@ Chưa cài đủ vcpkg deps. Xem section "Cài vcpkg deps" ở đầu file.
### Gridex.exe crash ngay khi khởi động với `MSVCP140.dll not found`
Máy thiếu VC++ 2015-2022 Redistributable. Script `build-unpackaged.ps1` tự copy CRT DLLs vào output folder → nếu vẫn lỗi thì check VS install path / logs script.
-### Setup.exe cài xong nhưng About hiện `0.0.0-dev` dù pack với `-Version 0.1.4`
+### Setup.exe cài xong nhưng About hiện `0.0.0-dev` dù pack với `-Version 0.1.5`
Dùng `build-and-pack.ps1` thay vì gọi `pack-velopack.ps1` trực tiếp. Trường hợp chạy `pack-velopack.ps1` với version khác version lúc build `Gridex.exe` → xóa `windows\Gridex\x64\Release\` rồi build lại đúng thứ tự.
### Lỗi `pwsh.exe exited with code 9009` trong vcpkg applocal step
@@ -288,8 +288,8 @@ del /q .\windows\Gridex\GridexVersion.generated.h
CI tự chạy khi push tag matching `v*.*.*`:
```bash
-git tag v0.1.4
-git push origin v0.1.4
+git tag v0.1.5
+git push origin v0.1.5
```
GitHub Actions workflow `windows-release.yml` sẽ tự build + pack + upload assets lên GitHub Release. Xem chi tiết ở `.github/workflows/windows-release.yml`.