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.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
Mcp and tool system fixes
tilakpatel228b6658040120
diff --git a/README.md b/README.mdindex 7f1a44dfc..5cbc8712a 100644--- a/README.md+++ b/README.md@@ -161,16 +161,6 @@ Questions: [[email protected]](mailto:[email protected]) · [Terms](https://fi### **Your Thinking is the Only Limit. The Data Isn't.**-<div align="center">-<a href="https://star-history.com/#Fincept-Corporation/FinceptTerminal&Date">- <picture>- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date&theme=dark" />- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fincept-Corporation/FinceptTerminal&type=Date" />- </picture>-</a>-</div>-[](https://repobeats.axiom.co)[](mailto:[email protected])diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txtindex fa3c54261..7b7252791 100644--- a/fincept-qt/CMakeLists.txt+++ b/fincept-qt/CMakeLists.txt@@ -33,7 +33,7 @@ if(WIN32 AND CMAKE_HOST_WIN32)unset(_fincept_sdk_dirs)endif()-project(FinceptTerminal VERSION 4.4.1 LANGUAGES C CXX)+project(FinceptTerminal VERSION 4.5.0 LANGUAGES C CXX)# Strip C/C++ flags out of RC invocations — rc.exe only understands /D, /I, /fo.if(WIN32)diff --git a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xmlindex eac95bfae..ce24615a4 100644--- a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml+++ b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.metainfo.xml@@ -71,6 +71,14 @@</provides><releases>+ <release version="4.5.0" date="2026-08-31">+ <description>+ <p>Fixes AI tool calling with Google Gemini. Around 150 tools take a free-form options object, which Gemini's schema cannot express; those tools were being advertised to Gemini as taking no arguments at all, so the assistant could call them but never pass them anything. They now work on Gemini as they already did on other providers.</p>+ <p>The assistant runs a turn's independent tool calls at the same time instead of one after another, so a request that needs several lookups returns sooner. Tools that change something still run in order, on their own.</p>+ <p>Long-running work — backtests, quant modules, agent runs — hands back a job you can watch instead of freezing the conversation for minutes; this now covers around 190 tools rather than a dozen. Job status reports elapsed time against the tool's own budget along with the tool's latest output, and cancelling a job returns control immediately.</p>+ <p>Tool sequences now have a time limit as well as a step limit, and say which one ran out instead of stopping without explanation. Also fixes the AstraFlow and AstraFlow CN providers failing to find their endpoint when the base URL field was cleared.</p>+ </description>+ </release><release version="4.4.1" date="2026-08-19"><description><p>Adds the TickerAll (MetaTrader 5) broker integration, so MT5 accounts can be linked, funded and traded from the equity trading screen alongside the existing brokers.</p>diff --git a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.ymlindex 832a86e32..325d82e89 100644--- a/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml+++ b/fincept-qt/packaging/flatpak/in.fincept.FinceptTerminal.yml@@ -55,7 +55,7 @@ modules:# Main repository- type: giturl: https://github.com/Fincept-Corporation/FinceptTerminal.git- tag: v4.4.1+ tag: v4.5.0# Vendored FetchContent dependencies (no network during build)- type: giturl: https://github.com/QtExcel/QXlsx.gitdiff --git a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txtindex 5404b8762..894e680a9 100644--- a/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt+++ b/fincept-qt/packaging/installer/packages/com.fincept.terminal.core/meta/license.txt@@ -226,5 +226,5 @@ Status: Current. Remains in force until expressly superseded by asubsequent version published by Fincept Corporation. Thedate above marks the most recent revision and is NOT anexpiry date.-Software Version: 4.4.1 (licence applies to all releases, branches, tags,+Software Version: 4.5.0 (licence applies to all releases, branches, tags,and commits of the open-source edition)diff --git a/fincept-qt/packaging/linux/AppImageBuilder.yml b/fincept-qt/packaging/linux/AppImageBuilder.ymlindex 11f887eed..35a07cbd5 100644--- a/fincept-qt/packaging/linux/AppImageBuilder.yml+++ b/fincept-qt/packaging/linux/AppImageBuilder.yml@@ -16,7 +16,7 @@ AppDir:id: com.fincept.terminalname: Fincept Terminalicon: fincept-terminal- version: !ENV ${FINCEPT_VERSION:-4.4.1}+ version: !ENV ${FINCEPT_VERSION:-4.5.0}exec: usr/bin/FinceptTerminalexec_args: $@@@ -56,6 +56,6 @@ AppDir:AppImage:arch: x86_64comp: xz- file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.4.1}-x86_64.AppImage+ file_name: FinceptTerminal-!ENV ${FINCEPT_VERSION:-4.5.0}-x86_64.AppImagesign-key: Noneupdate-information: gh-releases-zsync|Fincept-Corporation|FinceptTerminal|latest|FinceptTerminal-*x86_64.AppImage.zsyncdiff --git a/fincept-qt/packaging/linux/fincept-terminal.appdata.xml b/fincept-qt/packaging/linux/fincept-terminal.appdata.xmlindex f9f83515c..f95b406f4 100644--- a/fincept-qt/packaging/linux/fincept-terminal.appdata.xml+++ b/fincept-qt/packaging/linux/fincept-terminal.appdata.xml@@ -28,6 +28,11 @@<binary>FinceptTerminal</binary></provides><releases>+ <release version="4.5.0" date="2026-08-31">+ <description>+ <p>Version 4.5.0 — Fixes AI tool calling with Google Gemini: around 150 tools that take a free-form options object were being advertised to Gemini as taking no arguments, so they could be called but never given any input. The assistant now runs a turn's independent tool calls in parallel, while tools that change something still run in order. Long-running work (backtests, quant modules, agent runs) hands back a job you can watch and cancel instead of freezing the conversation, now across ~190 tools rather than a dozen. Tool sequences gain a time limit alongside the step limit and report which ran out. Fixes the AstraFlow providers failing to resolve their endpoint when the base URL was cleared.</p>+ </description>+ </release><release version="4.4.1" date="2026-08-19"><description><p>Version 4.4.1 — Adds the TickerAll (MetaTrader 5) broker integration for linking and trading MT5 accounts. Python runtime provisioning is more reliable on first run, and the unused FinRL analytics module and its heavy dependencies have been removed.</p>diff --git a/fincept-qt/scripts/agents/rdagents/mcp_server.py b/fincept-qt/scripts/agents/rdagents/mcp_server.pyindex 09e9965f5..9600a4db9 100644--- a/fincept-qt/scripts/agents/rdagents/mcp_server.py+++ b/fincept-qt/scripts/agents/rdagents/mcp_server.py@@ -23,7 +23,9 @@ from __future__ import annotationsimport astimport jsonimport logging+import mathimport os+import sysfrom datetime import datetime, timedeltafrom typing import Any@@ -99,13 +101,21 @@ def _compile_factor_expr(expr: str):# ---------------------------------------------------------------------------MCP_SERVER_AVAILABLE = False+# Which FastMCP is in use. The two packages export the same class name and the+# same decorators, but they do NOT agree on how a server is started, so the+# serving code has to know which one it got. See _serve().+# "mcp" — the official SDK (`pip install mcp`), FastMCP under mcp.server+# "fastmcp" — the standalone package (`pip install fastmcp`)+MCP_IMPL = ""try:from mcp.server.fastmcp import FastMCPMCP_SERVER_AVAILABLE = True+ MCP_IMPL = "mcp"except ImportError:try:from fastmcp import FastMCP # type: ignoreMCP_SERVER_AVAILABLE = True+ MCP_IMPL = "fastmcp"except ImportError:FastMCP = None # type: ignore@@ -124,6 +134,144 @@ except ImportError:pass+# ---------------------------------------------------------------------------+# Macro indicator catalogue (economics_data)+# ---------------------------------------------------------------------------+# Three kinds of indicator, and the difference is the whole point: a caller+# cannot interpret a number without knowing which kind produced it.+#+# market — the ticker *is* the indicator. vix -> ^VIX really is the VIX.+# proxy — the ticker is a tradeable stand-in whose price is NOT the+# statistic. ^VXX is a volatility ETN; its ~5200 has no reading as+# an unemployment rate. Presenting it unlabelled next to a market+# value invites exactly that misreading.+# static — a constant baked in here (or via env override), not fetched.+#+# These live at module scope, not inside build_mcp_server(), so the valid-name+# list has exactly one home. It previously had three — the two dicts, a+# hardcoded default list, and the docstring — and the latter two had already+# drifted: `nasdaq` and `dow` were fetchable but undocumented, so a caller had+# no way to learn they existed. Derive, don't restate.++INDICATOR_TICKERS: dict[str, str] = {+ "treasury_10y": "^TNX",+ "treasury_2y": "^IRX",+ "vix": "^VIX",+ "dxy": "DX-Y.NYB",+ "oil_wti": "CL=F",+ "gold": "GC=F",+ "sp500": "^GSPC",+ "nasdaq": "^IXIC",+ "dow": "^DJI",+}++# Market proxies for series with no yfinance ticker. Each MUST carry a note+# saying what the number actually is — that is the entire reason this table is+# separate from INDICATOR_TICKERS rather than merged into it.+FRED_PROXIES: dict[str, str] = {+ "cpi": "RINF",+ "unemployment": "^VXX",+}++PROXY_NOTES: dict[str, str] = {+ "cpi": (+ "PROXY, not the CPI. This is the market price of RINF (ProShares "+ "Inflation Expectations ETF), a tradeable read on expected inflation. "+ "It is not a CPI index level or an inflation rate. For the actual "+ "series use FRED CPIAUCSL."+ ),+ "unemployment": (+ "PROXY, and a poor one. This is the market price of ^VXX (a "+ "short-term VIX futures ETN): a risk-sentiment gauge with no "+ "unemployment content whatsoever. Do not read it as an unemployment "+ "rate. For the actual series use FRED UNRATE."+ ),+}++# Constants, with an env override. `note` is surfaced verbatim to the caller.+STATIC_INDICATORS: dict[str, tuple[str, str]] = {+ "fed_rate": ("FED_RATE_OVERRIDE", "5.25"),+ "gdp_growth": ("GDP_GROWTH_OVERRIDE", "2.8"),+}+++def valid_indicators() -> list[str]:+ """Every name economics_data accepts, in a stable documented order."""+ return (+ list(INDICATOR_TICKERS)+ + list(FRED_PROXIES)+ + list(STATIC_INDICATORS)+ )+++def resolve_indicator(name: str) -> tuple[str, str] | None:+ """Map a caller-supplied indicator name to ``(kind, key)``.++ Returns None when the name matches nothing — which is the caller's cue to+ report it rather than drop it. Lookup is case-insensitive and strips+ surrounding whitespace: an LLM writing the acronym as "CPI" is asking for+ the same series as "cpi", and silently failing that is the single most+ likely way to trigger the empty-result confusion this catalogue exists to+ prevent.+ """+ key = (name or "").strip().lower()+ if key in INDICATOR_TICKERS:+ return ("market", key)+ if key in FRED_PROXIES:+ return ("proxy", key)+ if key in STATIC_INDICATORS:+ return ("static", key)+ return None+++# ---------------------------------------------------------------------------+# Price-frame hygiene+# ---------------------------------------------------------------------------+#+# yfinance emits a row for the session currently in progress — and sometimes for+# a halted or untraded one — whose OHLC are all NaN while Volume is a real+# number. `hist.empty` is False, `len(hist)` counts it, and `iloc[-1]` returns+# it, so every "just take the last bar" path silently reports NaN as the price.+#+# It is not a regional quirk. It is whichever market has an unsettled bar at the+# moment you ask: reported for SAP.DE/CPG.L on one day, reproduced for AAPL on+# another.+#+# The damage is worse than one wrong field, because `json.dumps` writes NaN as a+# bare `NaN` literal and RFC 8259 defines no such token. A strict parser — Qt's+# QJsonDocument on the C++ side included — rejects the WHOLE document, so a+# single hollow bar destroys the entire tool result rather than one number in it.+++def _drop_hollow_bars(hist: Any) -> Any:+ """Drop rows with no usable Close from a yfinance history frame.++ Close is the anchor: every consumer here prices off it, and a row without+ one carries nothing worth keeping. Rows that merely lack an Open or a High+ survive — dropping those would discard a perfectly good close — and+ `_finite` keeps their gaps out of the JSON.+ """+ if hist is None or getattr(hist, "empty", True) or "Close" not in hist:+ return hist+ return hist.dropna(subset=["Close"])+++def _finite(value: Any, ndigits: int | None = None) -> float | None:+ """`float(value)`, or None if it is NaN/inf or not a number.++ None serialises to `null`, which is valid JSON and honestly says "no value".+ NaN serialises to a bare `NaN`, which does not parse. Never emit a raw float+ from market data into a response without passing it through here.+ """+ try:+ f = float(value)+ except (TypeError, ValueError):+ return None+ if not math.isfinite(f):+ return None+ return round(f, ndigits) if ndigits is not None else f++# ---------------------------------------------------------------------------# Server definition# ---------------------------------------------------------------------------@@ -175,22 +323,40 @@ def build_mcp_server() -> Any:if hist.empty:return {"error": f"No data found for symbol {symbol!r}"}+ # Distinguished from "no data at all" on purpose: a window in which+ # every bar is hollow is a different problem from an unknown symbol,+ # and collapsing the two sends the caller hunting for a typo.+ hist = _drop_hollow_bars(hist)+ if hist.empty:+ return {"error": f"No usable bars for {symbol!r} (every bar in the window is empty)"}+bars = []for ts, row in hist.iterrows():+ close = _finite(row["Close"], 4)+ if close is None:+ continue # belt and braces: _drop_hollow_bars already went first+ volume = _finite(row["Volume"])bars.append({"date": str(ts.date()) if hasattr(ts, "date") else str(ts),- "open": round(float(row["Open"]), 4),- "high": round(float(row["High"]), 4),- "low": round(float(row["Low"]), 4),- "close": round(float(row["Close"]), 4),- "volume": int(row["Volume"]),+ "open": _finite(row["Open"], 4),+ "high": _finite(row["High"], 4),+ "low": _finite(row["Low"], 4),+ "close": close,+ # int(NaN) raises, so an unguarded cast turned a hollow+ # volume into a failed call for the whole symbol.+ "volume": int(volume) if volume is not None else None,})latest = bars[-1] if bars else {}prev = bars[-2] if len(bars) > 1 else latest+ prev_close = prev.get("close")+ # `if prev_close` alone is not a NaN guard — bool(nan) is True, so the+ # old test waved NaN through and produced a NaN change_pct. Every+ # close reaching this point is finite by construction; the test now+ # only has to exclude a zero divisor.change_pct = (- (latest["close"] - prev["close"]) / prev["close"] * 100- if prev.get("close") else 0.0+ (latest["close"] - prev_close) / prev_close * 100+ if prev_close else 0.0)result: dict[str, Any] = {@@ -321,86 +487,137 @@ def build_mcp_server() -> Any:"""Fetch macroeconomic indicators using yfinance proxies.+ Every value carries a "source" saying what the number actually is:+ market - the ticker IS the indicator (vix -> ^VIX).+ proxy - a tradeable stand-in whose price is NOT the statistic. Also+ flagged proxy=true with a note. Do not report it as the+ series it stands in for.+ static - a constant, not fetched.+Args:- indicators: List of indicators to fetch. Options:- ['gdp_growth', 'cpi', 'unemployment', 'fed_rate',- 'treasury_10y', 'treasury_2y', 'vix', 'dxy',- 'oil_wti', 'gold', 'sp500']+ indicators: Names to fetch, case-insensitive. Valid names:+ treasury_10y, treasury_2y, vix, dxy, oil_wti, gold,+ sp500, nasdaq, dow (market); cpi, unemployment+ (proxy); fed_rate, gdp_growth (static).Defaults to all.- country: Country code (currently US-focused).+ country: Country code. Only US has data; anything else still+ returns US figures and says so in the response.Returns:- dict with indicator name → {value, change_pct, date}+ dict with indicators -> {value, change_pct, date, ticker, source}.+ Names matching nothing are listed in unknown_indicators (with+ valid_indicators) rather than silently dropped."""if not YFINANCE_AVAILABLE:return {"error": "yfinance not installed. Run: pip install yfinance"}- # Map indicator names to yfinance tickers- INDICATOR_TICKERS: dict[str, str] = {- "treasury_10y": "^TNX",- "treasury_2y": "^IRX",- "vix": "^VIX",- "dxy": "DX-Y.NYB",- "oil_wti": "CL=F",- "gold": "GC=F",- "sp500": "^GSPC",- "nasdaq": "^IXIC",- "dow": "^DJI",- }+ if indicators is None:+ indicators = valid_indicators()- # FRED-based indicators via yfinance ETF proxies- FRED_PROXIES: dict[str, str] = {- "cpi": "RINF", # inflation ETF as proxy- "unemployment": "^VXX", # no direct proxy — note in output+ result: dict[str, Any] = {+ "country": country,+ "timestamp": datetime.now().isoformat(),}+ # The country argument is accepted but every series here is US. Echoing+ # the request back unqualified would label US numbers as the caller's+ # country, so say plainly which one the data is.+ if (country or "").strip().upper() not in ("", "US", "USA"):+ result["data_country"] = "US"+ result["country_note"] = (+ f"No {country} data available; all values below are US. "+ "The country argument is not yet honoured."+ )- all_indicators = list(INDICATOR_TICKERS.keys()) + ["cpi", "unemployment",- "fed_rate", "gdp_growth"]- if indicators is None:- indicators = all_indicators-- result: dict[str, Any] = {"country": country, "timestamp": datetime.now().isoformat()}data: dict[str, Any] = {}+ unknown: list[str] = []for ind in indicators:- ticker_sym = INDICATOR_TICKERS.get(ind) or FRED_PROXIES.get(ind)- if not ticker_sym:- # Hardcoded / static values for indicators without direct tickers- if ind == "fed_rate":- data[ind] = {- "value": float(os.environ.get("FED_RATE_OVERRIDE", "5.25")),- "note": "Set FED_RATE_OVERRIDE env var to override, or use FRED API",- "source": "static",- }- elif ind == "gdp_growth":- data[ind] = {- "value": float(os.environ.get("GDP_GROWTH_OVERRIDE", "2.8")),- "note": "Set GDP_GROWTH_OVERRIDE env var to override, or use FRED API",- "source": "static",- }+ resolved = resolve_indicator(ind)+ if resolved is None:+ # Do NOT drop it. An unrecognised name and a genuinely empty+ # result used to be the same response ({"indicators": {}}),+ # which made a typo indistinguishable from unavailable data.+ unknown.append(ind)continue+ kind, key = resolved++ if kind == "static":+ env_var, default = STATIC_INDICATORS[key]+ data[key] = {+ "value": float(os.environ.get(env_var, default)),+ "note": f"Set {env_var} env var to override, or use FRED API",+ "source": "static",+ }+ continue++ ticker_sym = (+ INDICATOR_TICKERS[key] if kind == "market" else FRED_PROXIES[key]+ )try:ticker = yf.Ticker(ticker_sym)hist = ticker.history(period="5d", interval="1d")if hist.empty:- data[ind] = {"error": f"No data for {ticker_sym}"}+ data[key] = {"error": f"No data for {ticker_sym}", "ticker": ticker_sym}+ continue++ # Before this, a hollow last bar made the guard below report the+ # indicator as unavailable while a perfectly good close sat one+ # row up. Dropping first turns that error into the right number.+ hist = _drop_hollow_bars(hist)+ if hist.empty:+ data[key] = {+ "error": f"No usable close for {ticker_sym} (every bar is empty)",+ "ticker": ticker_sym,+ }continuelatest_close = float(hist["Close"].iloc[-1])- prev_close = float(hist["Close"].iloc[-2]) if len(hist) > 1 else latest_close- change_pct = (latest_close - prev_close) / prev_close * 100 if prev_close else 0+ # A non-empty frame can still carry a hollow last bar, and the+ # NaN that produces is not merely wrong — json.dumps writes it+ # as bare `NaN`, which is not JSON (RFC 8259 has no such+ # literal). A strict client — Qt's QJsonDocument on the C+++ # side included — then fails to parse the WHOLE tool result,+ # so one stale ETF takes down every other indicator with it.+ if latest_close != latest_close: # NaN+ data[key] = {+ "error": f"No usable close for {ticker_sym} (latest bar is empty)",+ "ticker": ticker_sym,+ }+ continue- data[ind] = {+ prev_close = float(hist["Close"].iloc[-2]) if len(hist) > 1 else latest_close+ if prev_close != prev_close: # NaN+ prev_close = latest_close+ change_pct = (latest_close - prev_close) / prev_close * 100 if prev_close else 0++ entry: dict[str, Any] = {"value": round(latest_close, 4),"change_pct": round(change_pct, 3),"date": str(hist.index[-1].date()),"ticker": ticker_sym,+ "source": "market" if kind == "market" else "proxy",}+ if kind == "proxy":+ # The value is a share price, not the statistic. Say so on+ # the value itself — a note filed elsewhere in the response+ # is a note the reader of this number will not see.+ entry["proxy"] = True+ entry["note"] = PROXY_NOTES[key]+ data[key] = entryexcept Exception as e:- data[ind] = {"error": str(e), "ticker": ticker_sym}+ data[key] = {"error": str(e), "ticker": ticker_sym}result["indicators"] = data+ if unknown:+ result["unknown_indicators"] = unknown+ result["valid_indicators"] = valid_indicators()+ result["error"] = (+ "Unrecognised indicator(s): "+ + ", ".join(repr(u) for u in unknown)+ + ". Valid ids: "+ + ", ".join(valid_indicators())+ )return result# ── Tool: factor_backtest ────────────────────────────────────────────────@@ -436,8 +653,14 @@ def build_mcp_server() -> Any:ticker = yf.Ticker(symbol.upper())hist = ticker.history(period=period, interval="1d")+ # Before the guard, not after: a hollow bar was counted toward the+ # 60-bar minimum, and it also entered `returns`, where pct_change+ # spread its NaN to the neighbouring row and cost the most recent+ # real observation its forward return. A hollow bar in the interior+ # additionally poisons a full window of any rolling factor.+ hist = _drop_hollow_bars(hist)if len(hist) < 60:- return {"error": f"Insufficient data for {symbol} ({len(hist)} bars)"}+ return {"error": f"Insufficient data for {symbol} ({len(hist)} usable bars)"}df = pd.DataFrame({"open": hist["Open"],@@ -546,21 +769,218 @@ def build_mcp_server() -> Any:# Entry point — run as standalone HTTP server# ---------------------------------------------------------------------------+def _serve(server: Any, host: str, port: int, path: str) -> None:+ """Start `server` on streamable-HTTP, whichever FastMCP we ended up with.++ There are three live shapes for this and they are mutually incompatible:++ 1. standalone ``fastmcp``+ run(transport, host=..., port=..., path=...)+ 2. official ``mcp`` SDK, FastMCP era (>=1.26, incl. 1.29)+ run(transport, mount_path=None) <- host/port/path NOT accepted+ host, port and streamable_http_path are Settings fields+ 3. official ``mcp`` SDK, MCPServer era+ run(transport, **kwargs) -> forwarded to run_streamable_http_async,+ where the path keyword is ``streamable_http_path``, not ``path``++ This used to hardcode shape 1 while the import block preferred shape 2, so+ `pip install mcp` — the install this repo's own error messages tell you to+ do — produced a server that raised ``TypeError: FastMCP.run() got an+ unexpected keyword argument 'host'`` on every start and never listened.+ It only worked if ``fastmcp`` was installed *and* ``mcp`` was not.++ Rather than pick a package and hope, set the settings when the object has+ them and pass the keywords when ``run`` actually accepts them. Shapes 2 and+ 3 each ignore the half that does not apply to them.+ """+ import inspect++ # Shape 2 reads these at run() time. hasattr-guarded because the standalone+ # package's settings object does not carry the same field names.+ settings = getattr(server, "settings", None)+ if settings is not None:+ for attr, value in (("host", host), ("port", port), ("streamable_http_path", path)):+ if hasattr(settings, attr):+ setattr(settings, attr, value)++ params = inspect.signature(server.run).parameters+ takes_kwargs = any(p.kind is p.VAR_KEYWORD for p in params.values())+ if "host" in params or takes_kwargs:+ # Shapes 1 and 3. They disagree on the path keyword, and passing the+ # wrong one is a TypeError, so it is chosen by which package we imported+ # rather than guessed.+ path_kw = "path" if MCP_IMPL == "fastmcp" else "streamable_http_path"+ server.run(transport="streamable-http", host=host, port=port, **{path_kw: path})+ return++ # Shape 2: everything travelled via settings above.+ server.run(transport="streamable-http")+++def _selftest() -> int:+ """Offline checks for the tool contracts. No network, no API key.++ Guards the two regressions from issue #382 — an unknown indicator name+ silently producing the same response as an empty result, and a proxy value+ presented as if it were the statistic — plus the NaN-is-not-JSON hazard+ that one stale ETF bar introduces into every other indicator's result.++ Section [4] guards issue #380: yfinance emits a bar for the unsettled+ session with all-NaN OHLC, and every "take the last bar" path reported that+ NaN as the price. Live data cannot be relied on to contain a hollow bar on+ any given day, so those frames are synthetic and pin the exact shape+ yfinance produces — all-NaN OHLC beside a real Volume.+ """+ failures: list[str] = []++ def check(label: str, ok: bool) -> None:+ print(f" [{'PASS' if ok else 'FAIL'}] {label}")+ if not ok:+ failures.append(label)++ print("[1] indicator catalogue")+ names = valid_indicators()+ check("no duplicate names", len(names) == len(set(names)))+ check("every proxy has a note", set(FRED_PROXIES) <= set(PROXY_NOTES))+ check("proxy and market tables are disjoint",+ not (set(FRED_PROXIES) & set(INDICATOR_TICKERS)))+ check("catalogue covers all three kinds",+ {resolve_indicator(n)[0] for n in names} == {"market", "proxy", "static"})++ print("[2] name resolution")+ check("known name resolves", resolve_indicator("vix") == ("market", "vix"))+ check("case/space insensitive", resolve_indicator(" CPI ") == ("proxy", "cpi"))+ check("unknown name returns None", resolve_indicator("banana") is None)+ check("near-miss 'gdp' is NOT silently accepted", resolve_indicator("gdp") is None)++ if not MCP_SERVER_AVAILABLE or not YFINANCE_AVAILABLE:+ print("[3] tool contract: SKIPPED (needs mcp + yfinance installed)")+ print(f"\n{len(failures)} failure(s)")+ return 1 if failures else 0++ print("[3] tool contract (offline paths only)")+ fn = build_mcp_server()._tool_manager._tools["economics_data"].fn+ typo, nonsense = fn(indicators=["gdp"]), fn(indicators=["banana"])+ check("a typo is reported, not dropped", typo.get("unknown_indicators") == ["gdp"])+ check("typo and nonsense are distinguishable",+ typo.get("unknown_indicators") != nonsense.get("unknown_indicators"))+ check("the correct name is discoverable from the response",+ "gdp_growth" in typo.get("valid_indicators", []))+ static_only = fn(indicators=["fed_rate", "gdp_growth"])+ check("static values still labelled source=static",+ all(v.get("source") == "static" for v in static_only["indicators"].values()))+ try:+ json.dumps(typo, allow_nan=False)+ json.dumps(static_only, allow_nan=False)+ check("responses are RFC-8259 valid JSON (no bare NaN)", True)+ except ValueError as e:+ check(f"responses are RFC-8259 valid JSON (no bare NaN): {e}", False)++ print("[4] hollow bars (issue #380)")+ import pandas as pd++ nan = float("nan")++ def frame(closes: list, *, hollow_volume: bool = False):+ """A yfinance-shaped daily frame. A NaN close marks a hollow bar."""+ return pd.DataFrame(+ {+ "Open": closes, "High": closes, "Low": closes, "Close": closes,+ # Volume is real even on a hollow bar — that is precisely why+ # the NaN slipped through instead of raising.+ "Volume": [nan if (hollow_volume and c != c) else 1_000_000.0 for c in closes],+ },+ index=pd.date_range("2026-01-01", periods=len(closes), freq="D"),+ )++ check("hollow trailing bar dropped", len(_drop_hollow_bars(frame([1.0, 2.0, nan]))) == 2)+ check("interior hollow bar dropped", len(_drop_hollow_bars(frame([1.0, nan, 3.0]))) == 2)+ check("clean frame untouched", len(_drop_hollow_bars(frame([1.0, 2.0]))) == 2)+ check("_finite rejects NaN and inf, keeps and rounds reals",+ _finite(nan) is None and _finite(float("inf")) is None and _finite(1.23456, 2) == 1.23)++ tools = build_mcp_server()._tool_manager._tools+ market_fn, factor_fn = tools["market_data"].fn, tools["factor_backtest"].fn++ def fake_yf(df):+ class _Ticker:+ info: dict = {}++ def history(self, **_kw):+ return df.copy()++ return type("yf", (), {"Ticker": staticmethod(lambda _sym: _Ticker())})++ global yf+ real_yf = yf+ try:+ yf = fake_yf(frame([100.0, 189.88, nan]))+ got = market_fn(symbol="SAP.DE", period="5d", interval="1d")+ check("latest_price is the last VALID close, not NaN", got.get("latest_price") == 189.88)+ check("the hollow bar is not counted", got.get("bar_count") == 2)+ try:+ json.dumps(got, allow_nan=False)+ check("market_data is RFC-8259 valid JSON", True)+ except ValueError as e:+ check(f"market_data is RFC-8259 valid JSON: {e}", False)++ # int(NaN) raises, so an unguarded volume cast used to fail the call.+ yf = fake_yf(frame([100.0, 101.0, nan], hollow_volume=True))+ got = market_fn(symbol="X", period="5d", interval="1d")+ check("a fully hollow bar does not error the whole call",+ "error" not in got and got.get("latest_price") == 101.0)++ yf = fake_yf(frame([nan, nan]))+ got = market_fn(symbol="Y", period="5d", interval="1d")+ check("an all-hollow window says so, rather than 'symbol not found'",+ "every bar in the window is empty" in str(got.get("error")))++ # 59 real bars plus a hollow one totalled 60 and slipped past the+ # sufficiency guard, which then returned confident statistics computed+ # on 58 rows.+ yf = fake_yf(frame([100.0 + i * 0.5 for i in range(59)] + [nan]))+ got = factor_fn(symbol="S", factor_expr="close", period="1y")+ check("59 real + 1 hollow is refused, and counted honestly",+ "(59 usable bars)" in str(got.get("error")))+ yf = fake_yf(frame([100.0 + i * 0.5 for i in range(60)] + [nan]))+ got = factor_fn(symbol="S", factor_expr="close", period="1y")+ check("60 real + 1 hollow still runs", "error" not in got)+ finally:+ yf = real_yf++ print(f"\n{len(failures)} failure(s)")+ return 1 if failures else 0++def main() -> None:import argparseparser = argparse.ArgumentParser(description="Fincept MCP server for RD-Agent")parser.add_argument("--port", type=int, default=18765)parser.add_argument("--host", default="127.0.0.1")+ parser.add_argument("--selftest", action="store_true",+ help="Run offline contract checks and exit")args = parser.parse_args()+ if args.selftest:+ raise SystemExit(_selftest())+if not MCP_SERVER_AVAILABLE:print(json.dumps({"error": "mcp[cli] not installed. Run: pip install mcp[cli]"}))raise SystemExit(1)server = build_mcp_server()- print(f"Fincept MCP server starting on http://{args.host}:{args.port}/mcp", flush=True)- server.run(transport="streamable-http", host=args.host, port=args.port, path="/mcp")+ # stderr, not stdout: stdout is the JSON-RPC channel for MCP's stdio+ # transport, so a banner printed there corrupts the stream for any client+ # that speaks it. Harmless over HTTP, fatal over stdio, and free to get+ # right. mcp_tools.start_mcp_server_process pipes both, so the line is+ # still captured either way.+ print(+ f"Fincept MCP server starting on http://{args.host}:{args.port}/mcp",+ file=sys.stderr,+ flush=True,+ )+ _serve(server, args.host, args.port, "/mcp")if __name__ == "__main__":diff --git a/fincept-qt/src/mcp/AsyncDispatch.h b/fincept-qt/src/mcp/AsyncDispatch.hindex 9e1fbd4cb..341423af5 100644--- a/fincept-qt/src/mcp/AsyncDispatch.h+++ b/fincept-qt/src/mcp/AsyncDispatch.h@@ -50,16 +50,74 @@#include <QFuture>#include <QMetaObject>#include <QPromise>+#include <QRegularExpression>+#include <QString>#include <QThread>+#include <algorithm>#include <atomic>#include <functional>#include <memory>namespace fincept::mcp {+/// Ceiling on a progress message. The snapshot it lands in is polled+/// repeatedly, so an unbounded line is re-billed on every poll.+inline constexpr int kProgressMessageMaxChars = 160;+class AsyncDispatch {public:+ /// Bridge a line-oriented stdout/stderr stream into `ctx.on_progress`, for+ /// services that expose one (PythonRunner::run's `on_line`).+ ///+ /// Returns a callback with PythonRunner's StreamCallback shape, or an empty+ /// one when `ctx` has no progress hook — so a caller can pass the result+ /// straight through without branching.+ ///+ /// What this deliberately does NOT do is invent a percentage. `job_status`+ /// reported `progress: 0.0` for every job in the catalogue because no+ /// handler ever called `on_progress`, and the obvious repair — synthesising+ /// elapsed/timeout as a completion ratio — would have replaced "no+ /// information" with "confident misinformation": a 3 s script at a 300 s+ /// budget is not 1% done. So the numeric field moves ONLY when the script+ /// says so, by printing a line carrying `"progress": <0..1>` (or a bare+ /// `progress: 42%`). Everything else becomes the human-readable `message`,+ /// which is what actually distinguishes a working job from a wedged one.+ static std::function<void(QString, bool)> line_progress_bridge(const ToolContext& ctx) {+ if (!ctx.on_progress)+ return {};+ auto on_progress = ctx.on_progress;+ return [on_progress](QString line, bool /*is_stderr*/) {+ const QString trimmed = line.trimmed();+ if (trimmed.isEmpty())+ return;+ // Cap the message: this lands in a snapshot the model polls+ // repeatedly, so a stray 4 KB traceback line would be re-billed on+ // every poll for the life of the job.+ on_progress(parse_progress_fraction(trimmed), trimmed.left(kProgressMessageMaxChars));+ };+ }++ /// Extract a machine-readable completion fraction from a status line, or 0+ /// when the line carries none. Accepts `"progress": 0.42`, `progress=0.42`+ /// and `progress: 42%`; anything else leaves the number untouched (0 is the+ /// registry's "no numeric progress reported" sentinel).+ static double parse_progress_fraction(const QString& line) {+ static const QRegularExpression rx(+ QStringLiteral(R"(\bprogress"?\s*[:=]\s*"?(\d+(?:\.\d+)?)\s*(%?))"),+ QRegularExpression::CaseInsensitiveOption);+ const auto m = rx.match(line);+ if (!m.hasMatch())+ return 0.0;+ bool ok = false;+ double v = m.captured(1).toDouble(&ok);+ if (!ok)+ return 0.0;+ if (m.captured(2) == QLatin1String("%") || v > 1.0)+ v /= 100.0;+ return std::clamp(v, 0.0, 1.0);+ }+/// Bridge an async-callback API to a QPromise<ToolResult>.////// `target` — the QObject whose thread the body runs on (e.g. the@@ -75,17 +133,25 @@ class AsyncDispatch {/// Re-entrancy: `resolve` is no-op after the first call. Useful when/// the timeout watchdog races with the service callback.template <typename BodyFn>- static void callback_to_promise(QObject* target, ToolContext /*ctx*/, std::shared_ptr<QPromise<ToolResult>> promise,+ static void callback_to_promise(QObject* target, ToolContext ctx, std::shared_ptr<QPromise<ToolResult>> promise,BodyFn&& body) {- // Wrap resolve so it's idempotent — the timeout watchdog and the- // service callback can race; whichever fires first wins.+ // Wrap resolve so it's idempotent — the timeout watchdog, the+ // cancellation watch and the service callback can all race; whichever+ // fires first wins.//// The guard must be a compare-exchange, not a `future().isFinished()`// test: the watchdog fires on the GUI thread while the service callback// fires on its own thread, so both can observe "not finished" and then// both addResult() — the loser writing after finish(), which Qt asserts// on. Only the thread that flips the flag proceeds.- auto resolved = std::make_shared<std::atomic<bool>>(false);+ //+ // Critically, the flag must be the SAME one the provider's watchdog+ // races. Minting a private one here made this look guarded while the+ // only contenders it actually excluded were each other's: the provider+ // let its winner through, this let its winner through, and both wrote.+ // `ctx.resolve_guard` carries the provider's flag; the fallback is for+ // a hand-built context in a test or a direct caller.+ auto resolved = ctx.resolve_guard ? ctx.resolve_guard : std::make_shared<std::atomic<bool>>(false);auto resolve = [promise, resolved](ToolResult r) {bool expected = false;if (!resolved->compare_exchange_strong(expected, true))diff --git a/fincept-qt/src/mcp/GeminiSchema.cpp b/fincept-qt/src/mcp/GeminiSchema.cppindex ab64154b3..00345e9c8 100644--- a/fincept-qt/src/mcp/GeminiSchema.cpp+++ b/fincept-qt/src/mcp/GeminiSchema.cpp@@ -3,6 +3,7 @@#include "mcp/GeminiSchema.h"#include <QJsonArray>+#include <QJsonDocument>#include <QJsonValue>#include <QRegularExpression>#include <QSet>@@ -188,9 +189,37 @@ std::optional<QJsonObject> gemini_sanitize(const QJsonObject& in, int depth) {if (type == QLatin1String("object")) {const QJsonObject props = out.value(QStringLiteral("properties")).toObject();// An OBJECT with no properties is rejected outright ("should be- // non-empty for OBJECT type"). Signal "drop me" to the caller.- if (props.isEmpty())- return std::nullopt;+ // non-empty for OBJECT type"), and Gemini has no `additionalProperties`+ // with which to say "any keys". So a FREE-FORM object parameter — the+ // `params` / `config` / `args` / `metadata` bag that ~150 tools in this+ // catalogue declare — cannot be expressed as an OBJECT at all.+ //+ // Dropping it (what this used to do) is not a safe fallback: the tool is+ // then declared to Gemini as taking no such argument, so the model can+ // never supply it. For the ~115 tools whose ONLY parameter is such a+ // bag, the whole `parameters` object collapsed and the tool was+ // advertised as parameterless — callable, and useless.+ //+ // Nested, we substitute a STRING carrying serialised JSON, which is the+ // one shape Gemini both accepts and lets the model fill with arbitrary+ // keys. `restore_gemini_call_args` parses it back before dispatch, so+ // the handler still receives a real object.+ //+ // At the top level (depth 0) there is nothing to substitute into:+ // `parameters` itself must be an OBJECT, so the caller must omit the+ // field entirely — which is correct there, since a top-level empty+ // object means a genuinely parameterless tool.+ if (props.isEmpty()) {+ if (depth == 0)+ return std::nullopt;+ QString desc = in.value(QStringLiteral("description")).toString().trimmed();+ if (!desc.isEmpty() && !desc.endsWith(QLatin1Char('.')))+ desc += QLatin1Char('.');+ desc += QStringLiteral(" Pass a JSON object serialised as a string, e.g. "+ "\"{\\\"key\\\": \\\"value\\\"}\".");+ return QJsonObject{{QStringLiteral("type"), QStringLiteral("string")},+ {QStringLiteral("description"), desc.trimmed()}};+ }// `required` may only name properties that survived sanitisation —// a required-but-absent name is itself a validation error.@@ -215,6 +244,76 @@ std::optional<QJsonObject> sanitize_schema_for_gemini(const QJsonObject& schema)return gemini_sanitize(schema, 0);}+namespace {++// One value, coerced against the type its schema declares. `depth` guards a+// self-referential schema the same way the sanitiser does.+QJsonValue gemini_restore_value(const QJsonValue& value, const QJsonObject& schema, int depth);++QJsonObject gemini_restore_object(const QJsonObject& args, const QJsonObject& schema, int depth) {+ const QJsonObject props = schema.value(QStringLiteral("properties")).toObject();+ if (props.isEmpty() || depth > 12)+ return args;+ QJsonObject out = args;+ for (auto it = args.constBegin(); it != args.constEnd(); ++it) {+ const QJsonValue decl = props.value(it.key());+ if (!decl.isObject())+ continue;+ out[it.key()] = gemini_restore_value(it.value(), decl.toObject(), depth + 1);+ }+ return out;+}++QJsonValue gemini_restore_value(const QJsonValue& value, const QJsonObject& schema, int depth) {+ if (depth > 12)+ return value;+ const QString type = gemini_normalise_type(schema.value(QStringLiteral("type")));++ if (type == QLatin1String("object")) {+ if (value.isObject())+ return gemini_restore_object(value.toObject(), schema, depth);+ if (value.isString()) {+ // The surrogate round-trip. An empty string means "not supplied" —+ // returning it unchanged lets the validator speak for itself.+ const QJsonDocument doc = QJsonDocument::fromJson(value.toString().toUtf8());+ if (doc.isObject())+ return gemini_restore_object(doc.object(), schema, depth);+ }+ return value;+ }++ if (type == QLatin1String("array")) {+ QJsonArray arr;+ if (value.isArray()) {+ arr = value.toArray();+ } else if (value.isString()) {+ const QJsonDocument doc = QJsonDocument::fromJson(value.toString().toUtf8());+ if (!doc.isArray())+ return value;+ arr = doc.array();+ } else {+ return value;+ }+ const QJsonValue items = schema.value(QStringLiteral("items"));+ if (!items.isObject())+ return arr;+ QJsonArray out;+ for (const auto& e : arr)+ out.append(gemini_restore_value(e, items.toObject(), depth + 1));+ return out;+ }++ return value;+}++} // namespace++QJsonObject restore_gemini_call_args(const QJsonObject& original_schema, const QJsonObject& args) {+ if (original_schema.isEmpty() || args.isEmpty())+ return args;+ return gemini_restore_object(args, original_schema, 0);+}+bool is_valid_gemini_function_name(const QString& name) {static const QRegularExpression rx(QStringLiteral("^[a-zA-Z_][a-zA-Z0-9_.:-]{0,63}$"));return rx.match(name).hasMatch();diff --git a/fincept-qt/src/mcp/GeminiSchema.h b/fincept-qt/src/mcp/GeminiSchema.hindex 142078264..d156c9dcd 100644--- a/fincept-qt/src/mcp/GeminiSchema.h+++ b/fincept-qt/src/mcp/GeminiSchema.h@@ -48,4 +48,20 @@ std::optional<QJsonObject> sanitize_schema_for_gemini(const QJsonObject& schema)/// request when it does.bool is_valid_gemini_function_name(const QString& name);+/// Undo the STRING-surrogate substitution `sanitize_schema_for_gemini` applies+/// to free-form OBJECT parameters, so tool handlers keep receiving real JSON.+///+/// Gemini cannot declare "an object with arbitrary keys" — it has no+/// `additionalProperties`, and an OBJECT with an empty `properties` map is+/// rejected outright. Such a parameter therefore goes out as a STRING holding+/// serialised JSON, and the model fills it with a string. Left alone,+/// `args["params"].toObject()` in the handler yields `{}` — the call silently+/// does nothing, which is worse than an error.+///+/// Walks `original_schema` (the UNSANITISED tool schema) and, wherever it+/// declares an object or array but the model supplied a string that parses as+/// one, substitutes the parsed value. Anything that does not parse is left+/// untouched so the normal argument validator still reports it.+QJsonObject restore_gemini_call_args(const QJsonObject& original_schema, const QJsonObject& args);+} // namespace fincept::mcpdiff --git a/fincept-qt/src/mcp/JobRegistry.cpp b/fincept-qt/src/mcp/JobRegistry.cppindex 47809f31e..621ec1a05 100644--- a/fincept-qt/src/mcp/JobRegistry.cpp+++ b/fincept-qt/src/mcp/JobRegistry.cpp@@ -36,6 +36,8 @@ QJsonObject JobSnapshot::to_json() const {};// Omit zero/empty fields — this object is polled repeatedly and every// key costs tokens on every poll.+ if (timeout_ms > 0 && state == JobState::Running)+ j["timeout_ms"] = timeout_ms; // only useful while there is still a decision to makeif (progress > 0.0)j["progress"] = progress;if (!message.isEmpty())@@ -48,7 +50,7 @@ JobRegistry& JobRegistry::instance() {return s;}-QString JobRegistry::create(const QString& tool) {+QString JobRegistry::create(const QString& tool, int timeout_ms) {QMutexLocker lock(&mutex_);sweep_locked();@@ -61,6 +63,7 @@ QString JobRegistry::create(const QString& tool) {job.snap.tool = tool;job.snap.state = JobState::Running;job.snap.started_ms = now_ms();+ job.snap.timeout_ms = timeout_ms;job.cancel_flag = std::make_shared<std::atomic<bool>>(false);jobs_.insert(id, std::move(job));diff --git a/fincept-qt/src/mcp/JobRegistry.h b/fincept-qt/src/mcp/JobRegistry.hindex 4df4d3892..58529faee 100644--- a/fincept-qt/src/mcp/JobRegistry.h+++ b/fincept-qt/src/mcp/JobRegistry.h@@ -70,6 +70,12 @@ struct JobSnapshot {QString message; // last status line from the handlerqint64 started_ms = 0; // epoch msqint64 finished_ms = 0;+ // The handler's hard budget. Reported alongside elapsed_ms because elapsed+ // alone is undecidable: "running, 40 s" is healthy for a 300 s backtest and+ // nearly dead for a 45 s quote fetch, and the model has no other way to+ // tell which it is holding. Together they answer the only question a poll+ // is really asking — keep waiting, or give up.+ int timeout_ms = 0;bool result_collected = false;bool is_finished() const { return state != JobState::Running; }@@ -85,7 +91,9 @@ class JobRegistry {static JobRegistry& instance();/// Register a new running job. Returns its id (e.g. "job_4f21ab").- QString create(const QString& tool);+ /// `timeout_ms` is the handler's hard budget, echoed back by `job_status`+ /// so a poller can tell a slow job from a stuck one.+ QString create(const QString& tool, int timeout_ms = 0);/// Handler progress hook. `progress` is clamped to [0,1]; an empty/// `message` leaves the previous one in place.diff --git a/fincept-qt/src/mcp/McpProvider.cpp b/fincept-qt/src/mcp/McpProvider.cppindex 02b990dba..27ff75ce1 100644--- a/fincept-qt/src/mcp/McpProvider.cpp+++ b/fincept-qt/src/mcp/McpProvider.cpp@@ -25,6 +25,11 @@ namespace fincept::mcp {static constexpr const char* TAG = "McpProvider";+// How often the cancellation watch checks the flag. Cancellation is a human+// action, so a quarter-second lag is imperceptible, and the timer only exists+// for the lifetime of a job-backed call.+static constexpr int kCancelPollMs = 250;+McpProvider& McpProvider::instance() {static McpProvider s;return s;@@ -141,6 +146,12 @@ std::vector<McpProvider::ToolAuditInfo> McpProvider::audit_all_tools() const {// A std::function is truthy when a target is bound. async wins if both.info.has_handler = static_cast<bool>(def.handler) || static_cast<bool>(def.async_handler);info.is_async = static_cast<bool>(def.async_handler);+ info.default_timeout_ms = def.default_timeout_ms;+ info.supports_async = def.supports_async;+ // Mirrors supports_async_jobs() without re-locking (we already hold the+ // mutex). Kept next to it so the two can't drift.+ info.job_eligible = static_cast<bool>(def.async_handler) &&+ (def.supports_async || def.default_timeout_ms > kMcpAsyncJobThresholdMs);info.enabled = !disabled_tools_.contains(it.key());info.is_destructive = def.is_destructive;info.auth_required = def.auth_required;@@ -188,10 +199,26 @@ bool McpProvider::supports_async_jobs(const QString& name) const {auto it = tools_.constFind(name);if (it == tools_.constEnd() || disabled_tools_.contains(name))return false;- // The flag alone isn't enough — a sync handler runs to completion on the- // calling thread and can be neither observed nor interrupted, so there is- // nothing a job wrapper could add.- return it->supports_async && static_cast<bool>(it->async_handler);+ // An async handler is the hard prerequisite — a sync handler runs to+ // completion on the calling thread and can be neither observed nor+ // interrupted, so there is nothing a job wrapper could add.+ if (!it->async_handler)+ return false;+ // Eligibility is derived from the declared budget, with the explicit flag+ // as an override. A tool that raised `default_timeout_ms` above the 30 s+ // default has already stated its p95 is tens of seconds, which is exactly+ // the condition the flag was supposed to encode; requiring both meant the+ // fact had to be written twice and, in practice, was written once. Twelve+ // tools carried the flag while ~125 qualified — 97 AI Quant Lab tools at a+ // 300 s budget among them, each able to hold the provider's HTTP turn open+ // for five minutes with no receipt the model could poll.+ return it->supports_async || it->default_timeout_ms > kMcpAsyncJobThresholdMs;+}++int McpProvider::effective_timeout_ms(const QString& name) const {+ QMutexLocker lock(&mutex_);+ auto it = tools_.constFind(name);+ return it == tools_.constEnd() ? kMcpDefaultTimeoutMs : it->default_timeout_ms;}ToolResult McpProvider::call_tool_or_defer(const QString& name, const QJsonObject& args, int grace_ms) {@@ -199,7 +226,7 @@ ToolResult McpProvider::call_tool_or_defer(const QString& name, const QJsonObjecreturn call_tool(name, args);auto& jobs = JobRegistry::instance();- const QString job_id = jobs.create(name);+ const QString job_id = jobs.create(name, effective_timeout_ms(name));// Wire the job into the handler's context: cancellation reads the job's own// atomic flag (no registry lock in the handler's polling loop), progress@@ -338,6 +365,12 @@ QFuture<ToolResult> McpProvider::call_tool_async(const QString& name, const QJso// Cancellation flag — set by the timeout timer or by a caller-supplied// hook. Wired into ctx.is_cancelled below.auto cancelled = std::make_shared<std::atomic<bool>>(false);+ // Whether the CALLER supplied a hook (i.e. this call runs under a job and+ // `job_cancel` can flip it). Composition below hides that distinction, and+ // it decides whether the cancellation watch is worth arming: our own+ // internal flag is only ever raised by the timeout timer, which already+ // resolves the promise itself.+ const bool caller_can_cancel = static_cast<bool>(ctx.is_cancelled);if (!ctx.is_cancelled) {ctx.is_cancelled = [cancelled]() { return cancelled->load(); };} else {@@ -360,6 +393,10 @@ QFuture<ToolResult> McpProvider::call_tool_async(const QString& name, const QJso// `watchdog_slot` is filled in below; resolve() only reads it, so the// fast path (handler resolves before we even arm the timer) is safe.auto resolved = std::make_shared<std::atomic<bool>>(false);+ // Publish it so the handler's own resolver races the SAME atomic as the+ // watchdog and the cancellation watch, rather than a private copy that+ // guards nothing against them. See ToolContext::resolve_guard.+ ctx.resolve_guard = resolved;auto watchdog_slot = std::make_shared<QPointer<QTimer>>();auto resolve = [promise, resolved, watchdog_slot](ToolResult r) {bool expected = false;@@ -394,6 +431,50 @@ QFuture<ToolResult> McpProvider::call_tool_async(const QString& name, const QJsoQMetaObject::invokeMethod(watchdog, [watchdog, ms = ctx.timeout_ms]() { watchdog->start(ms); }, Qt::QueuedConnection);+ // Cancellation watch. `job_cancel` raises a flag and the contract says+ // handlers poll it — but almost none do, and the ones that do check it+ // only in their completion callback, i.e. after the work they were meant+ // to abandon has already finished. So cancelling a 300 s backtest freed+ // nothing: the job stayed "running" for the full budget and the model+ // kept polling a job it had explicitly given up on.+ //+ // Watching the flag here resolves the promise as soon as it flips, for+ // every async tool, with no handler cooperation. Be precise about what+ // that buys: it ends the CALL, not the work. The handler keeps running+ // until it finishes or the watchdog fires, and its late resolve() is+ // absorbed by the single-winner guard. What the user gets back is the+ // turn, the job slot, and an honest terminal state — which is the part+ // that was missing. Killing the underlying process needs a cancellation+ // handle on the service doing the work (PythonRunner has none today).+ //+ // Only armed when the caller can actually cancel, so the ~800 tools that+ // never run under a job pay nothing.+ if (caller_can_cancel) {+ auto* cancel_watch = new QTimer;+ cancel_watch->setInterval(kCancelPollMs);+ cancel_watch->moveToThread(qApp->thread());+ auto is_cancelled = ctx.is_cancelled; // composed hook: internal flag OR caller's+ QObject::connect(cancel_watch, &QTimer::timeout, cancel_watch,+ [cancel_watch, resolve, resolved, is_cancelled, name]() {+ // Resolved by anyone (handler, watchdog, us) — stand down.+ if (resolved->load()) {+ cancel_watch->stop();+ cancel_watch->deleteLater();+ return;+ }+ if (!is_cancelled())+ return;+ cancel_watch->stop();+ cancel_watch->deleteLater();+ LOG_INFO(TAG, QString("Tool '%1' cancelled — releasing the call; the handler "+ "runs on until it finishes or times out")+ .arg(name));+ resolve(ToolResult::fail("cancelled"));+ });+ QMetaObject::invokeMethod(+ cancel_watch, [cancel_watch]() { cancel_watch->start(); }, Qt::QueuedConnection);+ }+try {LOG_DEBUG(TAG, "Calling async tool: " + name);async_handler(normalized, ctx, promise);diff --git a/fincept-qt/src/mcp/McpProvider.h b/fincept-qt/src/mcp/McpProvider.hindex b3f962215..f0fa41f94 100644--- a/fincept-qt/src/mcp/McpProvider.h+++ b/fincept-qt/src/mcp/McpProvider.h@@ -57,6 +57,9 @@ class McpProvider {QString description;bool has_handler = false; // sync OR async handler is setbool is_async = false; // async_handler is set+ int default_timeout_ms = kMcpDefaultTimeoutMs;+ bool supports_async = false; // the explicit override flag, not the derived verdict+ bool job_eligible = false; // what supports_async_jobs() would answerbool enabled = true;bool is_destructive = false;AuthLevel auth_required = AuthLevel::None;@@ -113,10 +116,17 @@ class McpProvider {/// they report through `ctx.on_progress` shows up in `job_status`.ToolResult call_tool_or_defer(const QString& name, const QJsonObject& args, int grace_ms = kMcpJobGraceMs);- /// True if `name` is registered, enabled, and eligible for the job protocol- /// (opted in AND has an async handler — a sync handler can't be backgrounded).+ /// True if `name` is registered, enabled, and eligible for the job protocol.+ ///+ /// Requires an async handler (a sync one can't be backgrounded), plus+ /// either an explicit `supports_async` or a `default_timeout_ms` above+ /// `kMcpAsyncJobThresholdMs` — raising the budget IS the opt-in.bool supports_async_jobs(const QString& name) const;+ /// The tool's declared hard budget, or the 30 s default if unknown.+ /// Recorded on the job so `job_status` can report elapsed against it.+ int effective_timeout_ms(const QString& name) const;+// ── Phase 6.3: Authorization hook ──────────────────────────────────────/// Caller-supplied predicate that returns true iff the call should/// proceed. The hook receives the tool's required AuthLevel anddiff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cppindex 0a7479d65..55f10205b 100644--- a/fincept-qt/src/mcp/McpService.cpp+++ b/fincept-qt/src/mcp/McpService.cpp@@ -543,6 +543,18 @@ std::size_t McpService::tool_count() {return get_all_tools().size();}+QJsonObject McpService::input_schema_for_function(const QString& function_name) {+ auto [server_id, tool_name] = McpProvider::parse_openai_function_name(function_name);+ if (server_id.isEmpty() || tool_name.isEmpty())+ return {};+ QMutexLocker lock(&mutex_);+ for (const auto& t : cached_tools_locked()) {+ if (t.server_id == server_id && t.name == tool_name)+ return t.input_schema;+ }+ return {};+}+// ============================================================================// Tool Execution// ============================================================================diff --git a/fincept-qt/src/mcp/McpService.h b/fincept-qt/src/mcp/McpService.hindex c1b0f64bb..80d237e63 100644--- a/fincept-qt/src/mcp/McpService.h+++ b/fincept-qt/src/mcp/McpService.h@@ -64,6 +64,14 @@ class McpService {std::size_t tool_count();+ /// The UNSANITISED input schema for a wire function name ("serverId__tool"),+ /// or an empty object when no such tool is registered.+ ///+ /// Needed by the Gemini path: its declarations carry a lossy translation of+ /// the schema (see mcp/GeminiSchema.h), so the arguments that come back have+ /// to be reconciled against the original before dispatch.+ QJsonObject input_schema_for_function(const QString& function_name);+// ── Unified Tool Execution ──────────────────────────────────────────/// Route to internal or external server.diff --git a/fincept-qt/src/mcp/McpTypes.h b/fincept-qt/src/mcp/McpTypes.hindex 55785126d..bc58cbeaa 100644--- a/fincept-qt/src/mcp/McpTypes.h+++ b/fincept-qt/src/mcp/McpTypes.h@@ -10,6 +10,7 @@#include <QString>#include <QStringList>+#include <atomic>#include <functional>#include <memory>#include <optional>@@ -28,6 +29,12 @@ constexpr int kMcpDefaultTimeoutMs = 30000;/// Overridable via the `mcp/job_grace_ms` setting.constexpr int kMcpJobGraceMs = 2500;+/// A tool whose declared `default_timeout_ms` exceeds this is treated as+/// job-eligible without setting `ToolDef::supports_async` (see the note there).+/// Equal to the default timeout on purpose: a tool that kept the default has+/// said nothing about being slow, while one that raised it has.+constexpr int kMcpAsyncJobThresholdMs = kMcpDefaultTimeoutMs;+// ============================================================================// Tool Result — returned by tool handlers// ============================================================================@@ -118,6 +125,24 @@ struct ToolContext {/// ToolDef::default_timeout_ms; per-call override via _meta.timeout_ms.int timeout_ms = kMcpDefaultTimeoutMs;+ /// The single-winner guard for resolving this call's promise. Set by+ /// `McpProvider::call_tool_async`; may be null for a hand-built context.+ ///+ /// A promise must be finished exactly once, and THREE things can want to+ /// finish this one: the handler, the timeout watchdog, and the cancellation+ /// watch. They run on different threads, so "is it finished yet?" is not a+ /// usable test — two of them can read "no" and both call addResult(), with+ /// the loser writing after finish(), which Qt asserts on.+ ///+ /// The provider and `AsyncDispatch` each used to make their own guard over+ /// the same promise, which is not a guard at all: two independent+ /// compare-exchanges each let exactly one of THEIR OWN contenders through,+ /// so the watchdog and a late service callback could still both win. That+ /// race needs a slow tool and a timeout landing together to show up, which+ /// is precisely the workload the job protocol exists for. Sharing one flag+ /// through the context makes all three contenders race the same atomic.+ std::shared_ptr<std::atomic<bool>> resolve_guard;+/// Convenience — true if cancellation hook is set AND signalled.bool cancelled() const { return is_cancelled && is_cancelled(); }};@@ -314,6 +339,19 @@ struct ToolDef {////// Requires `async_handler` — a sync handler cannot be interrupted or/// backgrounded, so the flag is ignored for those.+ ///+ /// USUALLY YOU DO NOT NEED TO SET THIS. Eligibility is *derived* from+ /// `default_timeout_ms` (see `kMcpAsyncJobThresholdMs`): a tool that+ /// declares a budget longer than the default 30 s has already said its p95+ /// is tens of seconds, so it opts in automatically. The flag was+ /// hand-maintained for a while and reached 12 of the ~125 tools that+ /// qualified — the other ~113, including 97 AI Quant Lab tools carrying a+ /// 300 s budget, blocked the provider's HTTP turn for their full timeout+ /// with no receipt and no progress. Deriving it removes the second place+ /// the same fact had to be written down.+ ///+ /// Set it explicitly only for a tool that is slow in practice but declares+ /// a short nominal timeout — it is an override, never a requirement.bool supports_async = false;// ── Phase 6: Authorization ──────────────────────────────────────────diff --git a/fincept-qt/src/mcp/ProviderToolFormatSelfTest.cpp b/fincept-qt/src/mcp/ProviderToolFormatSelfTest.cppindex 375dd373a..b963f9160 100644--- a/fincept-qt/src/mcp/ProviderToolFormatSelfTest.cpp+++ b/fincept-qt/src/mcp/ProviderToolFormatSelfTest.cpp@@ -3,9 +3,11 @@#include "mcp/ProviderToolFormatSelfTest.h"#include "mcp/GeminiSchema.h"+#include "mcp/McpProvider.h"#include "mcp/McpService.h"#include "services/llm/ProviderCatalog.h"+#include <QHash>#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>@@ -14,6 +16,8 @@#include <QString>#include <QStringList>+#include <vector>+#include <cstdio>namespace fincept::mcp {@@ -98,6 +102,110 @@ void ptf_check_gemini_schema(const QJsonObject& schema, const QString& path, QSt}}+// ── Per-declaration checks, shared by the Tier-0 sections and the+// catalogue-wide sweep ──────────────────────────────────────────────────────+//+// Factored out rather than written twice on purpose. The Tier-0 sections and+// the sweep have to agree on what "valid" means: if they drift, the sweep stops+// being a superset and the coverage it exists to provide is imaginary.++// One OpenAI `tools[]` entry: {"type":"function","function":{name,description,parameters}}.+void ptf_check_openai_entry(const QJsonObject& entry, QSet<QString>* seen, QStringList* errs) {+ if (entry.value(QStringLiteral("type")).toString() != QLatin1String("function"))+ *errs << QStringLiteral("entry missing type=function");+ const QJsonObject fn = entry.value(QStringLiteral("function")).toObject();+ const QString name = fn.value(QStringLiteral("name")).toString();+ if (!ptf_openai_name_rx().match(name).hasMatch())+ *errs << QStringLiteral("'%1' violates ^[a-zA-Z0-9_-]{1,64}$").arg(name);+ if (seen) {+ if (seen->contains(name))+ *errs << QStringLiteral("duplicate function name '%1'").arg(name);+ seen->insert(name);+ }+ if (fn.value(QStringLiteral("description")).toString().trimmed().isEmpty())+ *errs << QStringLiteral("'%1' has no description").arg(name);+ if (!fn.contains(QStringLiteral("parameters"))) {+ *errs << QStringLiteral("'%1' has no parameters object").arg(name);+ return;+ }+ // `parameters` is a JSON Schema object. OpenAI itself tolerates a bare+ // {"type":"object"}, but the OpenAI-compatible fleet (Kimi, Groq, MiniMax,+ // Ollama, …) is less forgiving, and every one of them is reached through+ // this same payload.+ const QJsonObject params = fn.value(QStringLiteral("parameters")).toObject();+ if (params.value(QStringLiteral("type")).toString() != QLatin1String("object"))+ *errs << QStringLiteral("'%1' parameters.type != object").arg(name);+ if (!params.contains(QStringLiteral("properties")))+ *errs << QStringLiteral("'%1' parameters has no properties map").arg(name);+}++// One Anthropic `tools[]` entry: bare {name, description, input_schema}.+void ptf_check_anthropic_entry(const QJsonObject& t, QSet<QString>* seen, QStringList* errs) {+ const QString name = t.value(QStringLiteral("name")).toString();+ if (!ptf_openai_name_rx().match(name).hasMatch())+ *errs << QStringLiteral("'%1' violates ^[a-zA-Z0-9_-]{1,64}$").arg(name);+ if (seen) {+ if (seen->contains(name))+ *errs << QStringLiteral("duplicate tool name '%1'").arg(name);+ seen->insert(name);+ }+ if (t.value(QStringLiteral("description")).toString().trimmed().isEmpty())+ *errs << QStringLiteral("'%1' has no description").arg(name);+ // Anthropic takes a bare tool object — an OpenAI-style+ // {"type":"function","function":{…}} wrapper is a 400.+ if (t.contains(QStringLiteral("type")) || t.contains(QStringLiteral("function")))+ *errs << QStringLiteral("'%1' carries an OpenAI-style wrapper").arg(name);+ const QJsonObject schema = t.value(QStringLiteral("input_schema")).toObject();+ if (schema.isEmpty())+ *errs << QStringLiteral("'%1' has no input_schema").arg(name);+ else if (schema.value(QStringLiteral("type")).toString() != QLatin1String("object"))+ *errs << QStringLiteral("'%1' input_schema.type != object").arg(name);+ else if (!schema.contains(QStringLiteral("properties")))+ *errs << QStringLiteral("'%1' input_schema has no properties map").arg(name);+}++// One Gemini `functionDeclarations[]` entry: {name, description, parameters?}.+// `parameters` is legitimately absent for a parameterless tool.+void ptf_check_gemini_decl(const QJsonObject& d, QSet<QString>* seen, QStringList* errs) {+ const QString name = d.value(QStringLiteral("name")).toString();+ if (!is_valid_gemini_function_name(name))+ *errs << QStringLiteral("'%1' violates ^[a-zA-Z_][a-zA-Z0-9_.:-]{0,63}$").arg(name);+ if (seen) {+ if (seen->contains(name))+ *errs << QStringLiteral("duplicate function name '%1'").arg(name);+ seen->insert(name);+ }+ if (d.value(QStringLiteral("description")).toString().trimmed().isEmpty())+ *errs << QStringLiteral("'%1' has no description").arg(name);+ if (!d.contains(QStringLiteral("parameters")))+ return;+ const QJsonObject params = d.value(QStringLiteral("parameters")).toObject();+ if (params.value(QStringLiteral("type")).toString() != QLatin1String("object"))+ *errs << QStringLiteral("%1.parameters: top-level type must be OBJECT").arg(name);+ ptf_check_gemini_schema(params, name + QStringLiteral(".parameters"), errs);+}++// Every parameter a tool declares must still be reachable in the dialect's+// rendering of it. A dropped parameter is not a 400 — it is worse: the request+// succeeds and the model is simply never told the argument exists.+void ptf_check_params_survived(const QString& dialect, const QString& name, const QJsonObject& source_schema,+ const QJsonObject& rendered_params, bool params_present, QStringList* errs) {+ const QJsonObject src = source_schema.value(QStringLiteral("properties")).toObject();+ if (src.isEmpty())+ return; // genuinely parameterless+ if (!params_present) {+ *errs << QStringLiteral("%1/%2: declares %3 parameter(s) but the %1 payload carries none — the model "+ "would be told the tool takes no arguments")+ .arg(dialect, name, QString::number(src.size()));+ return;+ }+ const QJsonObject kept = rendered_params.value(QStringLiteral("properties")).toObject();+ for (auto it = src.constBegin(); it != src.constEnd(); ++it) {+ if (!kept.contains(it.key()))+ *errs << QStringLiteral("%1/%2: parameter '%3' was dropped in translation").arg(dialect, name, it.key());+ }+}+void ptf_report(const QString& label, const QStringList& errs, bool* failed) {if (errs.isEmpty()) {ptf_out(QStringLiteral(" OK ") + label);@@ -140,22 +248,8 @@ int run_provider_tool_format_selftest() {if (tools.isEmpty())errs << QStringLiteral("empty tool array — the model would have no tools at all");QSet<QString> seen;- for (const auto& v : tools) {- const QJsonObject e = v.toObject();- if (e.value(QStringLiteral("type")).toString() != QLatin1String("function"))- errs << QStringLiteral("entry missing type=function");- const QJsonObject fn = e.value(QStringLiteral("function")).toObject();- const QString name = fn.value(QStringLiteral("name")).toString();- if (!ptf_openai_name_rx().match(name).hasMatch())- errs << QStringLiteral("'%1' violates ^[a-zA-Z0-9_-]{1,64}$").arg(name);- if (seen.contains(name))- errs << QStringLiteral("duplicate function name '%1'").arg(name);- seen.insert(name);- if (fn.value(QStringLiteral("description")).toString().trimmed().isEmpty())- errs << QStringLiteral("'%1' has no description").arg(name);- if (!fn.contains(QStringLiteral("parameters")))- errs << QStringLiteral("'%1' has no parameters object").arg(name);- }+ for (const auto& v : tools)+ ptf_check_openai_entry(v.toObject(), &seen, &errs);ptf_report(QStringLiteral("openai payload"), errs, &failed);}@@ -167,23 +261,9 @@ int run_provider_tool_format_selftest() {QStringList errs;if (tools.isEmpty())errs << QStringLiteral("empty tool array — the model would have no tools at all");- for (const auto& v : tools) {- const QJsonObject t = v.toObject();- const QString name = t.value(QStringLiteral("name")).toString();- if (!ptf_openai_name_rx().match(name).hasMatch())- errs << QStringLiteral("'%1' violates ^[a-zA-Z0-9_-]{1,64}$").arg(name);- // Anthropic takes a bare tool object — an OpenAI-style- // {"type":"function","function":{…}} wrapper is a 400.- if (t.contains(QStringLiteral("type")) || t.contains(QStringLiteral("function")))- errs << QStringLiteral("'%1' carries an OpenAI-style wrapper").arg(name);- const QJsonObject schema = t.value(QStringLiteral("input_schema")).toObject();- if (schema.isEmpty())- errs << QStringLiteral("'%1' has no input_schema").arg(name);- else if (schema.value(QStringLiteral("type")).toString() != QLatin1String("object"))- errs << QStringLiteral("'%1' input_schema.type != object").arg(name);- else if (!schema.contains(QStringLiteral("properties")))- errs << QStringLiteral("'%1' input_schema has no properties map").arg(name);- }+ QSet<QString> seen;+ for (const auto& v : tools)+ ptf_check_anthropic_entry(v.toObject(), &seen, &errs);ptf_report(QStringLiteral("anthropic payload"), errs, &failed);// The whole point of routing Anthropic through the shared selector: it@@ -215,18 +295,12 @@ int run_provider_tool_format_selftest() {errs << QStringLiteral("%1 declarations exceeds Gemini's limit of 128").arg(decls.size());int with_params = 0;+ QSet<QString> seen;for (const auto& v : decls) {const QJsonObject d = v.toObject();- const QString name = d.value(QStringLiteral("name")).toString();- if (!is_valid_gemini_function_name(name))- errs << QStringLiteral("'%1' violates ^[a-zA-Z_][a-zA-Z0-9_.:-]{0,63}$").arg(name);- if (d.value(QStringLiteral("description")).toString().trimmed().isEmpty())- errs << QStringLiteral("'%1' has no description").arg(name);- if (d.contains(QStringLiteral("parameters"))) {+ if (d.contains(QStringLiteral("parameters")))++with_params;- ptf_check_gemini_schema(d.value(QStringLiteral("parameters")).toObject(),- name + QStringLiteral(".parameters"), &errs);- }+ ptf_check_gemini_decl(d, &seen, &errs);}ptf_out(QStringLiteral(" %1 with parameters, %2 parameterless (parameters omitted, as Gemini requires)").arg(with_params)@@ -243,8 +317,11 @@ int run_provider_tool_format_selftest() {QStringList errs;// Parameterless tool → no usable schema, caller must omit `parameters`.+ // TOP level only: `parameters` must be an OBJECT, so there is nothing to+ // substitute into and the caller has to omit the field. (A NESTED empty+ // object is a free-form bag and becomes a STRING -- checked below.)if (sanitize_schema_for_gemini(QJsonObject{{"type", "object"}, {"properties", QJsonObject{}}}).has_value())- errs << QStringLiteral("empty-properties object should sanitise to nullopt");+ errs << QStringLiteral("top-level empty-properties object should sanitise to nullopt");// JSON Schema keywords with no Gemini equivalent must be dropped, not forwarded.const QJsonObject noisy{@@ -265,8 +342,14 @@ int run_provider_tool_format_selftest() {} else {ptf_check_gemini_schema(*cleaned, QStringLiteral("noisy"), &errs);const QJsonObject props = cleaned->value(QStringLiteral("properties")).toObject();- if (props.contains(QStringLiteral("empty")))- errs << QStringLiteral("property with an unusable object schema should have been dropped");+ // A nested object with no declared properties is a FREE-FORM bag,+ // not a broken schema. Gemini cannot express one, so it must be+ // carried as a JSON-bearing STRING rather than dropped -- dropping+ // it removes the parameter from the model's reach entirely.+ if (props.value(QStringLiteral("empty")).toObject().value(QStringLiteral("type")).toString() !=+ QLatin1String("string")) {+ errs << QStringLiteral("free-form object property should become a STRING surrogate, not vanish");+ }if (!props.value(QStringLiteral("tags")).toObject().contains(QStringLiteral("items")))errs << QStringLiteral("ARRAY property should have been given a default 'items'");if (props.value(QStringLiteral("sym")).toObject().contains(QStringLiteral("format")))@@ -277,8 +360,11 @@ int run_provider_tool_format_selftest() {r << v.toString();return r;}();- if (req.contains(QStringLiteral("ghost")) || req.contains(QStringLiteral("empty")))+ // `ghost` was never a property; `empty` still is one (as a STRING).+ if (req.contains(QStringLiteral("ghost")))errs << QStringLiteral("'required' still names a property that is not declared: ") + req.join(',');+ if (!req.contains(QStringLiteral("empty")))+ errs << QStringLiteral("'required' dropped a free-form object parameter that is still declared");}// A ["string","null"] union is legal JSON Schema and illegal here.@@ -299,6 +385,180 @@ int run_provider_tool_format_selftest() {ptf_report(QStringLiteral("sanitiser behaviour"), errs, &failed);}+ // -- Catalogue-wide sweep, all three dialects ------------------------+ //+ // Sections [1]-[3] only ever see Tier-0 plus a couple of activated tools --+ // ~14 of a ~926 tool catalogue. But Tool RAG hands the model ANY tool it+ // discovers, and that tool's declaration then rides in the next round's+ // payload, so a declaration only reachable after tool_list is exactly as+ // fatal as a Tier-0 one. It was never checked, and that is how 149 tools+ // came to lose parameters on Gemini while this suite stayed green.+ //+ // The sweep drives the REAL formatters rather than re-deriving what they+ // ought to emit -- a test that reimplements the thing it checks agrees with+ // its own bugs. Each dialect caps its array (Gemini at 128, the others at+ // 256), so the catalogue goes through in chunks: an anchored alternation of+ // exact names makes the filter non-default, which also bypasses Tier-0.+ {+ const std::vector<UnifiedTool> all = svc.get_all_tools();+ ptf_out(QStringLiteral("\n[5] CATALOGUE SWEEP, ALL DIALECTS - %1 tools").arg(all.size()));++ // Wire name -> source schema, for the parameter-survival check.+ QHash<QString, QJsonObject> source_schema;+ QStringList every_name;+ for (const auto& t : all) {+ source_schema.insert(t.server_id + QStringLiteral("__") ++ McpProvider::encode_tool_name_for_wire(t.name),+ t.input_schema);+ every_name << QRegularExpression::escape(t.name);+ }++ constexpr int kChunk = 100; // comfortably under the tightest dialect cap (128)+ QStringList oai_errs, ant_errs, gem_errs;+ QSet<QString> oai_seen, ant_seen, gem_seen;+ int oai_n = 0, ant_n = 0, gem_n = 0, gem_with_params = 0;++ for (int off = 0; off < every_name.size(); off += kChunk) {+ const QStringList names = every_name.mid(off, kChunk);+ ToolFilter f;+ f.name_patterns = QStringList{QStringLiteral("^(?:") + names.join(QLatin1Char('|')) ++ QStringLiteral(")$")};+ f.max_tools = kChunk * 4; // above the chunk size; the dialect cap still applies++ const QJsonArray oai = svc.format_tools_for_openai(f);+ if (oai.size() != names.size()) {+ oai_errs << QStringLiteral("chunk at %1: asked for %2 tools, payload carried %3")+ .arg(off)+ .arg(names.size())+ .arg(oai.size());+ }+ for (const auto& v : oai) {+ const QJsonObject e = v.toObject();+ ptf_check_openai_entry(e, &oai_seen, &oai_errs);+ const QJsonObject fn = e.value(QStringLiteral("function")).toObject();+ const QString name = fn.value(QStringLiteral("name")).toString();+ ptf_check_params_survived(QStringLiteral("openai"), name, source_schema.value(name),+ fn.value(QStringLiteral("parameters")).toObject(),+ fn.contains(QStringLiteral("parameters")), &oai_errs);+ ++oai_n;+ }++ const QJsonArray ant = svc.format_tools_for_anthropic(f);+ if (ant.size() != oai.size())+ ant_errs << QStringLiteral("chunk at %1: anthropic %2 vs openai %3 -- selection diverged")+ .arg(off)+ .arg(ant.size())+ .arg(oai.size());+ for (const auto& v : ant) {+ const QJsonObject t = v.toObject();+ ptf_check_anthropic_entry(t, &ant_seen, &ant_errs);+ const QString name = t.value(QStringLiteral("name")).toString();+ ptf_check_params_survived(QStringLiteral("anthropic"), name, source_schema.value(name),+ t.value(QStringLiteral("input_schema")).toObject(), true, &ant_errs);+ ++ant_n;+ }++ const QJsonArray gem_tools = svc.format_tools_for_gemini(f);+ const QJsonArray decls =+ gem_tools.isEmpty()+ ? QJsonArray{}+ : gem_tools[0].toObject().value(QStringLiteral("functionDeclarations")).toArray();+ if (decls.size() != oai.size()) {+ gem_errs << QStringLiteral("chunk at %1: gemini %2 vs openai %3 -- declarations were dropped")+ .arg(off)+ .arg(decls.size())+ .arg(oai.size());+ }+ for (const auto& v : decls) {+ const QJsonObject d = v.toObject();+ ptf_check_gemini_decl(d, &gem_seen, &gem_errs);+ const QString name = d.value(QStringLiteral("name")).toString();+ const bool has_params = d.contains(QStringLiteral("parameters"));+ if (has_params)+ ++gem_with_params;+ ptf_check_params_survived(QStringLiteral("gemini"), name, source_schema.value(name),+ d.value(QStringLiteral("parameters")).toObject(), has_params, &gem_errs);+ ++gem_n;+ }+ }++ ptf_out(QStringLiteral(" openai %1 | anthropic %2 | gemini %3 (%4 with parameters)")+ .arg(oai_n)+ .arg(ant_n)+ .arg(gem_n)+ .arg(gem_with_params));+ ptf_report(QStringLiteral("openai catalogue sweep"), oai_errs, &failed);+ ptf_report(QStringLiteral("anthropic catalogue sweep"), ant_errs, &failed);+ ptf_report(QStringLiteral("gemini catalogue sweep"), gem_errs, &failed);+ }++ // -- Free-form object round-trip -------------------------------------+ // Gemini has no `additionalProperties` and rejects an OBJECT with an empty+ // `properties` map, so "an object with arbitrary keys" is inexpressible.+ // Such a parameter goes out as a JSON-carrying STRING and must come back an+ // object before dispatch - otherwise `args["params"].toObject()` is `{}` and+ // the tool runs on nothing.+ {+ ptf_out(QStringLiteral("\n[6] GEMINI FREE-FORM OBJECT ROUND-TRIP"));+ QStringList errs;++ // This is the exact shape of the ~115 catalog-driven quant tools.+ const QJsonObject schema{+ {"type", "object"},+ {"properties",+ QJsonObject{+ {"module_id", QJsonObject{{"type", "string"}}},+ {"params", QJsonObject{{"type", "object"}, {"description", "Module-specific arguments object"}}},+ {"rows", QJsonObject{{"type", "array"}, {"items", QJsonObject{{"type", "object"}}}}},+ }},+ {"required", QJsonArray{"module_id"}}};++ const auto out = sanitize_schema_for_gemini(schema);+ if (!out) {+ errs << QStringLiteral("schema sanitised away entirely");+ } else {+ const QJsonObject props = out->value(QStringLiteral("properties")).toObject();+ if (!props.contains(QStringLiteral("params")))+ errs << QStringLiteral("free-form object parameter was dropped instead of substituted");+ else if (props.value(QStringLiteral("params")).toObject().value(QStringLiteral("type")).toString() !=+ QLatin1String("string"))+ errs << QStringLiteral("free-form object parameter must be declared as STRING");+ if (!props.contains(QStringLiteral("rows")))+ errs << QStringLiteral("array-of-free-form-objects parameter was dropped");+ ptf_check_gemini_schema(*out, QStringLiteral("freeform"), &errs);+ }++ // What the model sends back, and what the handler must receive.+ const QJsonObject restored = restore_gemini_call_args(+ schema, QJsonObject{{"module_id", "backtesting"},+ {"params", "{\"symbol\":\"AAPL\",\"lookback\":30}"},+ {"rows", "[{\"a\":1}]"}});+ const QJsonObject rp = restored.value(QStringLiteral("params")).toObject();+ if (rp.value(QStringLiteral("symbol")).toString() != QLatin1String("AAPL") ||+ rp.value(QStringLiteral("lookback")).toInt() != 30) {+ errs << QStringLiteral("serialised object argument did not parse back into an object");+ }+ const QJsonArray rr = restored.value(QStringLiteral("rows")).toArray();+ if (rr.size() != 1 || rr[0].toObject().value(QStringLiteral("a")).toInt() != 1)+ errs << QStringLiteral("serialised array argument did not parse back into an array");+ if (restored.value(QStringLiteral("module_id")).toString() != QLatin1String("backtesting"))+ errs << QStringLiteral("a plain string argument must pass through untouched");++ // A model that gets it right anyway, and a model that sends junk: the+ // first must be left alone, the second must reach the argument+ // validator unchanged rather than being swallowed here.+ const QJsonObject already_ok =+ restore_gemini_call_args(schema, QJsonObject{{"params", QJsonObject{{"symbol", "MSFT"}}}});+ if (already_ok.value(QStringLiteral("params")).toObject().value(QStringLiteral("symbol")).toString() !=+ QLatin1String("MSFT"))+ errs << QStringLiteral("a correctly-typed object argument must pass through untouched");+ const QJsonObject garbage = restore_gemini_call_args(schema, QJsonObject{{"params", "not json"}});+ if (!garbage.value(QStringLiteral("params")).isString())+ errs << QStringLiteral("an unparseable argument must be left for the validator to reject");++ ptf_report(QStringLiteral("free-form object handling"), errs, &failed);+ }+// ── Endpoint composition ────────────────────────────────────────────// A tool payload is only half the contract; it still has to reach the// route that speaks that dialect. Gemini is the trap: its body is the only@@ -307,7 +567,7 @@ int run_provider_tool_format_selftest() {// 400s — tools included. ProviderCatalog::chat_endpoint mirrors// LlmService::get_endpoint_url; both must agree with these cases.{- ptf_out(QStringLiteral("\n[5] ENDPOINT COMPOSITION"));+ ptf_out(QStringLiteral("\n[7] ENDPOINT COMPOSITION"));QStringList errs;struct Case {const char* provider;@@ -346,6 +606,45 @@ int run_provider_tool_format_selftest() {}}ptf_report(QStringLiteral("chat endpoint per provider"), errs, &failed);++ // Every provider the LLM Config screen can select must resolve to an+ // endpoint from its own defaults, with no base_url typed in. Two of+ // them (AstraFlow, AstraFlow CN) carry their host in+ // `default_base_url` rather than in the switch above, and were reachable+ // only because the screen prefills that value -- clearing the field+ // dropped them to "No endpoint URL for provider". Enumerating+ // known_providers() rather than a hand-listed set is the point: a+ // provider added later is covered the day it is added.+ QStringList coverage;+ for (const QString& prov : ai_chat::ProviderCatalog::known_providers()) {+ if (prov == QLatin1String("fincept"))+ continue; // route is AppConfig::api_base_url() + "/research/chat", composed by the caller+ const QString url =+ ai_chat::ProviderCatalog::chat_endpoint(prov, QString(), QStringLiteral("test-model"));+ if (url.isEmpty()) {+ coverage << QStringLiteral("%1: no endpoint with default settings").arg(prov);+ continue;+ }+ if (!url.startsWith(QLatin1String("http")))+ coverage << QStringLiteral("%1: endpoint is not an http(s) URL: %2").arg(prov, url);+ // The dialect the body will be built in has to match the route it is+ // posted to. Gemini is the only non-OpenAI-shaped body.+ const bool gemini_route = url.contains(QLatin1String(":generateContent"));+ const bool gemini_provider = (prov == QLatin1String("gemini") || prov == QLatin1String("google"));+ if (gemini_route != gemini_provider) {+ coverage << QStringLiteral("%1: dialect/route mismatch -- %2")+ .arg(prov, gemini_route ? QStringLiteral("native Gemini route for a non-Gemini "+ "provider")+ : QStringLiteral("OpenAI-compat route for Gemini"));+ }+ if (!gemini_provider) {+ const QString want = (prov == QLatin1String("anthropic")) ? QStringLiteral("/messages")+ : QStringLiteral("/chat/completions");+ if (!url.endsWith(want))+ coverage << QStringLiteral("%1: endpoint does not end in %2: %3").arg(prov, want, url);+ }+ }+ ptf_report(QStringLiteral("every known provider resolves an endpoint"), coverage, &failed);}ptf_out(QStringLiteral("\n--------------------------------------------------------------"));diff --git a/fincept-qt/src/mcp/ToolSelfTest.cpp b/fincept-qt/src/mcp/ToolSelfTest.cppindex ac496b786..f0114d0bb 100644--- a/fincept-qt/src/mcp/ToolSelfTest.cpp+++ b/fincept-qt/src/mcp/ToolSelfTest.cpp@@ -2,11 +2,15 @@#include "mcp/ToolSelfTest.h"+#include "mcp/JobRegistry.h"+#include "services/llm/LlmRequestPolicy.h"+#include "mcp/McpProvider.h"#include "mcp/ToolRetriever.h"#include <QHash>#include <QJsonArray>+#include <QElapsedTimer>#include <QJsonDocument>#include <QJsonObject>#include <QRegularExpression>@@ -15,6 +19,7 @@#include <algorithm>#include <cstdio>+#include <utility>#include <vector>namespace fincept::mcp {@@ -210,7 +215,9 @@ int run_tool_selftest() {QStringList bad_schema; // CRITICAL — required param not declaredQStringList thin_desc; // WARN — retrieval-poisonQStringList destructive_miss; // WARN — mutating verb but not flagged destructive+ QStringList blocking_slow; // CRITICAL — slow tool that can't be backgroundedQHash<QString, QStringList> by_desc; // duplicate-description detection+ int job_eligible_count = 0;static const QRegularExpression mutating_rx(QStringLiteral("(?:^|_)(delete|remove|cancel|close|clear|wipe|drop|reset|unregister)(?:_|$)"),@@ -243,6 +250,27 @@ int run_tool_selftest() {if (mutating_rx.match(t.name).hasMatch() && !t.is_destructive)destructive_miss << t.name;+ // §M1: a tool whose declared budget exceeds the 30 s default has said+ // its p95 is tens of seconds, so it MUST be backgroundable — otherwise+ // an LLM call to it holds the provider's HTTP turn open for the full+ // budget with no receipt to poll and no way to cancel. The only way to+ // fail this is a sync-only handler, which cannot be observed or+ // interrupted: the fix is to give the tool an async handler, not to+ // lower its timeout.+ if (t.job_eligible) {+ ++job_eligible_count;+ } else if (t.default_timeout_ms > kMcpAsyncJobThresholdMs && t.has_handler &&+ !t.name.startsWith(QLatin1String("job_"))) {+ // The `job_*` meta-tools are the one principled exception, and the+ // reason is worth stating: `job_status` carries a 35 s budget purely+ // because it LONG-POLLS another job. Backgrounding it would mean+ // starting a job to watch a job, and the model would then have to+ // poll the poll. Their budget is a waiting period, not work.+ blocking_slow << QStringLiteral("%1 (%2 ms budget, sync-only handler)")+ .arg(t.name)+ .arg(t.default_timeout_ms);+ }+const QString key = t.description.trimmed().toLower();if (!key.isEmpty())by_desc[key] << t.name;@@ -263,6 +291,8 @@ int run_tool_selftest() {report_list(QStringLiteral("tools with invalid schema"), bad_schema, true);report_list(QStringLiteral("tools with thin description (<20 chars)"), thin_desc, false);report_list(QStringLiteral("mutating tools NOT flagged destructive"), destructive_miss, false);+ report_list(QStringLiteral("slow tools that CANNOT be backgrounded"), blocking_slow, true);+ out(QStringLiteral(" ✓ tools eligible for the async job protocol: ") + QString::number(job_eligible_count));QStringList dup_desc;for (auto it = by_desc.cbegin(); it != by_desc.cend(); ++it) {@@ -319,6 +349,139 @@ int run_tool_selftest() {out(w);}+ // — Part 3: async job lifecycle ———+ //+ // The registry is what makes a long-running tool observable and+ // interruptible, and until now nothing exercised it. Every assertion here+ // is a property the model depends on when it is holding a receipt: that a+ // long-poll actually blocks, that progress survives, that a cancelled job+ // reaches a terminal state, and that a result can be collected exactly once.+ {+ out(QStringLiteral("\n[3] ASYNC JOB LIFECYCLE"));+ QStringList errs;+ auto& jobs = JobRegistry::instance();++ const QString id = jobs.create(QStringLiteral("__selftest_tool"), 90000);+ auto snap = jobs.status(id);+ if (!snap)+ errs << QStringLiteral("a job disappeared immediately after create()");+ else {+ if (snap->state != JobState::Running)+ errs << QStringLiteral("a new job is not in the Running state");+ // The budget must reach the wire: elapsed without it is undecidable.+ const QJsonObject wire = snap->to_json();+ if (wire.value(QStringLiteral("timeout_ms")).toInt() != 90000)+ errs << QStringLiteral("job_status omits timeout_ms, leaving elapsed_ms uninterpretable");+ if (!wire.contains(QStringLiteral("elapsed_ms")))+ errs << QStringLiteral("job_status omits elapsed_ms");+ if (wire.contains(QStringLiteral("progress")))+ errs << QStringLiteral("a job with no reported progress must omit the field, not report 0");+ }++ jobs.set_progress(id, 0.42, QStringLiteral("halfway"));+ snap = jobs.status(id);+ if (!snap || snap->progress < 0.41 || snap->progress > 0.43)+ errs << QStringLiteral("reported progress did not reach the snapshot");+ if (snap && snap->message != QLatin1String("halfway"))+ errs << QStringLiteral("reported status message did not reach the snapshot");++ // A zero-wait poll must not block; a real wait must actually elapse+ // rather than returning instantly (that is what keeps a poll from+ // costing one tool round per second).+ QElapsedTimer t;+ t.start();+ jobs.wait_for(id, 0);+ if (t.elapsed() > 50)+ errs << QStringLiteral("wait_for(0) blocked; it must return immediately");+ t.restart();+ jobs.wait_for(id, 300);+ const qint64 waited = t.elapsed();+ if (waited < 250)+ errs << QStringLiteral("wait_for(300) returned after %1 ms without the job finishing").arg(waited);++ // Cancellation raises the flag but must NOT fake a terminal state: the+ // job stays Running until the work actually unwinds, otherwise the model+ // collects a result that was never produced.+ if (!jobs.request_cancel(id))+ errs << QStringLiteral("request_cancel refused a running job");+ if (!jobs.is_cancelled(id))+ errs << QStringLiteral("the cancellation flag did not latch");+ snap = jobs.status(id);+ if (snap && snap->state != JobState::Running)+ errs << QStringLiteral("cancel moved the job to a terminal state before the handler unwound");++ jobs.complete(id, ToolResult::ok(QStringLiteral("finished")));+ snap = jobs.status(id);+ if (!snap || !snap->is_finished())+ errs << QStringLiteral("complete() left the job running");+ if (auto r = jobs.take_result(id)) {+ if (r->message != QLatin1String("finished"))+ errs << QStringLiteral("take_result returned a different payload than was stored");+ } else {+ errs << QStringLiteral("take_result found nothing after complete()");+ }+ // Completing twice is the watchdog/handler race; the second must lose.+ jobs.complete(id, ToolResult::fail(QStringLiteral("late loser")));+ if (auto r2 = jobs.take_result(id); r2 && r2->message != QLatin1String("finished"))+ errs << QStringLiteral("a second complete() overwrote the winning result");++ if (jobs.status(QStringLiteral("job_does_not_exist")).has_value())+ errs << QStringLiteral("an unknown job id returned a status");++ report_list(QStringLiteral("job lifecycle failures"), errs, true);+ }++ // — Part 4: tool-call batch planning ———+ //+ // Ordering is the one property of parallel execution that no compiler and+ // no smoke test will catch: get it wrong and a write silently overtakes a+ // read, occasionally, in production. The rule is that a destructive call is+ // a barrier, so these cases pin the shape exactly.+ {+ out(QStringLiteral("\n[4] TOOL-CALL BATCH PLANNING"));+ QStringList errs;+ using Batches = std::vector<std::pair<std::size_t, std::size_t>>;++ auto describe = [](const Batches& b) {+ QStringList parts;+ for (const auto& [x, y] : b)+ parts << QStringLiteral("[%1,%2)").arg(x).arg(y);+ return parts.join(QLatin1Char(' '));+ };+ auto check = [&](const QString& label, const std::vector<bool>& destructive, int fanout,+ const Batches& want) {+ const Batches got = ai_chat::detail::plan_tool_batches(destructive, fanout);+ if (got != want) {+ errs << QStringLiteral("%1: got %2, expected %3").arg(label, describe(got), describe(want));+ return;+ }+ // Whatever the plan, it must cover every call exactly once and in+ // order — that is what keeps results index-aligned.+ std::size_t cursor = 0;+ for (const auto& [x, y] : got) {+ if (x != cursor || y <= x)+ errs << QStringLiteral("%1: batches are not a contiguous ordered cover").arg(label);+ cursor = y;+ }+ if (cursor != destructive.size())+ errs << QStringLiteral("%1: batches do not cover every call").arg(label);+ };++ check(QStringLiteral("all read-only fan out together"), {false, false, false}, 4, {{0, 3}});+ check(QStringLiteral("fanout caps the batch"), {false, false, false, false, false}, 2,+ {{0, 2}, {2, 4}, {4, 5}});+ check(QStringLiteral("fanout=1 is fully sequential"), {false, false, false}, 1, {{0, 1}, {1, 2}, {2, 3}});+ check(QStringLiteral("a destructive call runs alone"), {true}, 4, {{0, 1}});+ // The case that matters: a write must not be overtaken by the read after+ // it, nor overtake the read before it.+ check(QStringLiteral("a write is a barrier"), {false, false, true, false, false}, 4,+ {{0, 2}, {2, 3}, {3, 5}});+ check(QStringLiteral("consecutive writes stay serial"), {true, true}, 4, {{0, 1}, {1, 2}});+ check(QStringLiteral("empty round plans nothing"), {}, 4, {});++ report_list(QStringLiteral("batch planning failures"), errs, true);+ }+out(QStringLiteral("\n──────────────────────────────────────────────────────────────"));out(QString(QStringLiteral(" recall@1 = %1 recall@5 = %2 MRR = %3")).arg(recall1, 0, 'f', 3)diff --git a/fincept-qt/src/mcp/tools/PythonTools.cpp b/fincept-qt/src/mcp/tools/PythonTools.cppindex d4becc2fe..9d8d3e6c1 100644--- a/fincept-qt/src/mcp/tools/PythonTools.cpp+++ b/fincept-qt/src/mcp/tools/PythonTools.cpp@@ -116,6 +116,10 @@ std::vector<ToolDef> get_python_tools() {auto* runner = &python::PythonRunner::instance();AsyncDispatch::callback_to_promise(runner, ctx, promise, [runner, script, script_args, ctx](auto resolve) {+ // Forward the script's own output as job progress. Under a job+ // this is the only thing that separates "still working" from+ // "hung": the tool is one opaque call, so its stdout is the+ // sole evidence anything is happening.runner->run(script, script_args, [resolve, ctx](python::PythonResult result) {if (ctx.cancelled()) {resolve(ToolResult::fail("cancelled"));@@ -140,7 +144,7 @@ std::vector<ToolDef> get_python_tools() {} else {resolve(ToolResult::ok(result.output));}- });+ }, AsyncDispatch::line_progress_bridge(ctx));});};tools.push_back(std::move(t));diff --git a/fincept-qt/src/mcp/tools/QuantLabTools.cpp b/fincept-qt/src/mcp/tools/QuantLabTools.cppindex 9257adf34..e3be975a2 100644--- a/fincept-qt/src/mcp/tools/QuantLabTools.cpp+++ b/fincept-qt/src/mcp/tools/QuantLabTools.cpp@@ -178,6 +178,14 @@ constexpr std::size_t kCatalogSize = sizeof(kCatalog) / sizeof(kCatalog[0]);void dispatch_quant_async(const QString& module_id, const QString& command, const QJsonObject& params, ToolContext ctx,std::shared_ptr<QPromise<ToolResult>> promise) {auto* svc = &services::quant::AIQuantLabService::instance();+ // Mark the handoff. These tools declare a 300 s budget, so under a job the+ // model can be polling for minutes; without this the snapshot says only+ // "running", which cannot distinguish work in flight from a dispatch that+ // never reached the service. The service reports no finer progress than+ // result/error, so this is the whole of the honest signal — one tick, not+ // a fabricated ramp.+ if (ctx.on_progress)+ ctx.on_progress(0.0, QStringLiteral("submitted to %1/%2").arg(module_id, command));AsyncDispatch::callback_to_promise(svc, std::move(ctx), promise, [svc, module_id, command, params](auto resolve) {auto* holder = new QObject(svc);QObject::connect(svc, &services::quant::AIQuantLabService::result_ready, holder,diff --git a/fincept-qt/src/screens/profile/ProfileScreen.cpp b/fincept-qt/src/screens/profile/ProfileScreen.cppindex 74e3facb0..afa17fd69 100644--- a/fincept-qt/src/screens/profile/ProfileScreen.cpp+++ b/fincept-qt/src/screens/profile/ProfileScreen.cpp@@ -906,23 +906,44 @@ void ProfileScreen::show_delete_account_dialog() {if (first != QMessageBox::Yes)return;- // Second confirmation — type email + enter password to confirm+ // Second confirmation — type email + enter password to confirm.+ //+ // The password gate used to be unsatisfiable for anyone who signed up via+ // Google: those accounts have no password, the DELETE button stayed+ // permanently disabled, and the dialog offered no way to set one. The+ // reset flow already existed (ForgotPasswordScreen) but was reachable only+ // from Login and Help — both pre-login surfaces — so a signed-in user+ // could not get to it at all. Hence "no input screen or text field is+ // displayed to enter the code" (issue #378).+ //+ // The fix does not try to detect an OAuth account: it can't. Neither+ // UserProfile nor the session carries an auth-provider or has-password+ // field, so the client has no way to know. Instead the set/reset path is+ // put inline here and offered to everyone — which serves the passwordless+ // Google user and the ordinary "I forgot it" user with one control, and+ // needs no new backend field. /user/forgot-password and+ // /user/reset-password are public, email-keyed endpoints, so they work+ // just as well while signed in.auto* dlg = new QDialog(this);dlg->setWindowTitle(tr("Confirm Account Deletion"));- dlg->setFixedSize(400, 260);+ dlg->setMinimumWidth(420);dlg->setStyleSheet(QString("background:%1;color:%2;font-family:'Consolas',monospace;").arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_PRIMARY()));auto* vl = new QVBoxLayout(dlg);vl->setContentsMargins(20, 16, 20, 16);vl->setSpacing(10);+ const QString danger_lbl_ss =+ QString("color:%1;font-size:11px;font-weight:700;background:transparent;").arg(ui::colors::NEGATIVE());+ const QString muted_lbl_ss =+ QString("color:%1;font-size:11px;background:transparent;").arg(ui::colors::TEXT_SECONDARY());+auto* warn = new QLabel(tr("TYPE YOUR EMAIL ADDRESS TO CONFIRM:"));- warn->setStyleSheet(- QString("color:%1;font-size:11px;font-weight:700;background:transparent;").arg(ui::colors::NEGATIVE()));+ warn->setStyleSheet(danger_lbl_ss);vl->addWidget(warn);auto* hint = new QLabel(email);- hint->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;").arg(ui::colors::TEXT_SECONDARY()));+ hint->setStyleSheet(muted_lbl_ss);vl->addWidget(hint);auto* input = new QLineEdit;@@ -931,8 +952,7 @@ void ProfileScreen::show_delete_account_dialog() {vl->addWidget(input);auto* pw_lbl = new QLabel(tr("ENTER YOUR PASSWORD:"));- pw_lbl->setStyleSheet(- QString("color:%1;font-size:11px;font-weight:700;background:transparent;").arg(ui::colors::NEGATIVE()));+ pw_lbl->setStyleSheet(danger_lbl_ss);vl->addWidget(pw_lbl);auto* pw_input = new QLineEdit;@@ -941,6 +961,79 @@ void ProfileScreen::show_delete_account_dialog() {pw_input->setPlaceholderText(tr("Current password"));vl->addWidget(pw_input);+ // ── Entry point into the inline set/reset flow ───────────────────────────+ auto* reset_link = new QPushButton(tr("Signed in with Google, or forgot your password? Email me a code"));+ reset_link->setFlat(true);+ reset_link->setCursor(Qt::PointingHandCursor);+ reset_link->setStyleSheet(QString("QPushButton{background:transparent;border:none;color:%1;font-size:11px;"+ "text-align:left;padding:0;font-family:'Consolas',monospace;}"+ "QPushButton:hover{color:%2;text-decoration:underline;}")+ .arg(ui::colors::INFO(), ui::colors::AMBER()));+ vl->addWidget(reset_link);++ // ── Reset panel: hidden until the link above is used ─────────────────────+ auto* reset_box = new QWidget;+ reset_box->setStyleSheet("background:transparent;");+ reset_box->setVisible(false);+ auto* rl = new QVBoxLayout(reset_box);+ rl->setContentsMargins(0, 4, 0, 0);+ rl->setSpacing(8);++ auto* sep = new QFrame;+ sep->setFrameShape(QFrame::HLine);+ sep->setStyleSheet(QString("background:%1;border:none;max-height:1px;").arg(ui::colors::BORDER_DIM()));+ rl->addWidget(sep);++ auto* code_lbl = new QLabel(tr("6-DIGIT CODE FROM YOUR EMAIL:"));+ code_lbl->setStyleSheet(danger_lbl_ss);+ rl->addWidget(code_lbl);++ auto* code_input = new QLineEdit;+ code_input->setFixedHeight(28);+ code_input->setPlaceholderText(tr("Verification code"));+ rl->addWidget(code_input);++ auto* new_pw_lbl = new QLabel(tr("NEW PASSWORD (MIN 8 CHARACTERS):"));+ new_pw_lbl->setStyleSheet(danger_lbl_ss);+ rl->addWidget(new_pw_lbl);++ auto* new_pw = new QLineEdit;+ new_pw->setFixedHeight(28);+ new_pw->setEchoMode(QLineEdit::Password);+ new_pw->setPlaceholderText(tr("New password"));+ rl->addWidget(new_pw);++ auto* confirm_pw = new QLineEdit;+ confirm_pw->setFixedHeight(28);+ confirm_pw->setEchoMode(QLineEdit::Password);+ confirm_pw->setPlaceholderText(tr("Confirm new password"));+ rl->addWidget(confirm_pw);++ auto* set_pw_btn = new QPushButton(tr("SET PASSWORD"));+ set_pw_btn->setFixedHeight(26);+ set_pw_btn->setStyleSheet(QString("QPushButton{background:%1;color:%2;border:none;padding:0 14px;"+ "font-size:11px;font-weight:700;font-family:'Consolas',monospace;}"+ "QPushButton:hover{background:#b45309;}")+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE()));+ rl->addWidget(set_pw_btn);+ vl->addWidget(reset_box);++ // Shared status line for both the code request and the reset itself.+ auto* status = new QLabel;+ status->setWordWrap(true);+ status->setStyleSheet(muted_lbl_ss);+ status->hide();+ vl->addWidget(status);++ auto say = [status, dlg](const QString& msg, const QString& color) {+ status->setStyleSheet(QString("color:%1;font-size:11px;background:transparent;").arg(color));+ status->setText(msg);+ status->show();+ // The dialog grows as the reset panel and status line appear; without+ // this it keeps its original height and clips them.+ dlg->adjustSize();+ };+auto* brl = new QHBoxLayout;brl->addStretch();auto* cancel = new QPushButton(tr("CANCEL"));@@ -963,6 +1056,76 @@ void ProfileScreen::show_delete_account_dialog() {connect(input, &QLineEdit::textChanged, this, [reeval](const QString&) { reeval(); });connect(pw_input, &QLineEdit::textChanged, this, [reeval](const QString&) { reeval(); });+ // Deliberately NOT captured as a local reference: the lambdas below+ // outlive this stack frame (they are owned by dlg, and a queued HTTP reply+ // can land after exec() returns but before deleteLater() runs), so they+ // call the singleton accessor themselves rather than hold a reference to+ // a local that has gone away.+ auto* auth_mgr = &auth::AuthManager::instance();++ // Reveal the panel and ask for a code in one click — the reporter's flow+ // was "click reset, then look for somewhere to type the code", so the+ // field has to be on screen by the time the email lands.+ connect(reset_link, &QPushButton::clicked, dlg, [reset_box, reset_link, code_input, say, email]() {+ reset_box->setVisible(true);+ reset_link->setText(tr("Re-send code"));+ code_input->setFocus();+ say(tr("Sending a verification code to %1 ...").arg(email), ui::colors::TEXT_SECONDARY());+ auth::AuthManager::instance().forgot_password(email);+ });++ // AuthManager's signals are global to the singleton; scoping every+ // connection to `dlg` means they die with the dialog rather than firing+ // into a destroyed lambda later.+ connect(auth_mgr, &auth::AuthManager::forgot_password_sent, dlg, [say, email]() {+ say(tr("Code sent to %1. Enter it above with a new password.").arg(email), ui::colors::POSITIVE());+ });+ connect(auth_mgr, &auth::AuthManager::forgot_password_failed, dlg,+ [say](const QString& err) { say(tr("Could not send code: %1").arg(err), ui::colors::NEGATIVE()); });++ connect(set_pw_btn, &QPushButton::clicked, dlg,+ [set_pw_btn, code_input, new_pw, confirm_pw, say, email]() {+ // Same rules as ForgotPasswordScreen::on_reset_password, so the+ // two paths can't disagree about what a valid password is.+ const QString otp = code_input->text().trimmed();+ if (otp.isEmpty()) {+ say(tr("Enter the verification code from your email"), ui::colors::NEGATIVE());+ code_input->setFocus();+ return;+ }+ if (new_pw->text().length() < 8) {+ say(tr("Password must be at least 8 characters"), ui::colors::NEGATIVE());+ new_pw->setFocus();+ return;+ }+ if (new_pw->text() != confirm_pw->text()) {+ confirm_pw->clear();+ say(tr("Passwords do not match"), ui::colors::NEGATIVE());+ confirm_pw->setFocus();+ return;+ }+ set_pw_btn->setEnabled(false);+ say(tr("Setting password ..."), ui::colors::TEXT_SECONDARY());+ auth::AuthManager::instance().reset_password(email, otp, new_pw->text());+ });++ connect(auth_mgr, &auth::AuthManager::password_reset_succeeded, dlg,+ [reset_box, reset_link, set_pw_btn, pw_input, new_pw, say, reeval]() {+ // Carry the new password straight into the delete field: the+ // user just typed it twice, and asking a third time to satisfy+ // a gate they only opened in order to delete is pure friction.+ pw_input->setText(new_pw->text());+ reset_box->setVisible(false);+ reset_link->hide();+ set_pw_btn->setEnabled(true);+ say(tr("Password set. You can now delete your account."), ui::colors::POSITIVE());+ reeval();+ });+ connect(auth_mgr, &auth::AuthManager::password_reset_failed, dlg, [set_pw_btn, say](const QString& err) {+ set_pw_btn->setEnabled(true);+ say(tr("Could not set password: %1").arg(err), ui::colors::NEGATIVE());+ });+QPointer<ProfileScreen> self = this;QPointer<QDialog> dlg_ptr = dlg;connect(confirm, &QPushButton::clicked, this, [self, dlg_ptr, email, pw_input]() {@@ -977,12 +1140,21 @@ void ProfileScreen::show_delete_account_dialog() {if (r.success) {LOG_INFO("Profile", "Account deleted successfully");auth::AuthManager::instance().logout();- } else {- LOG_ERROR("Profile", "Account deletion failed: " + r.error);- QMessageBox::critical(- self, tr("Delete Failed"),- tr("Account deletion failed: %1\n\nPlease contact [email protected]").arg(r.error));+ return;+ }+ // Never log r.error's context alongside the password; the error+ // string itself is server wording and safe.+ LOG_ERROR("Profile", "Account deletion failed: " + r.error);+ QString detail = r.error;+ if (r.status_code == 401) {+ // Resetting the password can invalidate the session that was+ // issued before it, so a 401 here is more likely "your session+ // is stale" than "wrong password" — say so rather than sending+ // the user round the password loop again.+ detail = tr("%1\n\nIf you just set a new password, sign out and back in, then retry.").arg(r.error);}+ QMessageBox::critical(self, tr("Delete Failed"),+ tr("Account deletion failed: %1\n\nPlease contact [email protected]").arg(detail));});});brl->addWidget(confirm);diff --git a/fincept-qt/src/services/llm/LlmRequestPolicy.h b/fincept-qt/src/services/llm/LlmRequestPolicy.hindex 8a8b82b7c..bd8ed2e42 100644--- a/fincept-qt/src/services/llm/LlmRequestPolicy.h+++ b/fincept-qt/src/services/llm/LlmRequestPolicy.h@@ -18,18 +18,28 @@#include "core/config/AppConfig.h"#include "core/logging/Logger.h"+#include "mcp/McpProvider.h"+#include "mcp/McpService.h"#include "mcp/McpTypes.h"#include "mcp/ResultStore.h"+#include "mcp/TerminalMcpBridge.h"#include "services/llm/LlmService.h"+#include <QElapsedTimer>+#include <QFuture>#include <QJsonArray>#include <QJsonDocument>#include <QJsonObject>#include <QSet>#include <QString>+#include <QtConcurrent>+#include <algorithm>+#include <cstddef>#include <functional>+#include <utility>+#include <vector>namespace fincept::ai_chat::detail {@@ -250,6 +260,77 @@ inline QString encode_tool_result_for_llm(const QString& tool_name, const mcp::T// capped at 20 and defaults to 5) while keeping the tail bounded.inline constexpr int kMaxActivatedTools = 24;+// —— Tool-loop budget ———+//+// `max_tool_rounds` bounds how many times the loop iterates, which is not the+// same as bounding how long it runs. One round can start a 300 s background+// job and long-poll it for 30 s, so the default 40 rounds is, in wall-clock+// terms, unbounded — and the user watching a chat bubble has no way to tell a+// working turn from a wedged one. The two budgets answer different questions+// and a loop needs both: rounds cap the token spend, the deadline caps the+// wait.+//+// Exhausting either is a normal outcome, not an error, but it must be VISIBLE.+// The loop used to stop and hand back whatever it had, so a turn that ran out+// of budget mid-task was indistinguishable from one that finished — the same+// failure shape as a silently truncated tool result (see §M4).++/// Wall-clock ceiling for one turn's tool loop, in ms. 0 disables it.+/// Ten minutes is well past any legitimate interactive turn while still short+/// enough that a stuck loop surfaces during the session rather than after it.+inline int tool_loop_deadline_ms() {+ return std::max(0, AppConfig::instance().get("mcp/tool_loop_deadline_ms", QVariant(600000)).toInt());+}++class ToolLoopBudget {+ public:+ explicit ToolLoopBudget(int max_rounds) : max_rounds_(max_rounds), deadline_ms_(tool_loop_deadline_ms()) {+ timer_.start();+ }++ /// Check at the top of every round, before issuing the next request.+ bool exhausted() const { return reason() != Reason::None; }++ void note_round() { ++rounds_; }+ int rounds_used() const { return rounds_; }+ qint64 elapsed_ms() const { return timer_.elapsed(); }++ /// One line naming which budget ran out and what it cost, for the log and+ /// for the model's final-summary prompt. Empty while the loop is healthy.+ QString exhaustion_note() const {+ switch (reason()) {+ case Reason::Rounds:+ return QStringLiteral("tool-call budget spent: %1 of %1 rounds used in %2 s")+ .arg(rounds_)+ .arg(elapsed_ms() / 1000);+ case Reason::Deadline:+ return QStringLiteral("time budget spent: %1 s elapsed (limit %2 s) after %3 round(s)")+ .arg(elapsed_ms() / 1000)+ .arg(deadline_ms_ / 1000)+ .arg(rounds_);+ case Reason::None:+ break;+ }+ return {};+ }++ private:+ enum class Reason { None, Rounds, Deadline };++ Reason reason() const {+ if (max_rounds_ > 0 && rounds_ >= max_rounds_)+ return Reason::Rounds;+ if (deadline_ms_ > 0 && timer_.elapsed() >= deadline_ms_)+ return Reason::Deadline;+ return Reason::None;+ }++ QElapsedTimer timer_;+ int max_rounds_ = 0;+ int deadline_ms_ = 0;+ int rounds_ = 0;+};+/// Insertion-ordered, capped set of tools the model has discovered this turn./// Evicts least-recently-activated first, so a tool the model keeps coming back/// to survives while stale candidates from an early search age out.@@ -304,4 +385,154 @@ inline void note_tool_activations(const QString& bare_tool_name, const QJsonObje}}++// —— Parallel tool execution ———+//+// A model that asks for six quotes emits six tool_calls in ONE assistant turn,+// and every loop here executed them one after another — six sequential round+// trips through Python or HTTP for work with no dependency between the calls.+// The async dispatcher built to fix that (McpService::execute_openai_function_async,+// "Phase 5 will join these with QtFuture::whenAll") had no callers at all.+//+// Two things stop this from being a plain std::transform over a thread pool:+//+// 1. ORDER IS OBSERVABLE. `is_destructive` tools mutate terminal state, and a+// round of [write_cell, read_cell] means something different if the read+// lands first. So a destructive call is a BARRIER: consecutive read-only+// calls fan out together, a destructive call runs alone, and the model's+// relative ordering is preserved exactly. Rounds that are all reads — the+// overwhelmingly common case — parallelise completely; a round with writes+// degrades gracefully toward sequential rather than reordering anything.+//+// 2. TOOLS READ THREAD-LOCAL STATE. The destructive-tool gate reads+// TerminalMcpBridge's thread_local flags, and four report-builder tools read+// `t_chat_session_id`. Both default to empty/false on a pool thread, which+// would silently reclassify an agent call as a chat call and detach report+// tools from their session. Every worker re-establishes both.+//+// Results come back index-aligned with the input, so callers append tool+// messages in the model's original order whatever order they finished in.++/// One tool call from a round, provider-agnostic.+struct PendingToolCall {+ QString wire_name; // "<server>__<tool>", as the model emitted it+ QString display; // bare name, for progress lines and activation tracking+ QJsonObject args;+ QString call_id; // tool_call_id / tool_use_id; opaque here, echoed by the caller+};++/// Max tool calls executed concurrently within one round. 1 restores the old+/// strictly-sequential behaviour and is the kill switch.+///+/// The default is deliberately low. PythonRunner caps itself at 3 concurrent+/// processes, so a wider fan-out on Python-backed tools just moves the queue+/// rather than shortening it, while still multiplying peak memory.+inline int tool_fanout() {+ return std::clamp(AppConfig::instance().get("mcp/tool_fanout", QVariant(4)).toInt(), 1, 16);+}++/// True if the tool mutates terminal state.+///+/// Resolved through `McpProvider::find_tool`, an O(1) snapshot lookup. The+/// obvious alternative — scanning `McpService::get_all_tools()` — returns the+/// whole catalogue BY VALUE, so a six-call round would copy 926 tool records,+/// each carrying a serialised JSON schema, six times over, to answer six+/// booleans.+///+/// `find_tool` only knows internal tools, and everything it does not know is+/// treated as destructive. That is the right default twice over: an+/// unrecognised name is more likely a stale alias than a proven read, and+/// external MCP tools are ALREADY gated destructive-by-default in+/// `McpService::execute_tool` because the MCP wire carries no destructiveness+/// metadata. Serialising them here matches the security posture they are+/// executed under. The cost is that a round of external calls does not fan+/// out; correctness first.+inline bool tool_is_destructive(const QString& wire_name) {+ const QString bare = mcp::McpProvider::parse_openai_function_name(wire_name).second;+ if (bare.isEmpty())+ return true;+ const auto t = mcp::McpProvider::instance().find_tool(bare);+ return t ? t->is_destructive : true;+}++/// Split a round into execution batches, preserving the model's ordering.+///+/// Each batch is a half-open `[begin, end)` range over the round's calls, and+/// batches run strictly in order. A batch with more than one element is safe to+/// run concurrently; a destructive call always lands in a batch of its own, so+/// nothing can overtake it and it can overtake nothing.+///+/// Pure and separated from execution because the ordering rule is the part that+/// can be wrong in a way no build error catches: get it subtly off and a write+/// silently overtakes a read, in production, occasionally. This shape is+/// exhaustively checked by the tool self-test.+inline std::vector<std::pair<std::size_t, std::size_t>> plan_tool_batches(const std::vector<bool>& destructive,+ int fanout) {+ std::vector<std::pair<std::size_t, std::size_t>> batches;+ const std::size_t n = destructive.size();+ std::size_t i = 0;+ while (i < n) {+ if (fanout <= 1 || destructive[i]) {+ batches.emplace_back(i, i + 1); // barrier, or fan-out disabled+ ++i;+ continue;+ }+ std::size_t end = i;+ while (end < n && static_cast<int>(end - i) < fanout && !destructive[end])+ ++end;+ batches.emplace_back(i, end);+ i = end;+ }+ return batches;+}++/// Execute one round's tool calls, honouring the ordering rules above.+/// Returns results index-aligned with `calls`.+inline std::vector<mcp::ToolResult> execute_tool_calls(const std::vector<PendingToolCall>& calls) {+ std::vector<mcp::ToolResult> out(calls.size());+ if (calls.empty())+ return out;++ std::vector<bool> destructive;+ destructive.reserve(calls.size());+ for (const auto& c : calls)+ destructive.push_back(tool_is_destructive(c.wire_name));+ const auto batches = plan_tool_batches(destructive, tool_fanout());++ // Capture the thread_local context ONCE, on the loop thread, and hand it to+ // every worker. Reading it inside the worker would read the pool thread's+ // defaults, which is the bug this exists to prevent.+ const bool call_in_progress = mcp::TerminalMcpBridge::is_call_in_progress();+ const bool destructive_allowed = mcp::TerminalMcpBridge::is_destructive_allowed();+ const QString session_id = t_chat_session_id;++ for (const auto& [begin, end] : batches) {+ if (end - begin == 1) {+ // In-thread: a single call gains nothing from a pool hop, and this+ // keeps the common one-call round byte-for-byte what it was.+ out[begin] = mcp::McpService::instance().execute_openai_function(calls[begin].wire_name,+ calls[begin].args,+ /*allow_defer=*/true);+ continue;+ }+ std::vector<QFuture<mcp::ToolResult>> futures;+ futures.reserve(end - begin);+ for (std::size_t k = begin; k < end; ++k) {+ futures.push_back(QtConcurrent::run(+ [call = calls[k], call_in_progress, destructive_allowed, session_id]() -> mcp::ToolResult {+ mcp::TerminalMcpBridge::ScopedCallFlags flags(call_in_progress, destructive_allowed);+ ChatSessionGuard session(session_id);+ return mcp::McpService::instance().execute_openai_function(call.wire_name, call.args,+ /*allow_defer=*/true);+ }));+ }+ for (std::size_t k = begin; k < end; ++k) {+ auto& f = futures[k - begin];+ f.waitForFinished();+ out[k] = f.resultCount() > 0 ? f.result() : mcp::ToolResult::fail("Tool produced no result");+ }+ }+ return out;+}+} // namespace fincept::ai_chat::detaildiff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cppindex 481351afa..d0fbf15ec 100644--- a/fincept-qt/src/services/llm/LlmService.cpp+++ b/fincept-qt/src/services/llm/LlmService.cpp@@ -7,10 +7,13 @@#include "core/logging/Logger.h"#include "datahub/DataHub.h"#include "datahub/TopicPolicy.h"+#include "mcp/GeminiSchema.h"#include "mcp/McpProvider.h"#include "mcp/McpService.h"#include "services/llm/LlmContentExtractors.h"#include "services/llm/LlmRequestPolicy.h"++#include <vector>#include "services/llm/ModelCatalog.h"#include "services/llm/ProviderCatalog.h"#include "storage/repositories/LlmConfigRepository.h"@@ -342,70 +345,23 @@ QString LlmService::get_endpoint_url() const {return {};// Fincept sync chat endpoint (async lives in fincept_async_request).- if (p == "fincept") {+ // The only provider whose route is not derivable from a base_url, so it is+ // the only one ProviderCatalog::chat_endpoint leaves to the caller.+ if (p == "fincept")return fincept::AppConfig::instance().api_base_url() + "/research/chat";- }-- // Custom base_url wins over hard-coded defaults.- if (!base_url_.isEmpty()) {- QString base = base_url_;- while (base.endsWith('/'))- base.chop(1);-- // Gemini is the one provider whose request body is NOT OpenAI-shaped,- // so a custom base_url has to compose Gemini's own path. Appending- // "/chat/completions" (what every other provider gets) pointed a- // native `contents`/`tools[].functionDeclarations` body at an- // OpenAI-compat route, which 400s — so any user with a Gemini proxy or- // a regional endpoint lost tool calling along with everything else.- if (p == "gemini" || p == "google") {- if (base.contains(QLatin1String(":generateContent")))- return base;- static const QRegularExpression gem_ver(QStringLiteral("/v\\d+[a-zA-Z]*$"));- if (!gem_ver.match(base).hasMatch())- base += QStringLiteral("/v1beta");- return base + QStringLiteral("/models/") + model_ + QStringLiteral(":generateContent");- }-- const QString suffix = (p == "anthropic") ? QStringLiteral("/messages") : QStringLiteral("/chat/completions");-- // Already a full endpoint — use verbatim.- if (base.endsWith(suffix))- return base;-- // Base already includes a version segment (e.g. ".../v1", ".../v1beta") —- // append only the suffix. Otherwise inject the default "/v1".- static const QRegularExpression re(QStringLiteral("/v\\d+[a-zA-Z]*$"));- if (re.match(base).hasMatch())- return base + suffix;- return base + QStringLiteral("/v1") + suffix;- }- if (p == "openai")- return "https://api.openai.com/v1/chat/completions";- if (p == "anthropic")- return "https://api.anthropic.com/v1/messages";- if (p == "gemini" || p == "google")- return "https://generativelanguage.googleapis.com/v1beta/models/" + model_ + ":generateContent";- if (p == "groq")- return "https://api.groq.com/openai/v1/chat/completions";- if (p == "deepseek")- return "https://api.deepseek.com/v1/chat/completions";- if (p == "openrouter")- return "https://openrouter.ai/api/v1/chat/completions";- if (p == "minimax")- return "https://api.minimax.io/v1/chat/completions";- if (p == "kimi")- return "https://api.moonshot.ai/v1/chat/completions";- if (p == "ollama")- return "http://localhost:11434/v1/chat/completions";- if (p == "xai")- return "https://api.x.ai/v1/chat/completions";- if (p == "aihubmix")- // Fallback for when the prefilled base_url was cleared; the custom-base_url- // branch above wins whenever it's set (incl. regional/proxy overrides).- return "https://aihubmix.com/v1/chat/completions";- return {};+ // Everything else — default hosts, custom/proxy base_urls, and Gemini's+ // native `:generateContent` path — is composed by ProviderCatalog.+ //+ // This used to be a hand-maintained copy of that function, kept in step by+ // a comment. It drifted: ProviderCatalog grew a `default_base_url` fallback+ // for providers whose host lives there rather than in the switch (AstraFlow,+ // AstraFlow CN), while this copy special-cased only AIHubMix and returned an+ // empty string for the other two. A user who cleared the prefilled base_url+ // then got "No endpoint URL for provider: astraflow" from chat while every+ // UI surface, reading ProviderCatalog, showed a working endpoint. Delegating+ // removes the mirror rather than re-synchronising it.+ return ProviderCatalog::chat_endpoint(p, base_url_, model_);}QMap<QString, QString> LlmService::get_headers() const {@@ -545,7 +501,10 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto// grows as the model discovers tools, so a hoisted array would// freeze the catalogue at whatever round 1 could see.const int kMaxRounds = active_max_tool_rounds();- for (int round = 0; round < kMaxRounds; ++round) {+ // Rounds cap the token spend; the deadline caps the wait. See ToolLoopBudget.+ detail::ToolLoopBudget ant_budget(kMaxRounds);+ for (int round = 0; !ant_budget.exhausted(); ++round) {+ ant_budget.note_round();const QJsonArray ant_tools = build_anthropic_tools(activated.names());QJsonObject fu;fu["model"] = model_;@@ -577,28 +536,42 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto// More tools requested — record the assistant turn, execute each// tool_use block, and feed the results back for the next round.loop_msgs.append(QJsonObject{{"role", "assistant"}, {"content", fcontent}});- QJsonArray more_results;+ // Collect the round, then dispatch it together — read-only calls+ // concurrently, writes as barriers (detail::execute_tool_calls).+ std::vector<detail::PendingToolCall> calls;for (const auto& block_val : fcontent) {const QJsonObject block = block_val.toObject();if (block["type"].toString() != "tool_use")continue;- const QString tid = block["id"].toString();- const QString tname = block["name"].toString();- const QJsonObject targs = block["input"].toObject();- LOG_INFO(kLlmSvcTag, QString("Anthropic tool loop r%1: %2").arg(round).arg(tname));- const QString bare = mcp::McpProvider::parse_openai_function_name(tname).second;- detail::emit_tool_progress(bare, targs);- auto tr = mcp::McpService::instance().execute_openai_function(tname, targs,- /*allow_defer=*/true);- detail::note_tool_activations(bare, targs, tr, activated);- more_results.append(QJsonObject{{"type", "tool_result"},- {"tool_use_id", tid},- {"content", detail::encode_tool_result_for_llm(bare, tr)}});+ detail::PendingToolCall c;+ c.call_id = block["id"].toString();+ c.wire_name = block["name"].toString();+ c.args = block["input"].toObject();+ c.display = mcp::McpProvider::parse_openai_function_name(c.wire_name).second;+ LOG_INFO(kLlmSvcTag, QString("Anthropic tool loop r%1: %2").arg(round).arg(c.wire_name));+ detail::emit_tool_progress(c.display, c.args);+ calls.push_back(std::move(c));+ }+ const auto results = detail::execute_tool_calls(calls);+ QJsonArray more_results;+ for (std::size_t k = 0; k < calls.size(); ++k) {+ // tool_result blocks are appended in the model's order: an+ // Anthropic content array is positional, so completion order+ // must not leak into the transcript.+ detail::note_tool_activations(calls[k].display, calls[k].args, results[k], activated);+ more_results.append(+ QJsonObject{{"type", "tool_result"},+ {"tool_use_id", calls[k].call_id},+ {"content", detail::encode_tool_result_for_llm(calls[k].display, results[k])}});}loop_msgs.append(QJsonObject{{"role", "user"}, {"content", more_results}});}- if (resp.content.isEmpty() && resp.error.isEmpty())- resp.error = "Anthropic tool loop exceeded maximum rounds";+ if (resp.content.isEmpty() && resp.error.isEmpty()) {+ // Name the budget that ran out. "exceeded maximum rounds" was+ // wrong the moment a second budget existed, and it told the user+ // nothing actionable either way.+ resp.error = "Anthropic tool loop ended without an answer — " + ant_budget.exhaustion_note();+ }} else {resp.content = extract_anthropic_content_text(content);}@@ -625,6 +598,7 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto// tool and never chain a second. We now loop, re-attaching the tool// set each round, until a text answer or the round cap.const int kMaxRounds = active_max_tool_rounds();+ detail::ToolLoopBudget gem_budget(kMaxRounds);// Rebuilt per round, not hoisted: under Tool RAG the declared// set grows as tool_list / tool_describe surface tools, and a// hoisted array would pin the model to what round 1 could see.@@ -646,23 +620,39 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto// round; seeded with the initial response's parts.QJsonArray model_parts = parts;QJsonArray last_response_parts;- for (int round = 0; round < kMaxRounds; ++round) {+ for (int round = 0; !gem_budget.exhausted(); ++round) {+ gem_budget.note_round();fu_contents.append(QJsonObject{{"role", "model"}, {"parts", model_parts}});- QJsonArray fn_response_parts;+ std::vector<detail::PendingToolCall> calls;for (const auto& part_val : model_parts) {const QJsonObject part = part_val.toObject();if (!part.contains("functionCall"))continue;const QJsonObject fc = part["functionCall"].toObject();- const QString fn_name = fc["name"].toString();- const QJsonObject fn_args = fc["args"].toObject();- LOG_INFO(kLlmSvcTag, QString("Gemini tool loop r%1: %2").arg(round).arg(fn_name));- const QString bare = mcp::McpProvider::parse_openai_function_name(fn_name).second;- detail::emit_tool_progress(bare, fn_args);- auto tr = mcp::McpService::instance().execute_openai_function(fn_name, fn_args,- /*allow_defer=*/true);- detail::note_tool_activations(bare, fn_args, tr, activated);+ detail::PendingToolCall c;+ c.wire_name = fc["name"].toString();+ c.call_id = c.wire_name; // Gemini correlates by name, not by id+ // Gemini's declaration of this tool is a lossy translation+ // of its real schema: a free-form object parameter goes out+ // as a JSON-carrying STRING because Gemini's Schema cannot+ // express "object with arbitrary keys" (mcp/GeminiSchema.h).+ // Reconcile against the original schema so the handler gets+ // the object it declared, not a string it will read as {}.+ c.args = mcp::restore_gemini_call_args(+ mcp::McpService::instance().input_schema_for_function(c.wire_name),+ fc["args"].toObject());+ c.display = mcp::McpProvider::parse_openai_function_name(c.wire_name).second;+ LOG_INFO(kLlmSvcTag, QString("Gemini tool loop r%1: %2").arg(round).arg(c.wire_name));+ detail::emit_tool_progress(c.display, c.args);+ calls.push_back(std::move(c));+ }+ const auto results = detail::execute_tool_calls(calls);+ QJsonArray fn_response_parts;+ for (std::size_t k = 0; k < calls.size(); ++k) {+ const auto& c = calls[k];+ const auto& tr = results[k];+ detail::note_tool_activations(c.display, c.args, tr, activated);// Gemini requires response to be an object — wrap strings under "result".QJsonObject response_obj;if (!tr.data.isNull() && !tr.data.isUndefined() && tr.data.isObject())@@ -673,9 +663,11 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vectoresponse_obj = tr.to_json();// Same transcript budget as the other providers — this// path re-posts `fu_contents` wholesale every round too.- detail::fit_llm_payload(bare, response_obj);+ detail::fit_llm_payload(c.display, response_obj);+ // Parts are positional and must mirror the model's+ // functionCall order, not completion order.fn_response_parts.append(QJsonObject{- {"functionResponse", QJsonObject{{"name", fn_name}, {"response", response_obj}}}});+ {"functionResponse", QJsonObject{{"name", c.wire_name}, {"response", response_obj}}}});}fu_contents.append(QJsonObject{{"role", "user"}, {"parts", fn_response_parts}});last_response_parts = fn_response_parts;@@ -724,17 +716,28 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vectoif (resp.content.isEmpty()) {// Loop exhausted without a text turn — render the last round's// function responses as readable text so the chat isn't blank.- QString fallback;+ // This is raw tool output, NOT an answer: label it as such, say+ // why the loop stopped, and mark any payload that gets clipped.+ // A silently-truncated JSON blob presented as a reply is the+ // worst of both — neither the user nor a model reading the+ // transcript later can tell it is partial (§M4).+ constexpr int kFallbackPayloadChars = 4000;+ QString fallback = "*(the tool loop ended before the model produced an answer — " ++ gem_budget.exhaustion_note() + ". Raw output from the last round below.)*\n";for (const auto& pv : last_response_parts) {const QJsonObject fr = pv.toObject()["functionResponse"].toObject();const QString fn_name = fr["name"].toString();const int sep = fn_name.indexOf("__");const QString short_name = (sep >= 0) ? fn_name.mid(sep + 2) : fn_name;- fallback +=- "\n**Tool: " + short_name + "**\n" +- QString::fromUtf8(QJsonDocument(fr["response"].toObject()).toJson(QJsonDocument::Compact))- .left(4000) +- "\n";+ QString payload = QString::fromUtf8(+ QJsonDocument(fr["response"].toObject()).toJson(QJsonDocument::Compact));+ if (payload.size() > kFallbackPayloadChars) {+ payload = payload.left(kFallbackPayloadChars) ++ QStringLiteral("\n[... truncated %1 of %2 characters ...]")+ .arg(payload.size() - kFallbackPayloadChars)+ .arg(payload.size());+ }+ fallback += "\n**Tool: " + short_name + "**\n" + payload + "\n";}resp.content = fallback;}diff --git a/fincept-qt/src/services/llm/LlmToolLoop.cpp b/fincept-qt/src/services/llm/LlmToolLoop.cppindex 75da79d40..8c9135269 100644--- a/fincept-qt/src/services/llm/LlmToolLoop.cpp+++ b/fincept-qt/src/services/llm/LlmToolLoop.cpp@@ -41,9 +41,17 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur// → actual call), so the default 40 gives ~13 real actions — enough for a// full report template fill. Below ~12 silently cripples report-builder flows.const int MAX_ROUNDS = active_max_tool_rounds();- LOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP: starting (max %1 rounds, model=%2)").arg(MAX_ROUNDS).arg(model_));-- for (int round = 0; round < MAX_ROUNDS; ++round) {+ // Rounds bound the token spend; the deadline bounds the wait. A round that+ // long-polls a background job can take 30 s, so MAX_ROUNDS alone leaves the+ // turn unbounded in wall-clock terms.+ detail::ToolLoopBudget budget(MAX_ROUNDS);+ LOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP: starting (max %1 rounds, %2 s deadline, model=%3)")+ .arg(MAX_ROUNDS)+ .arg(detail::tool_loop_deadline_ms() / 1000)+ .arg(model_));++ for (int round = 0; !budget.exhausted(); ++round) {+ budget.note_round();QJsonObject fu;fu["model"] = model_;fu["messages"] = loop_messages;@@ -80,39 +88,57 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urif (!tcs.isEmpty()) {// Another roundloop_messages.append(msg);+ // Collect the whole round before executing any of it: the calls in+ // one assistant turn are independent by construction, so they are+ // dispatched together (read-only ones concurrently, writes as+ // barriers — see detail::execute_tool_calls).+ std::vector<detail::PendingToolCall> calls;+ calls.reserve(static_cast<std::size_t>(tcs.size()));for (const auto& tc_val : tcs) {- QJsonObject tc = tc_val.toObject();- QString cid = tc["id"].toString();- QString fname = tc["function"].toObject()["name"].toString();- QJsonObject fa =+ const QJsonObject tc = tc_val.toObject();+ detail::PendingToolCall c;+ c.call_id = tc["id"].toString();+ c.wire_name = tc["function"].toObject()["name"].toString();+ c.args =QJsonDocument::fromJson(tc["function"].toObject()["arguments"].toString("{}").toUtf8()).object();-- LOG_INFO(- kLlmToolLoopTag,- QString("TOOL LOOP r%1: executing %2 args=%3")- .arg(round)- .arg(fname, QString::fromUtf8(QJsonDocument(fa).toJson(QJsonDocument::Compact)).left(200)));// Strip "<server>__" prefix for user-visible label; decode any wire encoding.- QString display = fname;- int sep = display.indexOf(QStringLiteral("__"));+ c.display = c.wire_name;+ const int sep = c.display.indexOf(QStringLiteral("__"));if (sep > 0)- display = display.mid(sep + 2);- display.replace(QStringLiteral("-dot-"), QStringLiteral("."));- detail::emit_tool_progress(display, fa);- // allow_defer: this is the one call site that knows about the- // job_* tools, so it is the one allowed to receive a receipt- // instead of a result for a long-running tool.- auto tr = mcp::McpService::instance().execute_openai_function(fname, fa, /*allow_defer=*/true);+ c.display = c.display.mid(sep + 2);+ c.display.replace(QStringLiteral("-dot-"), QStringLiteral("."));++ LOG_INFO(kLlmToolLoopTag,+ QString("TOOL LOOP r%1: executing %2 args=%3")+ .arg(round)+ .arg(c.wire_name,+ QString::fromUtf8(QJsonDocument(c.args).toJson(QJsonDocument::Compact)).left(200)));+ // Progress lines are emitted here, on the loop thread, in the+ // model's order — not from the workers, whose completion order+ // is arbitrary and whose thread has no business touching the UI.+ detail::emit_tool_progress(c.display, c.args);+ calls.push_back(std::move(c));+ }++ // allow_defer is set inside execute_tool_calls: this is the one call+ // site that knows about the job_* tools, so it is the one allowed to+ // receive a receipt instead of a result for a long-running tool.+ const auto results = detail::execute_tool_calls(calls);+ for (std::size_t k = 0; k < calls.size(); ++k) {+ const auto& c = calls[k];+ const auto& tr = results[k];LOG_INFO(kLlmToolLoopTag,QString("TOOL LOOP r%1: %2 -> %3 (msg=%4 err=%5)").arg(round)- .arg(fname, tr.success ? "OK" : "FAIL", tr.message.left(120), tr.error.left(120)));+ .arg(c.wire_name, tr.success ? "OK" : "FAIL", tr.message.left(120), tr.error.left(120)));// If this was a discovery call (tool_list / tool_describe), declare// what it surfaced so the model can actually call it next round.- detail::note_tool_activations(display, fa, tr, activated);+ // Applied in the model's order so the activation LRU evicts the+ // same way it did when execution was sequential.+ detail::note_tool_activations(c.display, c.args, tr, activated);loop_messages.append(QJsonObject{{"role", "tool"},- {"tool_call_id", cid},- {"content", detail::encode_tool_result_for_llm(display, tr)}});+ {"tool_call_id", c.call_id},+ {"content", detail::encode_tool_result_for_llm(c.display, tr)}});}continue;}@@ -151,14 +177,19 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& urreturn resp;}- // Max rounds exhausted. Force one final turn so the chat doesn't go silent.- LOG_WARN(kLlmToolLoopTag, "TOOL LOOP: exceeded max rounds — forcing summary turn");+ // Budget exhausted. Force one final turn so the chat doesn't go silent, and+ // tell the model WHICH budget ran out — "you are out of rounds" and "you are+ // out of time" call for different summaries, and a model told only "budget"+ // tends to relitigate the plan instead of reporting what it has.+ const QString exhaustion = budget.exhaustion_note();+ LOG_WARN(kLlmToolLoopTag, "TOOL LOOP: " + exhaustion + " — forcing summary turn");{- loop_messages.append(- QJsonObject{{"role", "system"},- {"content", "You have used your tool-call budget. Reply now with a final summary of what "- "you accomplished and what (if anything) is incomplete. If there are critical "- "remaining tool calls, you may make them, but prefer summarising."}});+ loop_messages.append(QJsonObject{+ {"role", "system"},+ {"content", "You have used your tool budget (" + exhaustion ++ "). Reply now with a final summary of what you accomplished and what (if anything) is "+ "incomplete. If there are critical remaining tool calls, you may make them, but prefer "+ "summarising."}});QJsonObject fu;fu["model"] = model_;