Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: let Deep Research search MCP tools as extra sources (#13103)
Nilayeca957368814
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 82fdd304abd..db374381d1d 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -13813,17 +13813,19 @@ def cached_mcp_tools() -> tuple[list[dict], bool]:return _mcp_listing(listed), complete-async def get_enabled_mcp_tools() -> list[dict]:- # Keep the SQLite-backed server list off the event loop.+async def get_enabled_mcp_tools(+ include_stdio: bool = True, server_ids: set[str] | None = None+) -> list[dict]:+ # keep the SQLite-backed server list off the event loop.servers = await asyncio.to_thread(lambda: _enabled_mcp_servers(mcp_servers_db.list_servers()))- # Never spawn stdio servers when stdio is disabled on this host.- if not stdio_mcp_enabled():+ if server_ids is not None:+ servers = [server for server in servers if server["id"] in server_ids]+ if not include_stdio or not stdio_mcp_enabled():servers = [s for s in servers if not is_stdio(s["url"])]if not servers:return []- # Skip servers still in their post-failure cool-off, otherwise a down server gets re-probed, and blocks the send- # for the full timeout, on every message.+ # cool-off avoids blocking every send for the full probe timeout when a server is down.uncached = [s for s in servers if get_cached_tools(s["id"]) is None and not in_failure_cooloff(s["id"])]@@ -13873,8 +13875,64 @@ async def get_enabled_mcp_tools() -> list[dict]:return _mcp_listing(listed)+def mcp_search_argument(name: str, tool: dict) -> str | None:+ schema = _mcp_input_schema(tool)+ required = schema.get("required") or []+ properties = schema.get("properties") or {}+ if len(required) != 1 or not isinstance(properties, dict):+ return None+ key = required[0]+ prop = properties.get(key) if isinstance(key, str) else None+ if not isinstance(prop, dict) or prop.get("type") != "string" or "enum" in prop:+ return None+ if is_potentially_unsafe_tool_call(name, {key: ""}):+ return None+ return key+++async def mcp_search_tools(+ include_stdio: bool = True, server_ids: set[str] | None = None+) -> list[dict]:+ from state.tool_policy import get_tool_policy++ if get_tool_policy() is False:+ return []+ await get_enabled_mcp_tools(include_stdio = include_stdio, server_ids = server_ids)+ servers = _enabled_mcp_servers(await asyncio.to_thread(mcp_servers_db.list_servers))+ if server_ids is not None:+ servers = [server for server in servers if server["id"] in server_ids]+ if not include_stdio or not stdio_mcp_enabled():+ servers = [s for s in servers if not is_stdio(s["url"])]+ found = []+ for server in servers:+ for tool in get_cached_tools(server["id"]) or ():+ raw_name = tool.get("name") if isinstance(tool, dict) else None+ if not isinstance(raw_name, str) or not tool_visible_to(tool, "model"):+ continue+ name = f"{MCP_TOOL_PREFIX}{server['id']}__{raw_name}"+ argument = mcp_search_argument(name, public_tool(server, tool))+ if argument:+ found.append(+ {+ "name": name,+ "serverId": server["id"],+ "serverName": server.get("display_name") or server["id"],+ "tool": raw_name,+ "description": tool.get("description") or "",+ "argument": argument,+ }+ )+ return found+++def execute_mcp_tool(name: str, arguments: dict, **kwargs) -> str:+ if not name.startswith(MCP_TOOL_PREFIX):+ return f"Error: '{name}' is not an MCP tool"+ return execute_tool(name, arguments, **kwargs)++def mcp_tool_definition(server_id: str, tool_name: str) -> "dict | None":- """Cache only: callers must not spawn a stdio subprocess or block on a probe."""+ """cache only: callers must not spawn a stdio subprocess or block on a probe."""tools = get_cached_tools(server_id) or ()return next((t for t in tools if isinstance(t, dict) and t.get("name") == tool_name), None)diff --git a/studio/backend/core/research/citations.py b/studio/backend/core/research/citations.pyindex fd575d33ca3..616374f3862 100644--- a/studio/backend/core/research/citations.py+++ b/studio/backend/core/research/citations.py@@ -18,9 +18,8 @@ from markdown_it.rules_inline.backticks import backtickfrom core.research.redaction import _escape_link_destination-# Unrolled rather than (?:[^\[\]]+|\[[^\[\]]*\])* : that alternation backtracks catastrophically on-# an unterminated "[Document:", and this runs on the event loop.-_DOCUMENT_CITATION = re.compile(r"\[Document:[^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*\]")+# unrolling avoids catastrophic backtracking on unclosed [Document: that would block the event loop.+_DOCUMENT_CITATION = re.compile(r"\[(?:Document|MCP):[^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*\]")_MARKDOWN_LINK_START = re.compile(r"\[([^\]\n]+)\]\((https?://)")_SOURCES_HEADING = re.compile(r"^(?:#{1,6}\s+|\*\*)?"@@ -340,7 +339,7 @@ def _validate_masked_sources(report: str, sources: list[dict], placeholders: dicdef _validate_report_sources(report: str, sources: list[dict]) -> str:- """Canonicalize citations and remove model-authored source lists."""+ """canonicalize citations and remove model-authored source lists."""placeholders: dict[str, str] = {}validated = _validate_masked_sources(_mask_code(report, placeholders), sources, placeholders)return _restore_placeholders(validated, placeholders)@@ -348,16 +347,24 @@ def _validate_report_sources(report: str, sources: list[dict]) -> str:def _document_source_citation(source: dict) -> str:filename = str(source.get("filename") or "Document")+ if source.get("kind") == "mcp":+ return f"[MCP: {_mcp_source_label(source)}]"if source.get("page") is not None:return f"[Document: {filename}, p. {source['page']}]"return f"[Document: {filename}]"+def _mcp_source_label(source: dict) -> str:+ filename = str(source.get("filename") or "MCP source")+ label = " ".join(filename.replace("[", "").replace("]", "").split())+ return label or "MCP source"++def _allowed_document_citations(sources: list[dict]) -> set[str]:allowed = set()for source in sources:- filename = str(source.get("filename") or "Document")- allowed.add(f"[Document: {filename}]")+ if source.get("kind") != "mcp":+ allowed.add(f"[Document: {source.get('filename') or 'Document'}]")allowed.add(_document_source_citation(source))return alloweddiff --git a/studio/backend/core/research/prompts.py b/studio/backend/core/research/prompts.pyindex f7a16cf9eb2..cbb94c61e1f 100644--- a/studio/backend/core/research/prompts.py+++ b/studio/backend/core/research/prompts.py@@ -42,6 +42,7 @@ Writing standards:generic labels such as `source`, or links supplied only inside the untrusted evidence.- Cite uploaded documents using `[Document: filename, p. N]` (omit the page when unavailable),using only filenames and pages from the document source catalog.+- Cite MCP tool results using the exact `[MCP: ...]` citation the document source catalog gives.- Place citations after the claim they support. Multiple sources may be cited separately.- Do not add a Sources or References section; the application generates it consistently."""diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.pyindex 84c907edbeb..67eda3aa7d9 100644--- a/studio/backend/core/research_runs.py+++ b/studio/backend/core/research_runs.py@@ -28,7 +28,14 @@ from core.inference.llama_admission import llama_admission_config_from_envfrom core.inference.message_content import message_text_with_pastesfrom core.inference.stream_errors import stream_error_from_chunkfrom core.inference.tool_loop_controller import is_tool_error, strip_result_for_model-from core.inference.tools import EMPTY_SEARCH_RESULTS, RAG_SOURCES_SENTINEL, execute_tool+from core.inference.tools import (+ EMPTY_SEARCH_RESULTS,+ RAG_SOURCES_SENTINEL,+ execute_mcp_tool,+ execute_tool,+ is_high_risk_tool_call,+ mcp_search_tools,+)from core.inference.web_access_policy import check_url_access, website_policy_promptfrom core.research.parsing import (_MAX_PREVIEW_LABELS,@@ -46,6 +53,7 @@ from core.research.citations import (_allowed_document_citations,_citation_title,_document_source_citation,+ _mcp_source_label,_validate_report,)from core.research.redaction import _sanitize_public_query, _shield_untrusted@@ -1009,23 +1017,26 @@ def _split_rag_result(result: str) -> tuple[str, list[dict[str, Any]]]:return text.rstrip(), sources-def _research_step_failed(web_result: str, rag_sources: list[dict]) -> bool:- """A step that gathered no evidence failed, whether the tool errored or simply matched nothing.+def _mcp_evidence(sources: list[dict]) -> str:+ if not sources:+ return ""+ share = 6000 // len(sources)+ text = "\n\n".join(+ f"{_document_source_citation(source)}\n{(source.get('snippet') or '')[:share]}"+ for source in sources+ )+ return f"\n\nMCP tools:\n{text}"- Reporting an empty search as completed hid the one outcome the user needs to see: the report- was written without the evidence that step was supposed to supply.- """++def _research_step_failed(web_result: str, rag_sources: list[dict]) -> bool:+ """empty searches must report missing evidence even when the tool succeeds."""if rag_sources:return Falsereturn is_tool_error(web_result) or web_result.strip() in EMPTY_SEARCH_RESULTSdef _preferred_step_error(current: str, candidate: str) -> str:- """The failure to report when several steps failed differently.-- An engine failure tells the user to wait and retry, an empty sweep tells them to ask- something else, so a later "No results found." must not bury an earlier rate limit.- """+ """engine errors need retries; empty searches need new queries, so preserve engine errors."""if not candidate:return currentif is_tool_error(current) and not is_tool_error(candidate):@@ -1313,6 +1324,65 @@ class ResearchSupervisor:fetched,)+ async def _search_mcp_tools(+ self, run: dict, tools: list[dict], query: str, position: int, tool_timeout: int+ ) -> list[dict]:+ labels = {+ tool["name"]: _mcp_source_label({"filename": f"{tool['serverName']} · {tool['tool']}"})+ for tool in tools+ }+ label_values = list(labels.values())+ labels = {+ name: f"{label} ({name})" if label_values.count(label) > 1 else label+ for name, label in labels.items()+ }+ cancel_event = self._cancel_event(run["id"])+ calls = [+ (tool, {tool["argument"]: query})+ for tool in tools+ if not is_high_risk_tool_call(tool["name"], {tool["argument"]: query})+ ]+ results = await asyncio.gather(+ *(+ asyncio.to_thread(+ execute_mcp_tool,+ tool["name"],+ arguments,+ cancel_event = cancel_event,+ timeout = tool_timeout,+ )+ for tool, arguments in calls+ ),+ return_exceptions = True,+ )+ found = []+ for (tool, _arguments), result in zip(calls, results):+ text = (+ strip_result_for_model(result, tool["name"]).strip()+ if isinstance(result, str)+ else ""+ )+ if not text or is_tool_error(text):+ logger.warning(+ "research.mcp_search_failed run_id=%s tool=%s error=%s",+ run["id"],+ tool["name"],+ (text or str(result))[:200],+ )+ continue+ found.append(+ {+ "kind": "mcp",+ "chunkId": f"{tool['name']}:{position}",+ "documentId": tool["name"],+ "filename": labels[tool["name"]],+ "page": None,+ "score": None,+ "snippet": text[:4000],+ }+ )+ return found+async def _check_worker_write(self, run_id: str, written: bool) -> None:if written:return@@ -1320,7 +1390,6 @@ class ResearchSupervisor:raise LeaseLost()def _salvage_report(self, run_id: str, notice: str) -> str:- """The report a failed run had, under a notice, or "" if synthesis produced none."""draft = self._report_drafts.get(account_key(run_id))if draft is None or not draft.text:return ""@@ -2335,9 +2404,9 @@ class ResearchSupervisor:max_steps = int(budgets["maxSteps"])max_sources = int(budgets["maxSources"])tool_timeout = int(budgets["toolTimeoutSeconds"])- # Absent for runs created before auto-scrape: default 0 keeps their behavior unchanged.+ # default 0 preserves behavior for runs created before auto-scrape.max_auto_scrape = int(budgets.get("maxAutoScrape", 0))- # On a tiny context the prompt overhead alone fills the window, so fall back to snippet-only.+ # prompt overhead fills tiny context windows, so use snippets alone.if max_auto_scrape > 0:loaded_ctx = _loaded_context_length(_run_inference_request(run))if loaded_ctx is not None and loaded_ctx < _AUTO_SCRAPE_MIN_CONTEXT_TOKENS:@@ -2349,6 +2418,20 @@ class ResearchSupervisor:max_auto_scrape = 0website_policy = run["config"].get("websitePolicy")policy_prompt = website_policy_prompt(website_policy)+ selected_mcp = {+ (item["serverId"], item["tool"]) for item in run["config"].get("mcpSources") or ()+ }+ mcp_tools = (+ [+ tool+ for tool in await mcp_search_tools(+ server_ids = {server_id for server_id, _tool in selected_mcp}+ )+ if (tool["serverId"], tool["tool"]) in selected_mcp+ ]+ if selected_mcp+ else []+ )notes: list[str] = []decision_notes: list[str] = []research_state: dict[str, Any] = {}@@ -2436,14 +2519,18 @@ class ResearchSupervisor:f"{item.get('filename') or 'Document'}: "f"{item.get('text') or item.get('snippet') or ''}"for item in accepted_rag_sources+ if item.get("kind") != "mcp")- # An unscraped search persists no excerpt, so a completed step can come back with nothing in it.- if web_evidence or rag_evidence:+ mcp_evidence = _mcp_evidence(+ [item for item in accepted_rag_sources if item.get("kind") == "mcp"]+ )+ # unscraped searches save no excerpt, so completed steps may resume without evidence.+ if web_evidence or rag_evidence or mcp_evidence:completed_steps += 1title = str(step.get("title") or "Recovered research step")notes.append(f"### {title} ({action})\nInput: {argument}\nResult:\n{web_evidence}\n\n"- f"Knowledge base:\n{rag_evidence}"+ f"Knowledge base:\n{rag_evidence}{mcp_evidence}")decision_notes.append(f"### {title} ({action})\nInput: {argument}\nResult:\n{web_evidence}"@@ -2617,6 +2704,7 @@ class ResearchSupervisor:},)await self._check_worker_write(run["id"], seq is not None)+ mcp_sources = []if action["action"] == "fetch":fetched_urls.add(argument)result = await asyncio.to_thread(@@ -2648,6 +2736,10 @@ class ResearchSupervisor:timeout = tool_timeout,rag_scope = run["config"]["ragScope"],)+ if mcp_tools:+ mcp_sources = await self._search_mcp_tools(+ run, mcp_tools, argument, position, tool_timeout+ )rag_result, rag_sources = _split_rag_result(rag_result)await self._check_active(run["id"])document_source_keys = {@@ -2685,10 +2777,22 @@ class ResearchSupervisor:for source in accepted_rag_sources)elif rag_sources:- # Chunks refused by the source cap have no catalog entry and the validator would strip every- # citation to them; gated on rag_sources so a text-only KB reply still passes through.+ # uncataloged chunks lose citations; keep text-only replies when no chunks exist.rag_result = ""rag_sources = accepted_rag_sources+ for source in mcp_sources:+ if len(sources) + len(document_sources) >= max_sources:+ break+ written = await asyncio.to_thread(+ db.upsert_document_source,+ run["id"],+ position,+ source,+ self.worker_id,+ )+ await self._check_worker_write(run["id"], written)+ document_sources.append({**source, "stepPosition": position})+ rag_sources.append(source)step_sources = []for match in _URL_BLOCK.finditer(result if action["action"] == "search" else ""):if len(sources) + len(document_sources) >= max_sources:@@ -2736,13 +2840,15 @@ class ResearchSupervisor:fetched_urls.update(scraped_urls)await self._check_active(run["id"])if scraped_section:- # Additive, not replace: see _merge_scraped_evidence for why replacing the snippets regressed- # accuracy.+ # replacing snippets with scraped chunks reduced accuracy.result = _merge_scraped_evidence(result, scraped_section)+ mcp_evidence = _mcp_evidence(+ [source for source in rag_sources if source.get("kind") == "mcp"]+ )note = (f"### {action['title']} ({action['action']})\n"f"Input: {argument}\nResult:\n{result[:12000]}\n\n"- f"Knowledge base:\n{rag_result[:6000]}"+ f"Knowledge base:\n{rag_result[:6000]}{mcp_evidence}")notes.append(note)decision_notes.append(diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 1f78feac53a..3c17c3fe167 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -468,6 +468,13 @@ class ChatResearchWebsitePolicy(BaseModel):)+class ChatResearchMcpSource(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ serverId: str = Field(min_length = 1, max_length = 200)+ tool: str = Field(min_length = 1, max_length = 500)++class ChatSettingsPayload(BaseModel):model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)@@ -502,6 +509,7 @@ class ChatSettingsPayload(BaseModel):webFetchToolsEnabled: Optional[bool] = NonedeepResearchEnabled: Optional[bool] = NoneresearchWebsitePolicy: Optional[ChatResearchWebsitePolicy] = None+ researchMcpSources: Optional[list[ChatResearchMcpSource]] = Field(default = None, max_length = 20)# Seconds per Deep Research model request; zero leaves the total wall clock off. Bounded# like the run route so a value it would reject cannot be persisted and replayed.researchModelTimeoutSeconds: Optional[int] = Field(default = None, ge = 0, le = 365 * 24 * 3600)diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.pyindex 4d100b68be1..83d22cf688e 100644--- a/studio/backend/routes/mcp_servers.py+++ b/studio/backend/routes/mcp_servers.py@@ -346,12 +346,25 @@ def list_mcp_servers():rows = mcp_servers_db.list_servers()if via_api_key or no_credential:- # Drop the row, not just its fields: `url` is the argv (carries credentials), `headers` is the subprocess- # env, and a blanked url would round-trip into update as a bogus command.+ # url/headers hold argv/env secrets; blanking url allows bogus commands on update.rows = [row for row in rows if not is_stdio(row["url"])]return [_row_to_response(row, include_headers = not no_credential) for row in rows][email protected]("/research-tools")+async def list_research_search_tools(+ current_subject: str = Depends(get_current_subject),+ via_api_key: ViaApiKey = False,+ no_credential: WithoutCredential = False,+):+ from core.inference.tools import mcp_search_tools+ tools = await mcp_search_tools(include_stdio = not (via_api_key or no_credential))+ return [+ {key: tool[key] for key in ("serverId", "serverName", "tool", "description")}+ for tool in tools+ ]++@router.post("/", response_model = McpServerResponse, status_code = 201)async def create_mcp_server(payload: McpServerCreate,diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex b4c96c99424..8e6b6f18408 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -24,7 +24,8 @@ from core.inference.web_access_policy import normalize_website_policyfrom storage import research_runs_db as dbfrom core.inference.providers import answers_decisions_only, provider_runs_local_toolsfrom models.providers import MAX_JSON_SAFE_INTEGER-from storage import providers_db+from state.tool_policy import get_tool_policy+from storage import mcp_servers_db, providers_dbfrom storage.studio_db import get_chat_message, get_chat_thread, upsert_chat_messagefrom utils.current_date_prompt_settings import current_date_prompt_line@@ -50,8 +51,7 @@ _SENSITIVE_KEY_SUFFIXES = ("sessiontoken",)_MAX_PLAN_STEPS = 30-# Zero is the unlimited sentinel, so a finite value only has to cover the longest run anyone-# would set: a year reads back in the 400, unlike a float-max ceiling.+# 0 means unlimited; a one-year finite ceiling keeps 400 errors readable._MIN_FINITE_MODEL_TIMEOUT_SECONDS = 10_MAX_FINITE_MODEL_TIMEOUT_SECONDS = 365 * 24 * 3600_DELTA_ONLY_EVENTS = {@@ -61,10 +61,16 @@ _DELTA_ONLY_EVENTS = {"phase.started","phase.ended",}-# Dedicated to the blocking event wait so open streams cannot exhaust the default executor.+# blocking event waits use a dedicated executor so open streams cannot exhaust the default._EVENT_WAIT_EXECUTOR = ThreadPoolExecutor(max_workers = 32, thread_name_prefix = "research-events")+class ResearchMcpSource(BaseModel):+ model_config = ConfigDict(extra = "forbid")+ serverId: str = Field(min_length = 1, max_length = 200)+ tool: str = Field(min_length = 1, max_length = 500)++class CreateResearchRun(BaseModel):model_config = ConfigDict(extra = "forbid")threadId: str@@ -75,6 +81,7 @@ class CreateResearchRun(BaseModel):)inferenceRequest: dict[str, Any] = Field(default_factory = dict)ragScope: dict[str, Any] | None = None+ mcpSources: list[ResearchMcpSource] = Field(default_factory = list, max_length = 20)budgets: dict[str, int] | None = NonewebsitePolicy: dict[str, list[str]] | None = Noneinstructions: str | None = Field(default = None, max_length = 32_000)@@ -83,8 +90,7 @@ class CreateResearchRun(BaseModel):@field_validator("budgets", mode = "before")@classmethoddef _reject_boolean_budgets(cls, value: Any) -> Any:- # bool is an int subclass, so False would coerce to the 0 "unlimited" sentinel and- # silently drop a deadline. Reject it here: by the time the field is typed it is 0.+ # reject bool before int coercion turns False into 0 and silently disables the deadline.if isinstance(value, dict):for key, item in value.items():if isinstance(item, bool):@@ -341,12 +347,15 @@ def _sanitize_config("whole_doc",}unknown_rag = set(rag_scope) - allowed_rag- # Every ragScope field is a scalar. A nested container evades the sensitive-key scan when its inner keys- # are unlisted (e.g. {"kb_id": {"auth": "sk-..."}}) and would reach retrieval code expecting a scalar scope- # id, so reject non-scalars outright.+ # retrieval requires scalar ragScope fields; containers can evade the sensitive-key scan.non_scalar = any(isinstance(value, (dict, list, tuple)) for value in rag_scope.values())if unknown_rag or non_scalar or _contains_sensitive_key(rag_scope):raise HTTPException(status_code = 400, detail = "Unsupported or sensitive ragScope field")+ mcp_sources = []+ for source in payload.mcpSources:+ server = mcp_servers_db.get_server(source.serverId)+ if server and server.get("is_enabled") and source.model_dump() not in mcp_sources:+ mcp_sources.append(source.model_dump())budgets = {"maxSteps": 12,"maxSources": 40,@@ -361,7 +370,7 @@ def _sanitize_config(limits = {"maxSteps": (1, _MAX_PLAN_STEPS),"maxSources": (1, 100),- # Zero disables the total wall-clock deadline. Per-output stall deadlines still apply.+ # 0 disables the total wall-clock deadline; per-output stall deadlines still apply."modelTimeoutSeconds": (_MIN_FINITE_MODEL_TIMEOUT_SECONDS,_MAX_FINITE_MODEL_TIMEOUT_SECONDS,@@ -379,8 +388,7 @@ def _sanitize_config(if key == "modelTimeoutSeconds":allowed = f"0 (unlimited) or {allowed}"raise HTTPException(status_code = 400, detail = f"{key} must be {allowed}")- # Server-controlled, not client tunable. OFF unless UNSLOTH_RESEARCH_AUTO_SCRAPE=1, and- # injected only when enabled, so a default run's budgets stay byte-identical to legacy.+ # server-only UNSLOTH_RESEARCH_AUTO_SCRAPE=1 adds maxAutoScrape; defaults match legacy.from core.research_runs import _auto_scrape_default_auto_scrape = _auto_scrape_default()@@ -394,6 +402,7 @@ def _sanitize_config("model": model,"inferenceRequest": request,"ragScope": rag_scope,+ **({"mcpSources": mcp_sources} if mcp_sources and get_tool_policy() is not False else {}),"budgets": budgets,"websitePolicy": website_policy,"instructions": (payload.instructions or "").strip(),diff --git a/studio/backend/storage/research_runs_db.py b/studio/backend/storage/research_runs_db.pyindex dcc889154da..2ae2adaf261 100644--- a/studio/backend/storage/research_runs_db.py+++ b/studio/backend/storage/research_runs_db.py@@ -479,6 +479,7 @@ def get_run(run_id: str, owner_subject: str | None = None) -> dict | None:for r in conn.execute("SELECT id, step_position AS stepPosition, document_id AS documentId, ""chunk_id AS chunkId, filename, page, score, snippet, "+ "COALESCE(kind, 'knowledge_base') AS kind, ""fetched_at AS fetchedAt FROM research_document_sources ""WHERE run_id = ? ORDER BY id",(run_id,),@@ -1288,12 +1289,13 @@ def upsert_document_source(conn.execute("""INSERT INTO research_document_sources(run_id, step_position, source_key, document_id, chunk_id, filename,- page, score, snippet, fetched_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ page, score, snippet, fetched_at, kind)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT(run_id, source_key) DO UPDATE SETstep_position=excluded.step_position, document_id=excluded.document_id,chunk_id=excluded.chunk_id, filename=excluded.filename, page=excluded.page,- score=excluded.score, snippet=excluded.snippet, fetched_at=excluded.fetched_at""",+ score=excluded.score, snippet=excluded.snippet, fetched_at=excluded.fetched_at,+ kind=excluded.kind""",(run_id,position,@@ -1305,6 +1307,7 @@ def upsert_document_source(float(source["score"]) if isinstance(source.get("score"), (int, float)) else None,str(source.get("text") or source.get("snippet") or "")[:4000],fetched_at,+ "mcp" if source.get("kind") == "mcp" else None,),)conn.commit()diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex ed78ad570c1..edb52eef884 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -1015,6 +1015,11 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:)""")+ document_source_cols = {+ row[1] for row in conn.execute("PRAGMA table_info(research_document_sources)").fetchall()+ }+ if "kind" not in document_source_cols:+ conn.execute("ALTER TABLE research_document_sources ADD COLUMN kind TEXT")conn.execute("""CREATE TABLE IF NOT EXISTS research_events (diff --git a/studio/backend/tests/test_chat_settings_payload.py b/studio/backend/tests/test_chat_settings_payload.pyindex 91bcadbb551..cd1bf98af56 100644--- a/studio/backend/tests/test_chat_settings_payload.py+++ b/studio/backend/tests/test_chat_settings_payload.py@@ -73,6 +73,16 @@ def test_thread_rag_source_keeps_its_shape():assert payload.model_dump(exclude_unset = True) == {"ragSource": {"type": "thread"}}+def test_research_mcp_sources_round_trip_and_clear():+ sources = [{"serverId": "notes", "tool": "search_notes"}]+ payload = ChatSettingsPayload.model_validate({"researchMcpSources": sources})+ assert payload.model_dump(exclude_unset = True) == {"researchMcpSources": sources}+ cleared = ChatSettingsPayload.model_validate({"researchMcpSources": []})+ assert _deep_merge_settings(+ payload.model_dump(exclude_unset = True), cleared.model_dump(exclude_unset = True)+ ) == {"researchMcpSources": []}++def test_rag_source_replaces_rather_than_merges():"""A thread pick over a stored kb pick must not keep kbId.diff --git a/studio/backend/tests/test_research_mcp_sources.py b/studio/backend/tests/test_research_mcp_sources.pynew file mode 100644index 00000000000..127c3f87603--- /dev/null+++ b/studio/backend/tests/test_research_mcp_sources.py@@ -0,0 +1,443 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import asyncio+import json+from types import SimpleNamespace++import pytest++from core.inference import mcp_client+from storage import mcp_servers_db+from storage import research_runs_db as research_db+from storage import studio_db++PLAN = {"title": "Zephyr", "steps": [{"title": "Launch", "query": "zephyr beta launch"}]}+++def _tool(name, *required):+ return {+ "name": name,+ "description": f"{name} tool",+ "inputSchema": {+ "type": "object",+ "properties": {key: {"type": "string"} for key in required},+ "required": list(required),+ },+ }+++def notes_server(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())+ studio_db.upsert_chat_thread(+ {+ "id": "thread-1",+ "title": "R",+ "modelType": "base",+ "modelId": "local-model",+ "createdAt": 1,+ }+ )+ studio_db.upsert_chat_message(+ {+ "id": "user-1",+ "threadId": "thread-1",+ "role": "user",+ "content": [{"type": "text", "text": "When did Zephyr launch?"}],+ "createdAt": 2,+ }+ )+ mcp_servers_db.create_server(+ id = "notes", display_name = "Project Notes", url = "https://notes.example/mcp"+ )+ mcp_client.cache_tools(+ "notes",+ [+ _tool("search_notes", "query"),+ _tool("search_papers", "query"),+ _tool("delete_note", "note_id"),+ _tool("lookup_pair", "left", "right"),+ _tool("get_secret_token", "query"),+ _tool("schedule_meeting", "query"),+ _tool("complete_task", "query"),+ ],+ )+ yield+ mcp_client.invalidate_tool_cache("notes")+++def test_research_lists_only_read_only_single_query_mcp_tools(notes_server):+ from routes.mcp_servers import list_research_search_tools+ tools = asyncio.run(list_research_search_tools(current_subject = "alice"))++ assert [(tool["serverName"], tool["tool"]) for tool in tools] == [+ ("Project Notes", "search_notes"),+ ("Project Notes", "search_papers"),+ ]+++def test_credentialless_discovery_never_starts_stdio_servers(monkeypatch):+ from core.inference import tools as tools_mod++ servers = [+ {+ "id": "local",+ "display_name": "Local",+ "url": "python server.py",+ "is_enabled": True,+ "use_oauth": False,+ },+ {+ "id": "remote",+ "display_name": "Remote",+ "url": "https://notes.example/mcp",+ "is_enabled": True,+ "use_oauth": False,+ },+ ]+ calls = []++ async def fake_list_tools(url, **kwargs):+ calls.append(url)+ return [_tool("search_notes", "query")]++ monkeypatch.setattr(mcp_client, "_tool_cache", {})+ monkeypatch.setattr(mcp_servers_db, "list_servers", lambda: servers)+ monkeypatch.setattr(tools_mod, "stdio_mcp_enabled", lambda: True)+ monkeypatch.setattr(tools_mod, "list_tools_async", fake_list_tools)++ tools = asyncio.run(tools_mod.mcp_search_tools(include_stdio = False))++ assert calls == ["https://notes.example/mcp"]+ assert [tool["serverId"] for tool in tools] == ["remote"]+++def test_run_discovery_only_probes_selected_servers(monkeypatch):+ from core.inference import tools as tools_mod++ servers = [+ {+ "id": server_id,+ "display_name": server_id.title(),+ "url": f"https://{server_id}.example/mcp",+ "is_enabled": True,+ "use_oauth": False,+ }+ for server_id in ("selected", "unused")+ ]+ calls = []++ async def fake_list_tools(url, **kwargs):+ calls.append(url)+ return [_tool("search_notes", "query")]++ monkeypatch.setattr(mcp_client, "_tool_cache", {})+ monkeypatch.setattr(mcp_servers_db, "list_servers", lambda: servers)+ monkeypatch.setattr(tools_mod, "list_tools_async", fake_list_tools)++ tools = asyncio.run(tools_mod.mcp_search_tools(server_ids = {"selected"}))++ assert calls == ["https://selected.example/mcp"]+ assert [tool["serverId"] for tool in tools] == ["selected"]+++def test_research_drops_mcp_servers_the_account_does_not_have(notes_server):+ from routes.research_runs import CreateResearchRun, _sanitize_config+ config = _sanitize_config(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ mcpSources = [+ {"serverId": "someone-elses", "tool": "search_notes"},+ {"serverId": "notes", "tool": "search_notes"},+ ],+ ),+ {"modelId": "local-model"},+ )+ assert config["mcpSources"] == [{"serverId": "notes", "tool": "search_notes"}]+++def test_mcp_evidence_keeps_content_from_every_source():+ from core.research_runs import _mcp_evidence++ sources = [+ {+ "kind": "mcp",+ "filename": f"Source {index}",+ "snippet": f"marker-{index} " + "x" * 4000,+ }+ for index in range(3)+ ]+ evidence = _mcp_evidence(sources)++ assert len(evidence) < 6500+ for index in range(3):+ assert f"marker-{index}" in evidence+++def test_mcp_citation_normalizes_untrusted_source_labels():+ from core.research.citations import (+ _document_source_citation,+ _validate_report_document_sources,+ )++ source = {"kind": "mcp", "filename": "Project ]\n[ Notes · search"}+ citation = _document_source_citation(source)++ assert citation == "[MCP: Project Notes · search]"+ assert _validate_report_document_sources(f"Claim {citation}.", [source]) == (+ f"Claim {citation}."+ )+ assert _validate_report_document_sources(+ "Claim [Document: Project Notes · search].", [source]+ ) == ("Claim .")+++def test_selected_mcp_tools_search_every_step_and_are_cited(notes_server, monkeypatch):+ from core import research_runs as worker+ from routes.research_runs import CreateResearchRun, _sanitize_config++ config = _sanitize_config(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ mcpSources = [+ {"serverId": "notes", "tool": "search_notes"},+ {"serverId": "notes", "tool": "search_papers"},+ {"serverId": "notes", "tool": "delete_note"},+ ],+ ),+ {"modelId": "local-model"},+ )+ research_db.create_run(+ run_id = "run-1",+ owner_subject = "alice",+ thread_id = "thread-1",+ user_message_id = "user-1",+ assistant_message_id = None,+ config = config,+ created_at = 10,+ )+ plan = research_db.set_plan("run-1", PLAN)+ research_db.approve("run-1", plan["planRevision"], plan["planHash"])+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))++ decisions = iter(+ (+ json.dumps({"action": "search", "title": "Launch", "query": "zephyr beta launch"}),+ json.dumps({"action": "search", "title": "Languages", "query": "zephyr languages"}),+ json.dumps({"action": "finish", "title": "Enough"}),+ )+ )+ decision_prompts = []+ synthesis_prompts = []+ report = "# Zephyr\n\nThe beta shipped on 14 March 2031 [MCP: Project Notes · search_notes]."++ async def fake_stream_completion(run, messages, **kwargs):+ if "iterative research process" in messages[0]["content"]:+ decision_prompts.append(messages[1]["content"])+ return next(decisions), "", "stop", None+ synthesis_prompts.append(messages[1]["content"])+ research_db.set_report_progress(run["id"], report)+ return report, "", "stop", None++ calls = []++ def fake_tool(name, arguments, *args, **kwargs):+ calls.append((name, arguments))+ if name == "web_search":+ return "No results found."+ if name == "mcp__notes__search_papers":+ return "Error: MCP tool 'search_papers' timed out after 120s"+ return f"Zephyr notes for {arguments['query']}: the beta shipped on 14 March 2031."++ monkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)+ monkeypatch.setattr(worker, "execute_tool", fake_tool)+ monkeypatch.setattr(worker, "execute_mcp_tool", fake_tool)+ asyncio.run(supervisor._process(research_db.claim_next(supervisor.worker_id)))++ completed = research_db.get_run("run-1")+ assert completed["status"] == "completed"+ assert [step["status"] for step in completed["steps"]] == ["completed", "completed"]+ assert ("mcp__notes__search_notes", {"query": "zephyr beta launch"}) in calls+ assert ("mcp__notes__search_notes", {"query": "zephyr languages"}) in calls+ assert ("mcp__notes__search_papers", {"query": "zephyr languages"}) in calls+ assert not [name for name, _ in calls if name == "mcp__notes__delete_note"]+ assert [(s["kind"], s["filename"]) for s in completed["documentSources"]] == [+ ("mcp", "Project Notes · search_notes"),+ ("mcp", "Project Notes · search_notes"),+ ]+ assert "Citation: [MCP: Project Notes · search_notes]" in synthesis_prompts[-1]+ assert "14 March 2031" in synthesis_prompts[-1]+ assert not any("14 March 2031" in prompt for prompt in decision_prompts)+ assert "[MCP: Project Notes · search_notes]" in completed["report"]+++def test_resumed_run_keeps_mcp_sources_citable(notes_server, monkeypatch):+ from core import research_runs as worker++ research_db.create_run(+ run_id = "run-1",+ owner_subject = "alice",+ thread_id = "thread-1",+ user_message_id = "user-1",+ assistant_message_id = None,+ config = {+ "model": "local-model",+ "inferenceRequest": {"model": "local-model"},+ "mcpSources": [{"serverId": "notes", "tool": "search_notes"}],+ "budgets": {+ "maxSteps": 1,+ "maxSources": 15,+ "modelTimeoutSeconds": 30,+ "toolTimeoutSeconds": 10,+ },+ },+ created_at = 10,+ )+ plan = research_db.set_plan("run-1", PLAN)+ research_db.approve("run-1", plan["planRevision"], plan["planHash"])+ research_db.claim_next("old-worker")+ research_db.reset_execution_steps("run-1", "old-worker")+ source = {+ "kind": "mcp",+ "chunkId": "mcp__notes__search_notes:0",+ "documentId": "mcp__notes__search_notes",+ "filename": "Project Notes · search_notes",+ "snippet": "The beta shipped on 14 March 2031.",+ }+ research_db.upsert_document_source("run-1", 0, source, "old-worker")+ research_db.upsert_execution_step(+ "run-1",+ 0,+ "Launch",+ "zephyr beta launch",+ "completed",+ {"action": "search", "input": "zephyr beta launch", "evidenceSources": [source]},+ "old-worker",+ )+ conn = studio_db.get_connection()+ try:+ conn.execute("UPDATE research_runs SET lease_expires_at=0 WHERE id='run-1'")+ conn.commit()+ finally:+ conn.close()+ assert research_db.recover_expired() == 1+ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))+ recovered = research_db.claim_next(supervisor.worker_id)+ synthesis_prompts = []+ report = "# Zephyr\n\nShipped 14 March 2031 [MCP: Project Notes · search_notes]."++ async def fake_stream_completion(run, messages, **kwargs):+ synthesis_prompts.append(messages[1]["content"])+ research_db.set_report_progress(run["id"], report)+ return report, "", "stop", None++ def unexpected_tool(*args, **kwargs):+ raise AssertionError("Recovered evidence should be synthesized without searching again")++ monkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)+ monkeypatch.setattr(worker, "execute_tool", unexpected_tool)+ monkeypatch.setattr(worker, "execute_mcp_tool", unexpected_tool)+ asyncio.run(supervisor._process(recovered))++ completed = research_db.get_run("run-1")+ assert completed["status"] == "completed"+ assert [s["kind"] for s in completed["documentSources"]] == ["mcp"]+ assert "Citation: [MCP: Project Notes · search_notes]" in synthesis_prompts[-1]+ assert "14 March 2031" in synthesis_prompts[-1]+ assert "[MCP: Project Notes · search_notes]" in completed["report"]+++def test_mcp_sources_only_accept_the_mcp_citation():+ from core.research.citations import _validate_report++ source = {"kind": "mcp", "filename": "Project Notes · search_notes"}+ report = "A [MCP: Project Notes · search_notes]. B [Document: Project Notes · search_notes]."++ assert _validate_report(report, [], [source]) == "A [MCP: Project Notes · search_notes]. B ."+++def test_every_selected_mcp_tool_reaches_the_notes():+ from core.research_runs import _mcp_evidence++ sources = [+ {"kind": "mcp", "filename": f"Notes · search_{i}", "snippet": f"fact-{i} " + "x" * 3990}+ for i in range(3)+ ]++ evidence = _mcp_evidence(sources)+ assert all(f"fact-{i}" in evidence for i in range(3))+ assert len(evidence) < 6500+++def test_research_tools_for_an_api_key_never_start_stdio_servers(notes_server, monkeypatch):+ from core.inference import tools+ from routes.mcp_servers import list_research_search_tools++ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")+ mcp_servers_db.create_server(id = "local", display_name = "Local", url = "/bin/sh -c id")+ probed = []++ async def probe(**kwargs):+ probed.append(kwargs["url"])+ return []++ monkeypatch.setattr(tools, "list_tools_async", probe)+ listed = asyncio.run(list_research_search_tools(current_subject = "alice", via_api_key = True))++ assert probed == []+ assert [tool["tool"] for tool in listed] == ["search_notes", "search_papers"]+++def test_research_ignores_mcp_sources_while_tools_are_disabled(notes_server):+ from routes.mcp_servers import list_research_search_tools+ from routes.research_runs import CreateResearchRun, _sanitize_config+ from state.tool_policy import tools_force_disabled++ with tools_force_disabled():+ listed = asyncio.run(list_research_search_tools(current_subject = "alice"))+ config = _sanitize_config(+ CreateResearchRun(+ threadId = "thread-1",+ userMessageId = "user-1",+ inferenceRequest = {"model": "local-model"},+ mcpSources = [{"serverId": "notes", "tool": "search_notes"}],+ ),+ {"modelId": "local-model"},+ )++ assert listed == []+ assert "mcpSources" not in config+++def test_research_mcp_calls_cannot_reach_built_in_tools():+ from core.inference.tools import execute_mcp_tool+ assert execute_mcp_tool("terminal", {"command": "id"}).startswith("Error:")+++def test_identically_named_mcp_sources_have_distinct_citations(monkeypatch):+ from core import research_runs as worker+ from core.research.citations import _document_source_citation++ supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))+ tools = [+ {+ "serverId": server_id,+ "serverName": "Notes",+ "tool": "search",+ "name": f"mcp__{server_id}__search",+ "argument": "query",+ }+ for server_id in ("first", "second")+ ]+ monkeypatch.setattr(+ worker, "execute_mcp_tool", lambda name, *args, **kwargs: f"Evidence from {name}"+ )+ sources = asyncio.run(supervisor._search_mcp_tools({"id": "r"}, tools, "query", 0, 10))+ assert len({_document_source_citation(source) for source in sources}) == 2diff --git a/studio/frontend/src/components/assistant-ui/rag-sources.tsx b/studio/frontend/src/components/assistant-ui/rag-sources.tsxindex 27e26ca8e94..5e5dfde1f48 100644--- a/studio/frontend/src/components/assistant-ui/rag-sources.tsx+++ b/studio/frontend/src/components/assistant-ui/rag-sources.tsx@@ -9,10 +9,11 @@ import type { FC } from "react";import { type Citation, parseCitations } from "./citation-utils";import { CitationBadge } from "./tool-ui-knowledge-base";-export const DocumentSourcesGroup: FC<{ sources: Citation[] }> = ({- sources: all,-}) => {- // Map updates keep first-seen order, so dedup to best-scoring chunk per doc.+export const DocumentSourcesGroup: FC<{+ sources: Citation[];+ label?: string;+}> = ({ sources: all, label = "Document Sources" }) => {+ // Map keeps first-seen order while retaining each document's top score.const byDoc = new Map<string, Citation>();for (const c of all) {const key = c.documentId ?? c.filename;@@ -33,7 +34,7 @@ export const DocumentSourcesGroup: FC<{ sources: Citation[] }> = ({return (<div className="mt-2 mb-3"><div className="mb-1 text-xs font-medium text-muted-foreground">- Document Sources+ {label}</div><div className="flex flex-wrap gap-1.5">{sources.map((citation, i) => (diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex ce1ba496a39..80ebef152a6 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -4683,11 +4683,13 @@ export function createOpenAIStreamAdapter(userMessageId: userMessage.id,assistantMessageId: unstable_assistantMessageId,inferenceRequest,- // Omitted when empty: CreateResearchRun forbids unknown fields, so an unconditional send 422s- // an older backend.+ // omit empty fields: old backends reject unknown fields with 422....(researchQuestion ? { question: researchQuestion } : {}),...(researchInstructions ? { instructions: researchInstructions } : {}),...(ragScope ? { ragScope } : {}),+ ...(runtime.researchMcpSources.length+ ? { mcpSources: runtime.researchMcpSources }+ : {}),budgets: {modelTimeoutSeconds: runtime.researchModelTimeoutSeconds,},@@ -4698,8 +4700,7 @@ export function createOpenAIStreamAdapter(});researchRunId = createdRun.id;if (researchStopRequested) {- // Stopped while createResearchRun was in flight, so the handle had no id; replay it rather- // than follow a run the user ended.+ // replay stop once creation supplies the missing run id.void cancelResearchRun(createdRun.id).catch(() => {});return;}diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.tsindex 32360f20b59..f5723b9d946 100644--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts@@ -11,7 +11,10 @@ import type {RagSource,ReasoningEffort,} from "../stores/chat-runtime-store";-import type { ResearchWebsitePolicy } from "../types/research";+import type {+ ResearchMcpSource,+ ResearchWebsitePolicy,+} from "../types/research";import type {InferenceParams,PersistedInferenceParams,@@ -55,6 +58,7 @@ export interface PersistedChatSettings {webFetchToolsEnabled?: boolean;deepResearchEnabled?: boolean;researchWebsitePolicy?: ResearchWebsitePolicy;+ researchMcpSources?: ResearchMcpSource[];researchModelTimeoutSeconds?: number;mcpEnabledForChat?: boolean;confirmToolCalls?: boolean;diff --git a/studio/frontend/src/features/chat/api/mcp-servers-api.ts b/studio/frontend/src/features/chat/api/mcp-servers-api.tsindex ca89cb0874e..742fa876efb 100644--- a/studio/frontend/src/features/chat/api/mcp-servers-api.ts+++ b/studio/frontend/src/features/chat/api/mcp-servers-api.ts@@ -260,6 +260,17 @@ export function listMcpServerTools(return mcpRequest(`/${serverId}/tools`);}+export interface ResearchMcpTool {+ serverId: string;+ serverName: string;+ tool: string;+ description: string;+}++export function listResearchMcpTools(): Promise<ResearchMcpTool[]> {+ return mcpRequest("/research-tools");+}+export function testMcpServer(payload: {url: string;headers?: Record<string, string>;diff --git a/studio/frontend/src/features/chat/components/deep-research-composer-button.tsx b/studio/frontend/src/features/chat/components/deep-research-composer-button.tsxindex 3ba8df7aaf8..b508f9ddbf5 100644--- a/studio/frontend/src/features/chat/components/deep-research-composer-button.tsx+++ b/studio/frontend/src/features/chat/components/deep-research-composer-button.tsx@@ -17,15 +17,29 @@ import { Switch } from "@/components/ui/switch";import { cn } from "@/lib/utils";import { ChevronDownStandardIcon } from "@/lib/chevron-icons";import { XIcon } from "lucide-react";-import { type KeyboardEvent, useState } from "react";+import {+ type Dispatch,+ type KeyboardEvent,+ type SetStateAction,+ useEffect,+ useState,+} from "react";+import {+ listResearchMcpTools,+ type ResearchMcpTool,+} from "../api/mcp-servers-api";import {DEFAULT_RESEARCH_MODEL_TIMEOUT_SECONDS,+ MAX_RESEARCH_MCP_SOURCES,useChatRuntimeStore,} from "../stores/chat-runtime-store";import { MAX_RESEARCH_MODEL_TIMEOUT_SECONDS } from "../utils/mirrored-chat-settings";-import type { ResearchWebsitePolicy } from "../types/research";+import type {+ ResearchMcpSource,+ ResearchWebsitePolicy,+} from "../types/research";-// The field is in minutes; its ceiling is the seconds cap the backend enforces.+// the backend caps seconds; this field takes minutes.const MAX_RESEARCH_MODEL_TIMEOUT_MINUTES = Math.floor(MAX_RESEARCH_MODEL_TIMEOUT_SECONDS / 60,);@@ -144,6 +158,120 @@ function DomainList({);}+const matches = (tool: ResearchMcpTool, value: ResearchMcpSource) =>+ value.serverId === tool.serverId && value.tool === tool.tool;++function McpSourceList({+ values,+ onChange,+}: {+ values: ResearchMcpSource[];+ onChange: Dispatch<SetStateAction<ResearchMcpSource[]>>;+}) {+ const [tools, setTools] = useState<ResearchMcpTool[] | null>(null);++ useEffect(() => {+ let cancelled = false;+ listResearchMcpTools().then(+ (found) => {+ if (cancelled) return;+ setTools(found);+ },+ () => {+ if (!cancelled) setTools([]);+ },+ );+ return () => {+ cancelled = true;+ };+ }, []);+ const unavailableValues = values.filter(+ (value) => tools !== null && !tools.some((tool) => matches(tool, value)),+ );++ return (+ <div className="space-y-2">+ <div>+ <div className="text-sm font-medium">MCP search sources</div>+ <p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">+ Every research search also sends its query to the tools turned on+ here. Choose up to {MAX_RESEARCH_MCP_SOURCES}.+ </p>+ </div>+ {tools === null ? (+ <p className="text-xs text-muted-foreground">Loading MCP tools…</p>+ ) : tools.length === 0 ? (+ <p className="text-xs text-muted-foreground">+ No enabled MCP server has a search tool that takes a single query.+ </p>+ ) : (+ tools.map((tool) => (+ <label+ key={`${tool.serverId}:${tool.tool}`}+ className="flex cursor-pointer items-start justify-between gap-6"+ >+ <span className="min-w-0">+ <span className="block break-words text-sm">+ {tool.serverName} · {tool.tool}+ </span>+ {tool.description ? (+ <span className="block line-clamp-2 text-xs text-muted-foreground">+ {tool.description}+ </span>+ ) : null}+ </span>+ <Switch+ checked={values.some((value) => matches(tool, value))}+ disabled={+ !values.some((value) => matches(tool, value)) &&+ values.length >= MAX_RESEARCH_MCP_SOURCES+ }+ onCheckedChange={(checked) =>+ onChange(+ checked+ ? [+ ...values,+ { serverId: tool.serverId, tool: tool.tool },+ ].slice(0, MAX_RESEARCH_MCP_SOURCES)+ : values.filter(+ (value) => !matches(tool, value),+ ),+ )+ }+ aria-label={`Search with ${tool.serverName} ${tool.tool}`}+ />+ </label>+ ))+ )}+ {unavailableValues.map((value) => (+ <div+ key={`${value.serverId}:${value.tool}`}+ className="flex items-start justify-between gap-6"+ >+ <span className="min-w-0 break-words text-sm">+ {value.serverId} · {value.tool}+ <span className="block text-xs text-muted-foreground">+ Currently unavailable. Selection kept until you remove it.+ </span>+ </span>+ <button+ type="button"+ className="text-sm text-muted-foreground hover:text-foreground"+ aria-label={`Remove unavailable source ${value.serverId} ${value.tool}`}+ onClick={() =>+ onChange(values.filter((item) =>+ item.serverId !== value.serverId || item.tool !== value.tool,+ ))+ }+ >+ Remove+ </button>+ </div>+ ))}+ </div>+ );+}+export function DeepResearchComposerButton({onConfigure,}: {@@ -208,6 +336,10 @@ export function DeepResearchWebsiteAccessDialog({const setModelTimeoutSeconds = useChatRuntimeStore((state) => state.setResearchModelTimeoutSeconds,);+ const mcpSources = useChatRuntimeStore((state) => state.researchMcpSources);+ const setMcpSources = useChatRuntimeStore(+ (state) => state.setResearchMcpSources,+ );return (<Dialog open={open} onOpenChange={onOpenChange}>@@ -217,6 +349,8 @@ export function DeepResearchWebsiteAccessDialog({setPolicy={setPolicy}modelTimeoutSeconds={modelTimeoutSeconds}setModelTimeoutSeconds={setModelTimeoutSeconds}+ mcpSources={mcpSources}+ setMcpSources={setMcpSources}onClose={() => onOpenChange(false)}/>) : null}@@ -229,17 +363,22 @@ function DeepResearchWebsiteAccessContent({setPolicy,modelTimeoutSeconds,setModelTimeoutSeconds,+ mcpSources,+ setMcpSources,onClose,}: {policy: ResearchWebsitePolicy;setPolicy: (policy: ResearchWebsitePolicy) => void;modelTimeoutSeconds: number;setModelTimeoutSeconds: (seconds: number) => void;+ mcpSources: ResearchMcpSource[];+ setMcpSources: (sources: ResearchMcpSource[]) => void;onClose: () => void;}) {const [draft, setDraft] = useState<ResearchWebsitePolicy>(policy);+ const [mcpDraft, setMcpDraft] = useState<ResearchMcpSource[]>(mcpSources);const [unlimited, setUnlimited] = useState(modelTimeoutSeconds === 0);- // Unlimited has no minutes of its own, so turning the limit back on offers the default.+ // re-enabling the limit from unlimited starts at the default.const [timeoutMinutes, setTimeoutMinutes] = useState(String(Math.ceil(@@ -247,8 +386,7 @@ function DeepResearchWebsiteAccessContent({),),);- // The API accepts second-level values the minutes field cannot spell, so saving an untouched- // control must replay the stored seconds rather than the rounded minutes.+ // preserve stored seconds when the rounded minutes field is untouched.const [timeoutEdited, setTimeoutEdited] = useState(false);return (@@ -323,6 +461,7 @@ function DeepResearchWebsiteAccessContent({values={draft.blockedDomains}onChange={(blockedDomains) => setDraft({ ...draft, blockedDomains })}/>+ <McpSourceList values={mcpDraft} onChange={setMcpDraft} /></div><DialogFooter><Button variant="ghost" onClick={onClose}>@@ -331,9 +470,9 @@ function DeepResearchWebsiteAccessContent({<ButtononClick={() => {setPolicy(draft);+ setMcpSources(mcpDraft);const minutes = Number(timeoutMinutes);- // The max attribute does not stop a typed value reaching here, and falling through to the default- // would hand someone asking for a long run a short one.+ // typed values bypass max; clamp to avoid a short default timeout.setModelTimeoutSeconds(unlimited? 0diff --git a/studio/frontend/src/features/chat/components/research-message.tsx b/studio/frontend/src/features/chat/components/research-message.tsxindex 646d64b47c2..772f9eefc59 100644--- a/studio/frontend/src/features/chat/components/research-message.tsx+++ b/studio/frontend/src/features/chat/components/research-message.tsx@@ -24,6 +24,7 @@ import {} from "../stores/research-run-store";import type { ResearchMessageMetadata } from "../types/research";import { researchReplyOwnsRun } from "../utils/research-run-binding";+import { researchCitation } from "../utils/research-citations";import { researchStatusLabel } from "./research-activity-panel";export function ResearchMessage(): ReactElement | null {@@ -79,7 +80,7 @@ export function ResearchMessage(): ReactElement | null {);}- // A failed run's report opens with its own notice, so nothing here repeats it.+ // failed reports include their own notice; avoid repeating it here.if ((run.status === "completed" || run.status === "failed") && run.report) {const failed = run.status === "failed";const sources: SourceData[] = run.sources.map((source) => ({@@ -88,19 +89,17 @@ export function ResearchMessage(): ReactElement | null {title: source.title || source.url,description: source.snippet ?? undefined,}));- const documentSources: Citation[] = (run.documentSources ?? []).map(- (source, index) => ({- id: source.chunkId ?? String(source.id ?? index),- filename: source.filename,- page: source.page,- score: source.score,- text: source.snippet ?? "",- documentId: source.documentId,- chunkId: source.chunkId,- }),- );+ const documentSources: Citation[] = [];+ const mcpSources: Citation[] = [];+ (run.documentSources ?? []).forEach((source, index) => {+ (source.kind === "mcp" ? mcpSources : documentSources).push(+ researchCitation(source, index),+ );+ });const documentCount = new Set(- documentSources.map((source) => source.documentId ?? source.filename),+ [...documentSources, ...mcpSources].map(+ (source) => source.documentId ?? source.filename,+ ),).size;const sourceCount = sources.length + documentCount;return (@@ -131,6 +130,7 @@ export function ResearchMessage(): ReactElement | null {/><SourcesGroup sources={sources} allowRemoteIcons={false} /><DocumentSourcesGroup sources={documentSources} />+ <DocumentSourcesGroup sources={mcpSources} label="MCP Sources" /></div>);}@@ -138,7 +138,7 @@ export function ResearchMessage(): ReactElement | null {const failed = run.status === "failed";const cancelled = run.status === "cancelled";const needsApproval = run.status === "awaiting_approval";- // Name the current model call, so the long silent phases read as work rather than a stall.+ // name the model call so long silent phases do not appear stalled.const liveDetail =runningResearchActivityTitle(session?.activities) ??run.plan?.title ??diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex e856d435e6a..1ba870104b0 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -81,6 +81,7 @@ import {} from "../utils/chat-settings-storage";import {loadShadowOwnsMirroredSetting,+ normalizeResearchMcpSources,MAX_RESEARCH_MODEL_TIMEOUT_SECONDS,MIN_FINITE_RESEARCH_MODEL_TIMEOUT_SECONDS,normalizeStoredPermissionMode,@@ -112,7 +113,10 @@ import {} from "../utils/model-lifecycle-gate";import { shouldAdvanceQueuedSettingsEpoch } from "../utils/queued-settings-epoch";import type { MmprojFallbackReason } from "../types/api";-import type { ResearchWebsitePolicy } from "../types/research";+import type {+ ResearchMcpSource,+ ResearchWebsitePolicy,+} from "../types/research";import {CHAT_GPU_MEMORY_MODE_KEY,CHAT_SPECULATIVE_TYPE_KEY,@@ -134,6 +138,9 @@ export const CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY ="unsloth_chat_deep_research_website_policy";export const CHAT_DEEP_RESEARCH_MODEL_TIMEOUT_KEY ="unsloth_chat_deep_research_model_timeout";+export const CHAT_DEEP_RESEARCH_MCP_SOURCES_KEY =+ "unsloth_chat_deep_research_mcp_sources";+export { MAX_RESEARCH_MCP_SOURCES } from "../utils/mirrored-chat-settings";export const CHAT_COLLAPSE_HTML_ARTIFACTS_KEY ="unsloth_chat_collapse_html_artifacts";export const CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY =@@ -248,6 +255,19 @@ function loadResearchWebsitePolicy(): ResearchWebsitePolicy {}}+function loadResearchMcpSources(): ResearchMcpSource[] {+ if (typeof window === "undefined") return [];+ try {+ return normalizeResearchMcpSources(+ JSON.parse(+ window.localStorage.getItem(CHAT_DEEP_RESEARCH_MCP_SOURCES_KEY) || "[]",+ ),+ );+ } catch {+ return [];+ }+}+function saveResearchWebsitePolicy(policy: ResearchWebsitePolicy): void {persistSetting(CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY, JSON.stringify(policy));}@@ -701,6 +721,10 @@ const MIRRORED_SETTINGS = {storageKey: CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY,...JSON_SETTING,},+ researchMcpSources: {+ storageKey: CHAT_DEEP_RESEARCH_MCP_SOURCES_KEY,+ ...JSON_SETTING,+ },researchModelTimeoutSeconds: {storageKey: CHAT_DEEP_RESEARCH_MODEL_TIMEOUT_KEY,...NUMBER_SETTING,@@ -2336,31 +2360,30 @@ type ChatRuntimeStore = {/** Whether the provider exposes server-side image generation (OpenAI Responses API).* Local models never receive it. */supportsBuiltinImageGeneration: boolean;- /** Whether the provider exposes server-side web_fetch (Anthropic `web_fetch_*`). Gates the- * composer's Fetch pill, independent of Search. */+ /** Anthropic server-side web_fetch_* gates Fetch independently of Search. */supportsBuiltinWebFetch: boolean;- /** Mirrors the backend Settings switch "Keep multiple models loaded". */+ /** mirrors the backend Settings switch "Keep multiple models loaded". */keepModelsLoaded: boolean;toolsEnabled: boolean;- /** Persisted Code preference. Use codeToolsOn() for the effective value. */+ /** persisted Code preference; codeToolsOn() gives the effective value. */codeToolsEnabled: boolean;- /** Session-only: a manual Code-off under Full access, so the grant is not re-applied over it.- * Cleared on entering or leaving the level. */+ /** session-only Code opt-out under Full access; cleared on level changes. */codeToolsDeclinedUnderFullAccess: boolean;imageToolsEnabled: boolean;deepResearchEnabled: boolean;researchWebsitePolicy: ResearchWebsitePolicy;researchModelTimeoutSeconds: number;- // Whether the Canvas toggle is offered in the composer + menu (hidden by default).+ researchMcpSources: ResearchMcpSource[];+ // offers the Canvas toggle in the composer + menu; hidden by default.collapseHtmlArtifacts: boolean;allowArtifactNetworkAccess: boolean;- // web_search also returns images the model can place inline; read by the backend per call.+ // backend reads per call: web_search returns images for inline model output.searchImages: boolean;mcpEnabledForChat: boolean;ragEnabled: boolean;ragSource: RagSource;projectAttachmentTarget: ProjectAttachmentTarget;- /** Per-chat override of that default, so a pick in one chat does not redirect the rest. Session-only. */+ /** session-only per-chat target override; leaves other chats unchanged. */projectAttachmentTargetByThread: Record<string, ProjectAttachmentTarget>;ragMode: RagMode;ragTopK: number;@@ -2648,6 +2671,7 @@ type ChatRuntimeStore = {setDeepResearchEnabled: (enabled: boolean) => void;setResearchWebsitePolicy: (policy: ResearchWebsitePolicy) => void;setResearchModelTimeoutSeconds: (seconds: number) => void;+ setResearchMcpSources: (sources: ResearchMcpSource[]) => void;setCollapseHtmlArtifacts: (enabled: boolean) => void;setAllowArtifactNetworkAccess: (enabled: boolean) => void;setSearchImages: (enabled: boolean) => void;@@ -2762,6 +2786,7 @@ type ScalarSettingKey =| "webFetchToolsEnabled"| "deepResearchEnabled"| "researchWebsitePolicy"+ | "researchMcpSources"| "researchModelTimeoutSeconds"| "mcpEnabledForChat"| "confirmToolCalls"@@ -2812,6 +2837,7 @@ const SCALAR_SETTING_KEYS = ["webFetchToolsEnabled","deepResearchEnabled","researchWebsitePolicy",+ "researchMcpSources","researchModelTimeoutSeconds","mcpEnabledForChat","confirmToolCalls",@@ -4158,6 +4184,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({deepResearchEnabled: loadBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false),researchWebsitePolicy: loadResearchWebsitePolicy(),researchModelTimeoutSeconds: loadResearchModelTimeoutSeconds(),+ researchMcpSources: loadResearchMcpSources(),collapseHtmlArtifacts: loadBool(CHAT_COLLAPSE_HTML_ARTIFACTS_KEY, false),allowArtifactNetworkAccess: loadBool(CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY,@@ -4165,11 +4192,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({),searchImages: loadBool(CHAT_SEARCH_IMAGES_KEY, false),mcpEnabledForChat: loadBool(CHAT_MCP_ENABLED_KEY, false),- // Mirrors permissionMode (gate requested for ask/auto) so both controls agree on load.+ // mirrors permissionMode so both controls agree on load.confirmToolCalls:INITIAL_PERMISSION_MODE === "ask" || INITIAL_PERMISSION_MODE === "auto",- // Never restore Bypass Permissions from storage: it disables the sandbox and the- // confirmation gate, so it needs the warning dialog each session.+ // no stored bypass: sandbox and gate removal needs a warning each session.bypassPermissions: false,permissionMode: INITIAL_PERMISSION_MODE,sandboxLevel: loadSandboxLevel(),@@ -5416,6 +5442,18 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}),+ setResearchMcpSources: (researchMcpSources) =>+ set((state) => {+ const sources = normalizeResearchMcpSources(researchMcpSources);+ persistSetting(+ CHAT_DEEP_RESEARCH_MCP_SOURCES_KEY,+ JSON.stringify(sources),+ );+ return {+ researchMcpSources: sources,+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),setCollapseHtmlArtifacts: (collapseHtmlArtifacts) =>set(() => {saveBool(CHAT_COLLAPSE_HTML_ARTIFACTS_KEY, collapseHtmlArtifacts);diff --git a/studio/frontend/src/features/chat/types/research.ts b/studio/frontend/src/features/chat/types/research.tsindex 61f1c5997e7..aab24b9da7a 100644--- a/studio/frontend/src/features/chat/types/research.ts+++ b/studio/frontend/src/features/chat/types/research.ts@@ -31,7 +31,7 @@ export interface ResearchPlan {}export interface ResearchEvidenceSource {- kind: "knowledge_base";+ kind: "knowledge_base" | "mcp";chunkId?: string | null;documentId?: string | null;filename: string;@@ -88,7 +88,7 @@ export interface ResearchBudgets {maxSources: number;modelTimeoutSeconds: number;toolTimeoutSeconds: number;- // Optional: runs created before this budget existed do not carry it.+ // runs created before this budget existed do not carry it.firstOutputTimeoutSeconds?: number;}@@ -97,16 +97,22 @@ export interface ResearchWebsitePolicy {blockedDomains: string[];}+export interface ResearchMcpSource {+ serverId: string;+ tool: string;+}+export interface CreateResearchRunInput {threadId: string;userMessageId: string;assistantMessageId?: string;inferenceRequest: ResearchInferenceRequest;ragScope?: Record<string, unknown>;+ mcpSources?: ResearchMcpSource[];budgets?: Partial<ResearchBudgets>;websitePolicy?: ResearchWebsitePolicy;instructions?: string;- /** The question the model handed off, which is what gets researched. */+ /** research the question handed off by the model. */question?: string;}diff --git a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.tsindex 92436a39b33..553d9327d19 100644--- a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts+++ b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts@@ -7,6 +7,35 @@// reaches the backend, which rejects the whole patch on a single out-of-contract field.import type { PersistedChatSettings } from "../api/chat-settings-api";+import type { ResearchMcpSource } from "../types/research";++export const MAX_RESEARCH_MCP_SOURCES = 20;++export function normalizeResearchMcpSources(value: unknown): ResearchMcpSource[] {+ if (!Array.isArray(value)) return [];+ const sources: ResearchMcpSource[] = [];+ const seen = new Set<string>();+ for (const item of value) {+ const serverId = item?.serverId;+ const tool = item?.tool;+ if (+ typeof serverId !== "string" ||+ serverId.length < 1 ||+ serverId.length > 200 ||+ typeof tool !== "string" ||+ tool.length < 1 ||+ tool.length > 500+ ) {+ continue;+ }+ const key = `${serverId}\0${tool}`;+ if (seen.has(key)) continue;+ seen.add(key);+ sources.push({ serverId, tool });+ if (sources.length === MAX_RESEARCH_MCP_SOURCES) break;+ }+ return sources;+}const MIRRORED_BOOLEAN_KEYS = ["reasoningEnabled",@@ -70,6 +99,7 @@ export const MIRRORED_SETTING_KEYS = [MIRRORED_NUMBER_BOUNDS,) as (keyof typeof MIRRORED_NUMBER_BOUNDS)[]),"researchWebsitePolicy",+ "researchMcpSources","ragSource",] as const satisfies readonly (keyof PersistedChatSettings)[];@@ -164,6 +194,11 @@ export function assignSanitizedMirroredSettings(if (researchWebsitePolicy) {settings.researchWebsitePolicy = researchWebsitePolicy;}+ if (Array.isArray(value.researchMcpSources)) {+ settings.researchMcpSources = normalizeResearchMcpSources(+ value.researchMcpSources,+ );+ }const ragSource = sanitizeRagSource(value.ragSource);if (ragSource) settings.ragSource = ragSource;}diff --git a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.tsindex e1721e8b7e9..7f33397c174 100644--- a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts@@ -27,6 +27,7 @@ const QUEUED_SETTING_KEYS = ["webFetchToolsEnabled","deepResearchEnabled","researchWebsitePolicy",+ "researchMcpSources","researchModelTimeoutSeconds","ragEnabled","ragSource",diff --git a/studio/frontend/src/features/chat/utils/research-citations.ts b/studio/frontend/src/features/chat/utils/research-citations.tsnew file mode 100644index 00000000000..c0a922550f5--- /dev/null+++ b/studio/frontend/src/features/chat/utils/research-citations.ts@@ -0,0 +1,20 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { Citation } from "@/components/assistant-ui/citation-utils";+import type { ResearchDocumentSource } from "../types/research";++export function researchCitation(+ source: ResearchDocumentSource,+ index: number,+): Citation {+ return {+ id: source.chunkId ?? String(source.id ?? index),+ filename: source.filename,+ page: source.page,+ score: source.score,+ text: source.snippet ?? "",+ documentId: source.kind === "mcp" ? undefined : source.documentId,+ chunkId: source.chunkId,+ };+}diff --git a/studio/frontend/tests/research-citations.test.ts b/studio/frontend/tests/research-citations.test.tsnew file mode 100644index 00000000000..5dd13298cb5--- /dev/null+++ b/studio/frontend/tests/research-citations.test.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import { researchCitation } from "../src/features/chat/utils/research-citations.ts";++test("MCP citations cannot open a RAG document preview, including stored reports", () => {+ const source = {+ kind: "mcp" as const,+ documentId: "mcp__notes__search",+ filename: "Notes",+ snippet: "A fact",+ };+ assert.equal(researchCitation(source, 0).documentId, undefined);+ assert.equal(researchCitation(source, 0).text, "A fact");+ assert.equal(+ researchCitation(+ { ...source, kind: "knowledge_base", documentId: "doc-1" },+ 0,+ ).documentId,+ "doc-1",+ );+});diff --git a/studio/frontend/tests/research-mcp-settings.test.ts b/studio/frontend/tests/research-mcp-settings.test.tsnew file mode 100644index 00000000000..016d0b0f609--- /dev/null+++ b/studio/frontend/tests/research-mcp-settings.test.ts@@ -0,0 +1,38 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+import { installLocalStorageFake } from "./helpers/kit.ts";+import { settingsHttp } from "./helpers/store-stubs/settings-http.ts";+import { snapshotQueuedChatRunSettings } from "../src/features/chat/utils/queued-chat-run-settings.ts";++const { store: storage } = installLocalStorageFake();+storage.set("unsloth_chat_settings_imported_to_studio_db", "true");+register("./store-settings-resolver.mjs", import.meta.url);+const { useChatRuntimeStore, flushPendingChatSettings } = await import(+ "../src/features/chat/stores/chat-runtime-store.ts"+);+const original = [{ serverId: "notes", tool: "search_notes" }];+const later = [{ serverId: "papers", tool: "search_papers" }];++test("MCP sources hydrate from the account and saves reach another session", async () => {+ settingsHttp.settings = { researchMcpSources: original };+ await useChatRuntimeStore.getState().hydratePersistedSettings();+ assert.deepEqual(useChatRuntimeStore.getState().researchMcpSources, original);+ useChatRuntimeStore.getState().setResearchMcpSources(later);+ await flushPendingChatSettings();+ assert.deepEqual(settingsHttp.puts.at(-1)?.researchMcpSources, later);+ useChatRuntimeStore.getState().setResearchMcpSources([]);+ await flushPendingChatSettings();+ assert.deepEqual(settingsHttp.puts.at(-1)?.researchMcpSources, []);+});++test("queued research retains the MCP sources selected when sent", () => {+ useChatRuntimeStore.getState().setResearchMcpSources(original);+ const queued = snapshotQueuedChatRunSettings(useChatRuntimeStore.getState());+ useChatRuntimeStore.getState().setResearchMcpSources(later);+ const runtime = { ...useChatRuntimeStore.getState(), ...queued };+ assert.deepEqual(runtime.researchMcpSources, original);+});diff --git a/studio/frontend/tests/research-mcp-source-limit.test.ts b/studio/frontend/tests/research-mcp-source-limit.test.tsnew file mode 100644index 00000000000..2522504f5ab--- /dev/null+++ b/studio/frontend/tests/research-mcp-source-limit.test.ts@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake } from "./helpers/kit.ts";++const { store: localStorageFake } = installLocalStorageFake();+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");+const sources = Array.from({ length: 21 }, (_, index) => ({+ serverId: `server-${index}`,+ tool: `search-${index}`,+}));+localStorageFake.set(+ "unsloth_chat_deep_research_mcp_sources",+ JSON.stringify([...sources, sources[0], { serverId: "", tool: "search" }]),+);+register("./store-settings-resolver.mjs", import.meta.url);++const { MAX_RESEARCH_MCP_SOURCES, useChatRuntimeStore } = await import(+ "../src/features/chat/stores/chat-runtime-store.ts"+);++test("MCP research sources stay within the backend request limit", () => {+ assert.equal(MAX_RESEARCH_MCP_SOURCES, 20);+ assert.deepEqual(+ useChatRuntimeStore.getState().researchMcpSources,+ sources.slice(0, MAX_RESEARCH_MCP_SOURCES),+ );++ const settingsEpoch = useChatRuntimeStore.getState().queuedSettingsEpoch;+ useChatRuntimeStore+ .getState()+ .setResearchMcpSources([+ ...sources,+ sources[0],+ { serverId: "server", tool: "" },+ ]);+ assert.deepEqual(+ useChatRuntimeStore.getState().researchMcpSources,+ sources.slice(0, MAX_RESEARCH_MCP_SOURCES),+ );+ assert.equal(+ useChatRuntimeStore.getState().queuedSettingsEpoch,+ settingsEpoch + 1,+ );+ assert.deepEqual(+ JSON.parse(+ localStorageFake.get("unsloth_chat_deep_research_mcp_sources") || "[]",+ ),+ sources.slice(0, MAX_RESEARCH_MCP_SOURCES),+ );+});