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(mcp): Round 1B — 4 Tier-3 write tools with approval gate
DangHuynh71f043a3116f
diff --git a/windows/Gridex/Gridex.items.props b/windows/Gridex/Gridex.items.propsindex 9a2dc47..b357dc4 100644--- a/windows/Gridex/Gridex.items.props+++ b/windows/Gridex/Gridex.items.props@@ -59,6 +59,10 @@<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)Models\DatabaseAdapter.h" /><ClInclude Include="$(MSBuildThisFileDirectory)Models\ConnectionManager.h" />@@ -374,6 +378,18 @@<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>diff --git a/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.cpp b/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.cppindex 266c8a3..8e9dc61 100644--- a/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.cpp+++ b/windows/Gridex/Services/MCP/Tools/MCPBuiltinTools.cpp@@ -14,6 +14,10 @@#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 {@@ -32,7 +36,13 @@ void registerAll(MCPToolRegistry& r)r.registerTool(std::make_shared<ExplainQueryTool>());r.registerTool(std::make_shared<SearchAcrossTablesTool>());- // Tier 3 — write tools arrive in Round 1B.+ // 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>());}}} // namespacediff --git a/windows/Gridex/Services/MCP/Tools/Tier3/DeleteRowsTool.cpp b/windows/Gridex/Services/MCP/Tools/Tier3/DeleteRowsTool.cppnew file mode 100644index 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.hnew file mode 100644index 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.cppnew file mode 100644index 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.hnew file mode 100644index 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.cppnew file mode 100644index 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.hnew file mode 100644index 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.cppnew file mode 100644index 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.hnew file mode 100644index 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;+ };+}