Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

37.7 KB
Raw Blame
// PortfolioTools.cpp — Portfolio tab MCP tools
// Merges flat holdings (PortfolioHoldingsRepository) + full CRUD (PortfolioRepository)

#include "mcp/tools/PortfolioTools.h"

#include "core/logging/Logger.h"
#include "services/portfolio/PortfolioService.h"
#include "storage/repositories/PortfolioHoldingsRepository.h"
#include "storage/repositories/PortfolioRepository.h"

#include <QDate>
#include <QMetaObject>
#include <QThread>

#include <algorithm>

namespace fincept::mcp::tools {

namespace portfolio_tools_detail {

constexpr const char* kPortfolioToolsTag = "PortfolioTools";

/// Tool handlers run on a worker thread; PortfolioService lives on the GUI
/// thread. Run the mutation there and block until it has committed (and its
/// signals have refreshed the screen) — same pattern as ReportBuilderTools.
template <typename F>
void run_on_service_thread(F&& fn) {
    auto* svc = &services::PortfolioService::instance();
    if (QThread::currentThread() == svc->thread()) {
        fn();
        return;
    }
    QMetaObject::invokeMethod(svc, std::forward<F>(fn), Qt::BlockingQueuedConnection);
}

/// Run a service write on its thread, capturing its bool result and any
/// operation_failed() message it emits (over-sell, bad input, DB error).
template <typename F>
std::pair<bool, QString> run_service_write(F&& write) {
    bool ok = false;
    QString message;
    run_on_service_thread([&]() {
        auto& svc = services::PortfolioService::instance();
        auto conn = QObject::connect(&svc, &services::PortfolioService::operation_failed, &svc,
                                     [&message](const QString&, const QString& msg) { message = msg; });
        ok = write(svc);
        QObject::disconnect(conn);
    });
    return {ok, message};
}

bool valid_trade_date(const QString& date) {
    if (date.isEmpty())
        return true;
    const QDate d = QDate::fromString(date.left(10), Qt::ISODate);
    return d.isValid() && d <= QDate::currentDate();
}

} // namespace portfolio_tools_detail

namespace ptd = portfolio_tools_detail;
using ptd::kPortfolioToolsTag;

std::vector<ToolDef> get_portfolio_tools() {
    std::vector<ToolDef> tools;

    // ════════════════════════════════════════════════════════════════════
    // Holdings (flat quick-add list)
    // ════════════════════════════════════════════════════════════════════

    // ── get_holdings ───────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "get_holdings";
        t.description = "Get all active portfolio holdings (symbol, shares, avg cost).";
        t.category = "portfolio";
        t.handler = [](const QJsonObject&) -> ToolResult {
            auto result = PortfolioHoldingsRepository::instance().get_active();
            if (result.is_err())
                return ToolResult::fail("Failed to load holdings: " + QString::fromStdString(result.error()));

            QJsonArray arr;
            for (const auto& h : result.value()) {
                arr.append(QJsonObject{{"id", h.id},
                                       {"symbol", h.symbol},
                                       {"name", h.name},
                                       {"shares", h.shares},
                                       {"avg_cost", h.avg_cost},
                                       {"added_at", h.added_at},
                                       {"updated_at", h.updated_at}});
            }
            return ToolResult::ok_data(arr);
        };
        tools.push_back(std::move(t));
    }

    // ── add_holding ────────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "add_holding";
        t.description = "Add or increase a position in the portfolio holdings list.";
        t.category = "portfolio";
        t.is_destructive = true; // writes the user's holdings book (ordering matters between edits)
        t.input_schema.properties =
            QJsonObject{{"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol (e.g. AAPL)"}}},
                        {"shares", QJsonObject{{"type", "number"}, {"description", "Number of shares/units"}}},
                        {"avg_cost", QJsonObject{{"type", "number"}, {"description", "Average cost per share/unit"}}},
                        {"name", QJsonObject{{"type", "string"}, {"description", "Company/asset name (optional)"}}}};
        t.input_schema.required = {"symbol", "shares", "avg_cost"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString symbol = args["symbol"].toString().trimmed().toUpper();
            double shares = args["shares"].toDouble(0.0);
            double avg_cost = args["avg_cost"].toDouble(0.0);
            QString name = args["name"].toString();

            if (symbol.isEmpty() || shares <= 0 || avg_cost <= 0)
                return ToolResult::fail("Missing or invalid: symbol, shares (>0), avg_cost (>0)");

            auto r = PortfolioHoldingsRepository::instance().add(symbol, shares, avg_cost, name);
            if (r.is_err())
                return ToolResult::fail("Failed to add holding: " + QString::fromStdString(r.error()));

            LOG_INFO(kPortfolioToolsTag, QString("Added holding: %1 x%2 @ %3").arg(symbol).arg(shares).arg(avg_cost));
            return ToolResult::ok("Holding added", QJsonObject{{"id", static_cast<int>(r.value())},
                                                               {"symbol", symbol},
                                                               {"shares", shares},
                                                               {"avg_cost", avg_cost}});
        };
        tools.push_back(std::move(t));
    }

    // ── update_holding ─────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "update_holding";
        t.description = "Update shares and average cost for an existing holding by ID.";
        t.category = "portfolio";
        t.is_destructive = true; // overwrites the stored position
        t.input_schema.properties =
            QJsonObject{{"id", QJsonObject{{"type", "integer"}, {"description", "Holding ID"}}},
                        {"shares", QJsonObject{{"type", "number"}, {"description", "Updated share count"}}},
                        {"avg_cost", QJsonObject{{"type", "number"}, {"description", "Updated average cost"}}}};
        t.input_schema.required = {"id", "shares", "avg_cost"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            int id = args["id"].toInt(-1);
            double shares = args["shares"].toDouble(0.0);
            double avg_cost = args["avg_cost"].toDouble(0.0);

            if (id < 0 || shares <= 0 || avg_cost <= 0)
                return ToolResult::fail("Missing or invalid: id, shares (>0), avg_cost (>0)");

            auto r = PortfolioHoldingsRepository::instance().update(id, shares, avg_cost);
            if (r.is_err())
                return ToolResult::fail("Failed to update holding: " + QString::fromStdString(r.error()));

            return ToolResult::ok("Holding updated", QJsonObject{{"id", id}});
        };
        tools.push_back(std::move(t));
    }

    // ── remove_holding ─────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "remove_holding";
        t.description = "Remove a holding from the portfolio by ID.";
        t.category = "portfolio";
        t.is_destructive = true; // mutation tool — penalise on read-style queries
        t.input_schema.properties =
            QJsonObject{{"id", QJsonObject{{"type", "integer"}, {"description", "Holding ID"}}}};
        t.input_schema.required = {"id"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            int id = args["id"].toInt(-1);
            if (id < 0)
                return ToolResult::fail("Missing or invalid 'id'");

            auto r = PortfolioHoldingsRepository::instance().remove(id);
            if (r.is_err())
                return ToolResult::fail("Failed to remove holding: " + QString::fromStdString(r.error()));

            return ToolResult::ok("Holding removed", QJsonObject{{"id", id}});
        };
        tools.push_back(std::move(t));
    }

    // ════════════════════════════════════════════════════════════════════
    // Portfolio CRUD (named portfolios with assets, transactions, snapshots)
    // ════════════════════════════════════════════════════════════════════

    // ── list_portfolios ─────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "list_portfolios";
        t.description = "Show all my portfolios — lists every named investment portfolio I created to "
                        "track real holdings (not paper-trading accounts).";
        t.category = "portfolio";
        t.handler = [](const QJsonObject&) -> ToolResult {
            auto r = PortfolioRepository::instance().list_portfolios();
            if (r.is_err())
                return ToolResult::fail("Failed to list portfolios: " + QString::fromStdString(r.error()));

            QJsonArray arr;
            for (const auto& p : r.value()) {
                arr.append(QJsonObject{{"id", p.id},
                                       {"name", p.name},
                                       {"owner", p.owner},
                                       {"currency", p.currency},
                                       {"description", p.description},
                                       {"created_at", p.created_at},
                                       {"updated_at", p.updated_at}});
            }
            return ToolResult::ok_data(arr);
        };
        tools.push_back(std::move(t));
    }

    // ── get_portfolio ───────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "get_portfolio";
        t.description = "Get a single portfolio by ID.";
        t.category = "portfolio";
        t.input_schema.properties =
            QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};
        t.input_schema.required = {"portfolio_id"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString id = args["portfolio_id"].toString().trimmed();
            if (id.isEmpty())
                return ToolResult::fail("Missing 'portfolio_id'");

            auto r = PortfolioRepository::instance().get_portfolio(id);
            if (r.is_err())
                return ToolResult::fail("Portfolio not found: " + QString::fromStdString(r.error()));

            const auto& p = r.value();
            return ToolResult::ok_data(QJsonObject{{"id", p.id},
                                                   {"name", p.name},
                                                   {"owner", p.owner},
                                                   {"currency", p.currency},
                                                   {"description", p.description},
                                                   {"created_at", p.created_at},
                                                   {"updated_at", p.updated_at}});
        };
        tools.push_back(std::move(t));
    }

    // ── create_portfolio ────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "create_portfolio";
        t.description = "Create a new named investment portfolio.";
        t.category = "portfolio";
        t.is_destructive = true; // persistent write; add_portfolio_asset / add_transaction depend on it existing
        t.input_schema.properties =
            QJsonObject{{"name", QJsonObject{{"type", "string"}, {"description", "Portfolio name"}}},
                        {"owner", QJsonObject{{"type", "string"}, {"description", "Owner name"}}},
                        {"currency", QJsonObject{{"type", "string"}, {"description", "Currency code (default: USD)"}}},
                        {"description", QJsonObject{{"type", "string"}, {"description", "Optional description"}}}};
        t.input_schema.required = {"name", "owner"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString name = args["name"].toString().trimmed();
            QString owner = args["owner"].toString().trimmed();
            if (name.isEmpty() || owner.isEmpty())
                return ToolResult::fail("Missing 'name' or 'owner'");

            QString currency = args["currency"].toString("USD");
            QString description = args["description"].toString();

            auto r = PortfolioRepository::instance().create_portfolio(name, owner, currency, description);
            if (r.is_err())
                return ToolResult::fail("Failed to create portfolio: " + QString::fromStdString(r.error()));

            LOG_INFO(kPortfolioToolsTag, "Created portfolio: " + name);
            ptd::run_on_service_thread([]() { services::PortfolioService::instance().load_portfolios(); });
            return ToolResult::ok("Portfolio created",
                                  QJsonObject{{"id", r.value()}, {"name", name}, {"currency", currency}});
        };
        tools.push_back(std::move(t));
    }

    // ── delete_portfolio ────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "delete_portfolio";
        t.description = "Delete a portfolio and all its assets and transactions.";
        t.category = "portfolio";
        t.is_destructive = true; // mutation tool — penalise on read-style queries
        t.input_schema.properties =
            QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};
        t.input_schema.required = {"portfolio_id"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString id = args["portfolio_id"].toString().trimmed();
            if (id.isEmpty())
                return ToolResult::fail("Missing 'portfolio_id'");

            if (PortfolioRepository::instance().get_portfolio(id).is_err())
                return ToolResult::fail("Portfolio not found: " + id);
            // Through the service so its caches are dropped and the open screen refreshes.
            ptd::run_on_service_thread([id]() { services::PortfolioService::instance().delete_portfolio(id); });
            if (PortfolioRepository::instance().get_portfolio(id).is_ok())
                return ToolResult::fail("Failed to delete portfolio " + id);

            LOG_INFO(kPortfolioToolsTag, "Deleted portfolio: " + id);
            return ToolResult::ok("Portfolio deleted", QJsonObject{{"id", id}});
        };
        tools.push_back(std::move(t));
    }

    // ── get_portfolio_assets ────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "get_portfolio_assets";
        t.description = "Get all asset holdings for a named portfolio.";
        t.category = "portfolio";
        t.input_schema.properties =
            QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}}};
        t.input_schema.required = {"portfolio_id"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString id = args["portfolio_id"].toString().trimmed();
            if (id.isEmpty())
                return ToolResult::fail("Missing 'portfolio_id'");

            auto r = PortfolioRepository::instance().get_assets(id);
            if (r.is_err())
                return ToolResult::fail("Failed to load assets: " + QString::fromStdString(r.error()));

            QJsonArray arr;
            for (const auto& a : r.value()) {
                arr.append(QJsonObject{{"id", a.id},
                                       {"symbol", a.symbol},
                                       {"quantity", a.quantity},
                                       {"avg_buy_price", a.avg_buy_price},
                                       {"cost_basis", a.quantity * a.avg_buy_price},
                                       {"sector", a.sector},
                                       {"first_purchase_date", a.first_purchase_date},
                                       {"last_updated", a.last_updated}});
            }
            return ToolResult::ok_data(arr);
        };
        tools.push_back(std::move(t));
    }

    // ── add_portfolio_asset ─────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "add_portfolio_asset";
        t.description = "Buy an asset into a named portfolio: records a BUY in the ledger and updates the "
                        "position (weighted-average cost).";
        t.category = "portfolio";
        t.is_destructive = true; // upserts quantity / average price in the user's portfolio
        t.input_schema.properties = QJsonObject{
            {"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},
            {"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol (e.g. AAPL)"}}},
            {"quantity", QJsonObject{{"type", "number"}, {"description", "Number of shares/units"}}},
            {"price", QJsonObject{{"type", "number"}, {"description", "Purchase price per unit"}}},
            {"date", QJsonObject{{"type", "string"}, {"description", "Purchase date YYYY-MM-DD (optional)"}}}};
        t.input_schema.required = {"portfolio_id", "symbol", "quantity", "price"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString portfolio_id = args["portfolio_id"].toString().trimmed();
            QString symbol = args["symbol"].toString().trimmed().toUpper();
            double quantity = args["quantity"].toDouble(0.0);
            double price = args["price"].toDouble(0.0);
            QString date = args["date"].toString();

            if (portfolio_id.isEmpty() || symbol.isEmpty() || quantity <= 0 || price <= 0)
                return ToolResult::fail("Missing or invalid: portfolio_id, symbol, quantity (>0), price (>0)");
            if (!ptd::valid_trade_date(date))
                return ToolResult::fail("Invalid 'date': expected YYYY-MM-DD, not in the future");
            if (PortfolioRepository::instance().get_portfolio(portfolio_id).is_err())
                return ToolResult::fail("Portfolio not found: " + portfolio_id);

            // Through the service: the old path wrote the position WITHOUT a BUY
            // ledger row, so history replay, realised P&L and exports never saw it.
            const auto [ok, msg] = ptd::run_service_write([&](services::PortfolioService& svc) {
                return svc.add_asset(portfolio_id, symbol, quantity, price, date.left(10));
            });
            if (!ok)
                return ToolResult::fail(msg.isEmpty() ? QStringLiteral("Failed to add asset") : msg);

            LOG_INFO(kPortfolioToolsTag,
                     QString("Added asset %1 x%2 to portfolio %3").arg(symbol).arg(quantity).arg(portfolio_id));
            return ToolResult::ok("BUY recorded",
                                  QJsonObject{{"symbol", symbol}, {"quantity", quantity}, {"price", price}});
        };
        tools.push_back(std::move(t));
    }

    // ── remove_portfolio_asset ──────────────────────────────────────────
    {
        ToolDef t;
        t.name = "remove_portfolio_asset";
        t.description = "Delete a position from a named portfolio WITHOUT recording a sale (data correction). "
                        "To record an actual sale use sell_portfolio_asset.";
        t.category = "portfolio";
        t.is_destructive = true; // mutation tool — penalise on read-style queries
        t.input_schema.properties =
            QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},
                        {"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol to remove"}}}};
        t.input_schema.required = {"portfolio_id", "symbol"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString portfolio_id = args["portfolio_id"].toString().trimmed();
            QString symbol = args["symbol"].toString().trimmed().toUpper();
            if (portfolio_id.isEmpty() || symbol.isEmpty())
                return ToolResult::fail("Missing 'portfolio_id' or 'symbol'");

            auto r = PortfolioRepository::instance().remove_asset(portfolio_id, symbol);
            if (r.is_err())
                return ToolResult::fail("Failed to remove asset: " + QString::fromStdString(r.error()));
            ptd::run_on_service_thread(
                [portfolio_id]() { services::PortfolioService::instance().refresh_summary(portfolio_id); });

            return ToolResult::ok("Position removed (no SELL recorded)", QJsonObject{{"symbol", symbol}});
        };
        tools.push_back(std::move(t));
    }

    // ── sell_portfolio_asset ────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "sell_portfolio_asset";
        t.description = "Sell part or all of a position: records a SELL in the ledger and reduces the position. "
                        "Refused when the quantity exceeds what is held.";
        t.category = "portfolio";
        t.is_destructive = true;
        t.input_schema.properties = QJsonObject{
            {"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},
            {"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol held in the portfolio"}}},
            {"quantity", QJsonObject{{"type", "number"}, {"description", "Units to sell (<= units held)"}}},
            {"price", QJsonObject{{"type", "number"}, {"description", "Sale price per unit"}}},
            {"date", QJsonObject{{"type", "string"}, {"description", "Trade date YYYY-MM-DD (optional, default today)"}}}};
        t.input_schema.required = {"portfolio_id", "symbol", "quantity", "price"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            const QString portfolio_id = args["portfolio_id"].toString().trimmed();
            const QString symbol = args["symbol"].toString().trimmed().toUpper();
            const double quantity = args["quantity"].toDouble(0.0);
            const double price = args["price"].toDouble(0.0);
            const QString date = args["date"].toString().trimmed();
            if (portfolio_id.isEmpty() || symbol.isEmpty() || quantity <= 0 || price <= 0)
                return ToolResult::fail("Missing or invalid: portfolio_id, symbol, quantity (>0), price (>0)");
            if (!ptd::valid_trade_date(date))
                return ToolResult::fail("Invalid 'date': expected YYYY-MM-DD, not in the future");
            const auto [ok, msg] = ptd::run_service_write([&](services::PortfolioService& svc) {
                return svc.sell_asset(portfolio_id, symbol, quantity, price, date.left(10));
            });
            if (!ok)
                return ToolResult::fail(msg.isEmpty() ? QStringLiteral("Failed to record the sale") : msg);
            return ToolResult::ok("SELL recorded",
                                  QJsonObject{{"symbol", symbol}, {"quantity", quantity}, {"price", price}});
        };
        tools.push_back(std::move(t));
    }

    // ── get_transactions ────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "get_transactions";
        t.description = "Get transaction history for a portfolio.";
        t.category = "portfolio";
        t.input_schema.properties =
            QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},
                        {"limit", QJsonObject{{"type", "integer"},
                                              {"description", "Max rows, most recent first (default: 50, max 500)"},
                                              {"minimum", 1},
                                              {"maximum", 500}}}};
        t.input_schema.required = {"portfolio_id"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString id = args["portfolio_id"].toString().trimmed();
            if (id.isEmpty())
                return ToolResult::fail("Missing 'portfolio_id'");

            const int limit = std::clamp(args["limit"].toInt(50), 1, 500);
            // Ask for one row more than we will return: the extra row is the only way to
            // know the ledger continues, so a full page is never mistaken for "everything".
            auto r = PortfolioRepository::instance().get_transactions(id, limit + 1);
            if (r.is_err())
                return ToolResult::fail("Failed to load transactions: " + QString::fromStdString(r.error()));

            const bool more = r.value().size() > limit;
            QJsonArray arr;
            for (const auto& tx : r.value()) {
                if (arr.size() >= limit)
                    break;
                arr.append(QJsonObject{{"id", tx.id},
                                       {"symbol", tx.symbol},
                                       {"type", tx.transaction_type},
                                       {"quantity", tx.quantity},
                                       {"price", tx.price},
                                       {"total_value", tx.total_value},
                                       {"date", tx.transaction_date},
                                       {"notes", tx.notes},
                                       {"created_at", tx.created_at}});
            }
            if (more)
                return ToolResult::ok(QStringLiteral("Showing the %1 most recent transactions — older ones exist; "
                                                     "raise `limit` (max 500) to see more.")
                                          .arg(arr.size()),
                                      arr);
            return ToolResult::ok_data(arr);
        };
        tools.push_back(std::move(t));
    }

    // ── add_transaction ─────────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "add_transaction";
        t.description = "Record a transaction in a portfolio. BUY/SELL also update the position (a SELL above "
                        "the quantity held is refused); DIVIDEND records income (quantity = shares held, price = "
                        "amount per share). SPLIT is not supported.";
        t.category = "portfolio";
        t.is_destructive = true; // appends to the user's transaction ledger
        t.input_schema.properties =
            QJsonObject{{"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},
                        {"symbol", QJsonObject{{"type", "string"}, {"description", "Ticker symbol"}}},
                        {"type", QJsonObject{{"type", "string"}, {"description", "BUY, SELL or DIVIDEND"}}},
                        {"quantity", QJsonObject{{"type", "number"}, {"description", "Number of shares/units"}}},
                        {"price", QJsonObject{{"type", "number"}, {"description", "Price per unit"}}},
                        {"date", QJsonObject{{"type", "string"}, {"description", "Transaction date YYYY-MM-DD"}}},
                        {"notes", QJsonObject{{"type", "string"}, {"description", "Optional notes"}}}};
        t.input_schema.required = {"portfolio_id", "symbol", "type", "quantity", "price", "date"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString portfolio_id = args["portfolio_id"].toString().trimmed();
            QString symbol = args["symbol"].toString().trimmed().toUpper();
            QString type = args["type"].toString().trimmed().toUpper();
            double quantity = args["quantity"].toDouble(0.0);
            double price = args["price"].toDouble(0.0);
            QString date = args["date"].toString().trimmed();
            QString notes = args["notes"].toString();

            if (portfolio_id.isEmpty() || symbol.isEmpty() || type.isEmpty() || quantity <= 0 || date.isEmpty())
                return ToolResult::fail("Missing required: portfolio_id, symbol, type, quantity (>0), date");

            if (type == QLatin1String("SPLIT"))
                return ToolResult::fail("SPLIT is not supported: positions and history are not split-adjusted. "
                                        "Record the post-split position with SELL/BUY instead.");
            static const QStringList valid_types{"BUY", "SELL", "DIVIDEND"};
            if (!valid_types.contains(type))
                return ToolResult::fail("Invalid type. Must be BUY, SELL or DIVIDEND");
            if (price <= 0)
                return ToolResult::fail("'price' must be > 0");
            if (!ptd::valid_trade_date(date))
                return ToolResult::fail("Invalid 'date': expected YYYY-MM-DD, not in the future");
            if (PortfolioRepository::instance().get_portfolio(portfolio_id).is_err())
                return ToolResult::fail("Portfolio not found: " + portfolio_id);

            // Ledger-only writes used to leave the position untouched, so holdings
            // and history disagreed. Route through the service, which keeps both.
            const auto [ok, msg] = ptd::run_service_write([&](services::PortfolioService& svc) {
                if (type == QLatin1String("BUY"))
                    return svc.add_asset(portfolio_id, symbol, quantity, price, date.left(10));
                if (type == QLatin1String("SELL"))
                    return svc.sell_asset(portfolio_id, symbol, quantity, price, date.left(10));
                return svc.record_dividend(portfolio_id, symbol, quantity, price, quantity * price, date.left(10),
                                           notes);
            });
            if (!ok)
                return ToolResult::fail(msg.isEmpty() ? QStringLiteral("Failed to add transaction") : msg);

            LOG_INFO(kPortfolioToolsTag, QString("Transaction %1 %2 x%3").arg(type, symbol).arg(quantity));
            return ToolResult::ok("Transaction recorded",
                                  QJsonObject{{"symbol", symbol}, {"type", type}, {"quantity", quantity}});
        };
        tools.push_back(std::move(t));
    }

    // ── delete_transaction ──────────────────────────────────────────────
    {
        ToolDef t;
        t.name = "delete_transaction";
        t.description = "Delete a transaction by ID. A BUY/SELL deletion re-derives that symbol's position "
                        "from the remaining ledger.";
        t.category = "portfolio";
        t.is_destructive = true; // mutation tool — penalise on read-style queries
        t.input_schema.properties = QJsonObject{
            {"transaction_id", QJsonObject{{"type", "string"}, {"description", "Transaction ID"}}},
            {"portfolio_id",
             QJsonObject{{"type", "string"}, {"description", "Portfolio ID (optional; looked up when omitted)"}}}};
        t.input_schema.required = {"transaction_id"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString id = args["transaction_id"].toString().trimmed();
            if (id.isEmpty())
                return ToolResult::fail("Missing 'transaction_id'");

            QString portfolio_id = args["portfolio_id"].toString().trimmed();
            if (portfolio_id.isEmpty()) {
                auto ports = PortfolioRepository::instance().list_portfolios();
                if (ports.is_ok()) {
                    for (const auto& p : ports.value()) {
                        const auto txns = services::PortfolioService::instance().ledger(p.id);
                        if (std::any_of(txns.begin(), txns.end(), [&id](const auto& t) { return t.id == id; })) {
                            portfolio_id = p.id;
                            break;
                        }
                    }
                }
                if (portfolio_id.isEmpty())
                    return ToolResult::fail("Transaction not found: " + id);
            }
            const auto [ok, msg] = ptd::run_service_write(
                [&](services::PortfolioService& svc) { return svc.delete_transaction(id, portfolio_id); });
            if (!ok)
                return ToolResult::fail(msg.isEmpty() ? QStringLiteral("Failed to delete transaction") : msg);

            return ToolResult::ok("Transaction deleted", QJsonObject{{"id", id}, {"portfolio_id", portfolio_id}});
        };
        tools.push_back(std::move(t));
    }

    // ── get_portfolio_snapshots ─────────────────────────────────────────
    {
        ToolDef t;
        t.name = "get_portfolio_snapshots";
        t.description = "Get historical performance snapshots for a portfolio.";
        t.category = "portfolio";
        t.input_schema.properties = QJsonObject{
            {"portfolio_id", QJsonObject{{"type", "string"}, {"description", "Portfolio ID"}}},
            {"days", QJsonObject{{"type", "integer"},
                                 {"description", "Days of history (default: 365)"},
                                 {"minimum", 1},
                                 {"maximum", 3650}}},
            {"max_points", QJsonObject{{"type", "integer"},
                                       {"description", "Max snapshots returned (default 90, max 500). When the window "
                                                       "holds more, they are sampled evenly and the latest is always "
                                                       "included."},
                                       {"minimum", 2},
                                       {"maximum", 500}}}};
        t.input_schema.required = {"portfolio_id"};
        t.handler = [](const QJsonObject& args) -> ToolResult {
            QString id = args["portfolio_id"].toString().trimmed();
            if (id.isEmpty())
                return ToolResult::fail("Missing 'portfolio_id'");

            const int days = std::clamp(args["days"].toInt(365), 1, 3650);
            const int max_points = std::clamp(args["max_points"].toInt(90), 2, 500);
            auto r = PortfolioRepository::instance().get_snapshots(id, days);
            if (r.is_err())
                return ToolResult::fail("Failed to load snapshots: " + QString::fromStdString(r.error()));

            // A year of daily snapshots is ~365 rows — far over the result budget, and the
            // overflow shaper would keep the OLDEST rows and drop the recent ones, which
            // are the ones that matter. Sample evenly (newest row always kept, order
            // preserved) and say so.
            const auto& all = r.value();
            const qsizetype n = all.size();
            QVector<qsizetype> picks;
            if (n <= max_points) {
                for (qsizetype i = 0; i < n; ++i)
                    picks.append(i);
            } else {
                const double step = static_cast<double>(n - 1) / static_cast<double>(max_points - 1);
                qsizetype last = -1;
                for (int k = 0; k < max_points; ++k) {
                    const qsizetype idx = std::min<qsizetype>(n - 1, static_cast<qsizetype>(k * step + 0.5));
                    if (idx != last)
                        picks.append(idx);
                    last = idx;
                }
            }

            QJsonArray arr;
            for (const qsizetype pi : picks) {
                const auto& s = all[pi];
                arr.append(QJsonObject{{"id", s.id},
                                       {"total_value", s.total_value},
                                       {"total_cost_basis", s.total_cost_basis},
                                       {"total_pnl", s.total_pnl},
                                       {"total_pnl_percent", s.total_pnl_percent},
                                       {"date", s.snapshot_date}});
            }
            if (n > static_cast<qsizetype>(arr.size()))
                return ToolResult::ok(QStringLiteral("%1 snapshots in the last %2 days, sampled evenly down to %3 "
                                                     "(first and latest included). Raise `max_points` (max 500) or "
                                                     "shorten `days` for finer resolution.")
                                          .arg(n)
                                          .arg(days)
                                          .arg(arr.size()),
                                      arr);
            return ToolResult::ok_data(arr);
        };
        tools.push_back(std::move(t));
    }

    return tools;
}

} // namespace fincept::mcp::tools