๐ Feature: Render MCP Apps (interactive tool UIs) in chat, starting with Excalidraw
๐ Feature description
Render MCP Apps in chat: interactive UIs that an MCP server ships with its tools, shown inline in the answer. The first target is Excalidraw's hosted MCP server (https://mcp.excalidraw.com/mcp, no sign-in), whose create_view tool draws a live, animated hand-drawn diagram.
MCP Apps is the official MCP extension io.modelcontextprotocol/ui (SEP-1865). A tool declares a UI with _meta.ui.resourceUri: "ui://...". The host reads that resource (resources/read, mimeType text/html;profile=mcp-app), renders it in a sandboxed iframe, and talks to it over postMessage JSON-RPC. Claude, ChatGPT, VS Code Copilot, Cursor and Goose already support it.
DocsGPT doesn't support it yet. In docsgpt/agents/tools/mcp_tool.py:
_format_toolsandget_actions_metadatadrop each tool's_meta.resources/readis never called._format_resultflattens results to a string, sostructuredContentis lost.
So Excalidraw's create_view returns "Canvas โฆ is rendering" and nothing is drawn.
๐ค Why is this feature needed?
A growing number of MCP servers ship UIs that are much better than text: diagrams (Excalidraw), hotel and ferry search results (trivago, Ferryhopper) and canvases (tldraw). Supporting the standard once makes all of them work in DocsGPT without per-server code.
โ๏ธ How do you aim to achieve this?
This is a larger feature, not a good first issue. Please comment with your plan before starting, especially for the sandbox origin (see "Security").
Spec: stable 2026-01-26 ยท draft ยท reference host. Phase 1 targets the stable spec.
Backend
- Advertise support. In
_setup_client(docsgpt/agents/tools/mcp_tool.py), passextensions={"io.modelcontextprotocol/ui": {"mimeTypes": ["text/html;profile=mcp-app"]}}to the fastmcpClient. The pinned fastmcp acceptsextensions=. - Gate it behind a setting in
docsgpt/core/settings.py, so the feature can be turned off. - Keep the UI metadata. Keep
_meta.ui.resourceUri(and the deprecated flat_meta["ui/resourceUri"]) and_meta.ui.visibilityin the tool metadata. - Respect visibility.
- Tools whose
visibilitylacks"model"must not be offered to the LLM. Excalidraw'sexport_to_excalidraw,save_checkpointandread_checkpointare app-only. - Calls from the app to tools whose
visibilitylacks"app"must be rejected.
- Tools whose
- Read the UI resource. Add a
read_resourceoperation next tocall_toolin_run_async_operation.- Validate the
ui://scheme and the mimeType. - Read
_meta.ui(csp,permissions,prefersBorder) from the content item, falling back to theresources/listentry. - Cache the HTML per server and URI. Excalidraw's is about 450 KB.
- Validate the
- Keep that HTML out of the LLM context and out of the persisted
tool_callsrecord. Serve it from its own endpoint instead. - Attach UI info to the tool call.
- Add a small
uipayload (resource URI, connection, display hints) to thetool_callevent, using the same pattern as theget_artifactshook indocsgpt/agents/tool_executor.py. - Add it to
_PRESERVED_TOOL_CALL_KEYS, so the widget renders again when the conversation is reopened. - The widget needs the real
CallToolResult(contentplusstructuredContent), not the 2,000-characterstr()that is persisted today. Keep it in the event and the journal.
- Add a small
- Add authenticated endpoints for the widget, scoped to the user's own conversation:
- read the UI resource
- proxy
tools/call(and optionallyresources/read) from the app to the MCP server
- Approvals must apply to app calls. A widget-initiated
tools/callmust go through the same permission checks as an agent call (docsgpt/connectors/permissions.pyaction_permission, and the approval gate intool_executor.pycheck_pause). A write that needs approval must prompt; it must not bypass approval.
Frontend
- New answer step. In
frontend/src/conversation/AnswerFlow.tsx, add a branch for tool calls that carryuiand render anMcpAppViewinside the sharedToolCallCardframe.SchedulerToolCallCardis an existing example of a per-tool card. - Host bridge. Use
AppBridgefrom@modelcontextprotocol/ext-apps/app-bridgewithclient = null, and route its handlers to the backend endpoints. Check its peer dependencies (TS SDK v2, zod 4) and the bundle size.@mcp-ui/client'sAppRendereris the alternative. - Messages to implement in phase 1:
ui/initializeandui/notifications/initializedui/notifications/tool-inputandtool-resultui/notifications/size-changedui/notifications/host-context-changed, sending theme, locale and thestyles.variablesmapped from our tokens insrc/index.css, and again when the theme changesui/open-link, opening a new tab withnoopener- proxied
tools/call ui/resource-teardown
- Phase 2 (follow-ups are fine):
ui/request-display-mode, wherefullscreenopens the docked side panel (ArtifactPanel,PanelBody scroll={false})ui/messageui/update-model-context
- Fallback. When the feature is off or the UI fails to load, fall back to the existing
InlineToolCallChip. A failed load showsEmptyState tone="destructive"with retry.
Security
- Follow the spec's Security section: the View runs in a double iframe. The outer sandbox proxy runs on an origin different from the app, and the inner iframe runs with
sandboxand a CSP built only from the resource's_meta.ui.csp. Excalidraw declaresesm.shforresourceDomainsandconnectDomains. - With no
csp, the restrictive default applies. Undeclared domains are never allowed.permissionsmap to the inner iframe'sallowattribute (Excalidraw asks forclipboardWrite). - The sandbox origin has to work for self-hosters too, for example a configurable sandbox URL or subdomain. Propose an approach in your plan comment.
- Today no iframe in
frontend/srcallows scripts and nothing usespostMessage, so this is new surface. Keep it narrow and well tested.
Design (frontend/DESIGN.md and frontend/PATTERNS.md)
- Components and layout
- Compose existing
ui/components and theToolCallCardframe; don't create a new card. classNameis for placement only.- The card sits in the chat answer column (
w-full min-w-0, on themr-5 ml-6step column) and never scrolls sideways.
- Compose existing
- Colour and shape
- Theme tokens only. No raw Tailwind palette, no arbitrary
[...]values. - Check both light and dark themes.
- One card radius (
rounded-2xl), no shadow, no fill on a fill. - Card state is a
Badge.
- Theme tokens only. No raw Tailwind palette, no arbitrary
- Controls and states
- Icon-only actions (expand, open in panel, reload) are
IconButtonwith alabel. - Loading uses
LoadingState. Errors useEmptyStateorAlert, never a baretext-destructiveparagraph.
- Icon-only actions (expand, open in panel, reload) are
- Sizing
- The iframe height reported by
size-changedgoes through a CSS custom property, not ad-hoc inline styles. - Cap the height with
svh, nevervh.
- The iframe height reported by
- Motion and focus
- Entrance uses
animate-in fade-in duration-200 motion-reduce:animate-none. Don't usetransition-all. - Use the standard focus ring. Use only the documented z-index levels.
- Entrance uses
- Text: every user-visible string,
aria-labelandtitleincluded, is at()key in all seven locales (de en es jp ru zh zh-TW). - Design page: add the new card's states to the
/designpage.
Acceptance criteria
- With Excalidraw connected, asking an agent to "draw a diagram of how DocsGPT ingests a PDF" renders the live Excalidraw canvas inline in the answer. It looks right in light and dark themes and at phone width.
- Reopening the conversation renders the widget again.
- App-only tools are not offered to the model, and the app can't call model-only tools.
- A widget-initiated write call respects the tool's permission (ask, always or off).
- The widget can't reach domains outside its declared
csp. The CSP builder and the visibility rules have unit tests. - MCP servers without UIs, and DocsGPT with the setting off, behave exactly as today.
ruff check .,python -m pytest,cd frontend && npm run lintandcd frontend && npm run buildpass.
๐๏ธ Additional Information
Please attach a short video of the Excalidraw diagram drawing itself in the chat, in both themes.
The Excalidraw connector preset is tracked separately in #2914.
The spec's examples/basic-host (sandbox.ts) is the best reference for the sandbox proxy.
Hi! I would love to work on this issue. /assign me
@abhijeetnardele24-hash, you're assigned.
- Open a PR or post progress within 14 days; otherwise the issue may be reassigned.
- Read
CONTRIBUTING.mdandfrontend/DESIGN.mdbefore starting. - Include a screenshot or short recording of the UI change in your PR, and unit tests for backend behaviour.
Automated triage. A maintainer will follow up.
I'd like to work on this, starting with the harness/result contract before the UI. Proposed sequence against current main b6b43b67:
- Keep failure semantics through the existing executor. I executed the unmodified
_format_resultandresult_statusfunctions extracted from this revision: both FastMCPis_error=Trueand MCPisError=Truebecome{"content": [...], "isError": true}, butresult_statusreturnscompleted. The executor uses that function for the streamed/persisted call status. Both false controls remain completed. This is an isolated function-level reproduction, not a full application or remote-server run. A small prerequisite fix should recognize an explicit booleanisErrorand test the event plus conversation-reload status; the journal's execution/confirmation states should retain their separate meanings. - Add the bounded UI/result contract behind the setting. Preserve UI metadata/visibility and a typed CallToolResult for the widget, alongside the existing model-readable result. Main already has a bounded
result_fullcopy, so that field alone does not preserve typed structured content or the widget's reload metadata. Keep resource HTML out of model messages and conversation records, and add only the required small keys to the persisted projection. Include both-content-and-structuredContent coverage, beyond #2949's empty-content fallback. - Use one authorization path. Conversation-owned resource/proxy endpoints should use the same connection resolution, action permissions and approval gate as agent calls. Tests should cover app-only/model-only visibility, another user's conversation, disabled actions and an approval-required write before enabling the bridge.
- Sandbox first, then render. Use a configured separate-origin sandbox proxy for the outer iframe and the restrictive inner iframe/CSP described above. Self-hosters can provide that origin/subdomain; without a valid separate origin, keep the widget disabled and use the existing fallback. Do not weaken isolation to make same-origin installs work. Then integrate AppBridge into ToolCallCard and validate Excalidraw, reload, theme/locale, phone width and teardown.
I have checked the existing assignment and open PRs; please flag any unpublished implementation so we can coordinate rather than duplicate it. I would split these stages into independently reviewable changes. No UI implementation or end-to-end validation is claimed by this plan.
@Protocol-zero-0, @abhijeetnardele24-hash is already assigned and is still within the 14-day progress window. You'll be next if the assignment becomes available.
PR #2947 adds the Excalidraw connector preset, not the inline MCP Apps UI, so it does not replace this work. Please coordinate any split of the implementation here before starting.
Automated triage. A maintainer will follow up.
A narrow harness prerequisite is ready against main fe137a4d. This does not implement the assigned MCP Apps UI.
result_status needs to recognize the explicit MCP boolean isError: true. The patch below preserves HTTP/in-band errors, success results, the existing execution journal, and the bounded stream/persistence projection. String/integer lookalikes do not become MCP failures.
Validation: 26 runs of the intact executor generator/wrapper and projection methods, extracted from that revision with external services mocked. The baseline reproduces false completion; the patched 13-case matrix passes. The seven proposed regression cases below also ran in that isolated harness: baseline 2 failed, 5 passed, patch 7 passed. Both the streamed event and a JSON roundtrip of get_truncated_tool_calls() retain the correct status, while the side-effect journal is still marked executed. The two-file patch dry-applies to the pinned source.
This is an apply-ready patch, not a submitted or merged PR. Full application imports, PostgreSQL persistence, browser reload, a remote MCP server and UI integration have not been tested. The reload check here is the persisted projection plus JSON roundtrip.
On the assignment: I saw the automated progress-window reminder. I am keeping this independent harness fix separate from UI implementation; a maintainer-confirmed split can settle the UI ownership before that stage.
--- a/docsgpt/agents/tool_executor.py
+++ b/docsgpt/agents/tool_executor.py
@@ -281,7 +281,7 @@
"""Derive the persisted status from a tool's result payload.
Tools report failure in-band (``{"status": "error", ...}`` or an ``error``
- key) while the executor used to stamp every returned result ``completed``,
+ key) or an MCP ``isError: true`` result, while the executor used to stamp every returned result ``completed``,
so the stored conversation showed failed calls as successes. HTTP-backed
tools (cryptoprice, api_tool, ntfy, duckduckgo) report an integer
``status_code`` instead, and a 4xx/5xx there is a failure too.
@@ -294,7 +294,7 @@
"""
if not isinstance(result, dict):
return "completed"
- if result.get("status") == "error" or result.get("error"):
+ if result.get("isError") is True or result.get("status") == "error" or result.get("error"):
return "error"
code = result.get("status_code")
if isinstance(code, int) and not isinstance(code, bool) and code >= 400:
--- a/tests/agents/test_tool_executor.py
+++ b/tests/agents/test_tool_executor.py
@@ -1068,6 +1068,48 @@
assert "pending" in statuses
assert "completed" in statuses
+ @pytest.mark.parametrize(
+ "flag, expected",
+ [(True, "error"), (False, "completed"), (None, "completed"),
+ ("false", "completed"), (1, "completed")],
+ )
+ def test_result_status_reads_boolean_mcp_error_flag(self, flag, expected):
+ from docsgpt.agents.tool_executor import result_status
+
+ assert result_status({"content": [], "isError": flag}) == expected
+
+ @pytest.mark.parametrize("flag, expected", [(True, "error"), (False, "completed")])
+ def test_mcp_status_survives_stream_and_persisted_projection(self, monkeypatch, flag, expected):
+ import json
+ from docsgpt.agents import tool_executor as module
+
+ executor = ToolExecutor()
+ result = {"content": [{"type": "text", "text": "tool result"}], "isError": flag}
+ tool = Mock(spec=["execute_action"])
+ tool.execute_action.return_value = result
+ monkeypatch.setattr(executor, "_get_or_load_tool", lambda *a, **kw: tool)
+ monkeypatch.setattr(module, "ToolActionParser", lambda *a, **kw: Mock(
+ parse_args=Mock(return_value=("t1", "test_action", {}))))
+ monkeypatch.setattr(module, "_record_proposed", Mock(return_value=True))
+ executed = Mock()
+ failed = Mock()
+ monkeypatch.setattr(module, "_mark_executed", executed)
+ monkeypatch.setattr(module, "_mark_failed", failed)
+ tools = {"t1": {"id": "test-id", "name": "mcp_tool", "actions": [
+ {"name": "test_action", "parameters": {"properties": {}}}]}}
+
+ events = list(executor.execute(tools, self._make_call(), "MockLLM"))
+ stored = json.loads(json.dumps(executor.get_truncated_tool_calls()))
+
+ assert events[0]["data"]["status"] == "pending"
+ assert events[-1]["data"]["status"] == expected
+ assert stored[0]["status"] == expected
+ assert "result_full" not in events[-1]["data"]
+ assert "result_full" not in stored[0]
+ tool.execute_action.assert_called_once()
+ executed.assert_called_once()
+ failed.assert_not_called()
+
def test_get_truncated_tool_calls(self):
from docsgpt.agents.tool_executor import PERSISTED_RESULT_MAX_LEN
@dartpain can I get this issue assigned ? I would like to work on this issue. I ll actively work on the fix , thanks
@Protocol-zero-0, you're assigned as the earliest eligible claimant. @bhushan4work, you're next if the issue becomes available.
- Open a PR or post progress within 14 days; otherwise the issue may be reassigned.
- Read
CONTRIBUTING.mdandfrontend/DESIGN.mdbefore starting. - Include a screenshot or short recording of the UI change in your PR, and tests for backend behaviour.
PR #2947 adds the Excalidraw connector preset, not the inline MCP Apps UI, so it does not replace this work.
Automated triage. A maintainer will follow up.
Backend progress on the narrow isError prerequisite: the patch is now validated against main 81acd559 through normal production executor imports and the project's PostgreSQL fixtures, replacing the earlier AST-only validation limitation.
- The seven new classifier/stream/projection regressions reproduce 2 failures / 5 passes on the unmodified executor, then all seven pass with the explicit
isError is Truecheck. - Two additional tests use the installed FastMCP
CallToolResulttype, execute throughToolExecutor, write the projection throughConversationsRepository, and reload the real PostgreSQL JSONB row. The error case fails on the baseline; the success control passes. Both pass with the patch. Stream and reloaded conversation status agree, and the actualtool_call_attemptsrow remainsexecuted: an in-band tool failure does not mean the invocation did not run. - The complete executor and MCP-tool test files pass together: 249 passed, 21 skipped.
ruff check .passes. PostgreSQL 16.15 runs in the suite's disposable cluster with the full migration chain; Python 3.13.11 on Linux.
The tool/network response is stubbed. This does not claim a full Flask application run, browser reload, remote MCP server, or the inline Apps UI. The backend status fix is independent of the UI and preserves the existing permission/approval paths. I remain on #2913 and will build the UI stages on the previously proposed separate-origin sandbox plan.
Updated two-file patch against the current main:
diff --git a/docsgpt/agents/tool_executor.py b/docsgpt/agents/tool_executor.py
index 0794189..d17ae6e 100644
--- a/docsgpt/agents/tool_executor.py
+++ b/docsgpt/agents/tool_executor.py
@@ -281,7 +281,8 @@ def result_status(result: Any) -> str:
"""Derive the persisted status from a tool's result payload.
Tools report failure in-band (``{"status": "error", ...}`` or an ``error``
- key) while the executor used to stamp every returned result ``completed``,
+ key) or the MCP boolean ``isError: true``. The executor used to stamp
+ every returned result ``completed``,
so the stored conversation showed failed calls as successes. HTTP-backed
tools (cryptoprice, api_tool, ntfy, duckduckgo) report an integer
``status_code`` instead, and a 4xx/5xx there is a failure too.
@@ -294,7 +295,7 @@ def result_status(result: Any) -> str:
"""
if not isinstance(result, dict):
return "completed"
- if result.get("status") == "error" or result.get("error"):
+ if result.get("isError") is True or result.get("status") == "error" or result.get("error"):
return "error"
code = result.get("status_code")
if isinstance(code, int) and not isinstance(code, bool) and code >= 400:
diff --git a/tests/agents/test_tool_executor.py b/tests/agents/test_tool_executor.py
index aca34fa..bd8c477 100644
--- a/tests/agents/test_tool_executor.py
+++ b/tests/agents/test_tool_executor.py
@@ -1068,6 +1068,113 @@ class TestToolExecutorExecute:
assert "pending" in statuses
assert "completed" in statuses
+ @pytest.mark.parametrize(
+ "flag, expected",
+ [(True, "error"), (False, "completed"), (None, "completed"),
+ ("false", "completed"), (1, "completed")],
+ )
+ def test_result_status_reads_boolean_mcp_error_flag(self, flag, expected):
+ """Only the explicit MCP boolean true marks a result as failed."""
+ from docsgpt.agents.tool_executor import result_status
+
+ assert result_status({"content": [], "isError": flag}) == expected
+
+ @pytest.mark.parametrize("flag, expected", [(True, "error"), (False, "completed")])
+ def test_mcp_status_survives_stream_and_persisted_projection(self, monkeypatch, flag, expected):
+ """Stream and persisted projection agree without changing journal semantics."""
+ import json
+ from docsgpt.agents import tool_executor as module
+
+ executor = ToolExecutor()
+ result = {"content": [{"type": "text", "text": "tool result"}], "isError": flag}
+ tool = Mock(spec=["execute_action"])
+ tool.execute_action.return_value = result
+ monkeypatch.setattr(executor, "_get_or_load_tool", lambda *a, **kw: tool)
+ monkeypatch.setattr(module, "ToolActionParser", lambda *a, **kw: Mock(
+ parse_args=Mock(return_value=("t1", "test_action", {}))))
+ monkeypatch.setattr(module, "_record_proposed", Mock(return_value=True))
+ executed = Mock()
+ failed = Mock()
+ monkeypatch.setattr(module, "_mark_executed", executed)
+ monkeypatch.setattr(module, "_mark_failed", failed)
+ tools = {"t1": {"id": "test-id", "name": "mcp_tool", "actions": [
+ {"name": "test_action", "parameters": {"properties": {}}}]}}
+
+ events = list(executor.execute(tools, self._make_call(), "MockLLM"))
+ stored = json.loads(json.dumps(executor.get_truncated_tool_calls()))
+
+ assert events[0]["data"]["status"] == "pending"
+ assert events[-1]["data"]["status"] == expected
+ assert stored[0]["status"] == expected
+ assert "result_full" not in events[-1]["data"]
+ assert "result_full" not in stored[0]
+ tool.execute_action.assert_called_once()
+ executed.assert_called_once()
+ failed.assert_not_called()
+
+ @pytest.mark.parametrize("flag, expected", [(True, "error"), (False, "completed")])
+ def test_mcp_error_status_roundtrips_postgres(self, pg_conn, monkeypatch, flag, expected):
+ """Keep MCP failure status through execution, JSONB storage and reload."""
+ from contextlib import contextmanager
+ import json
+
+ from fastmcp.client.client import CallToolResult
+ from mcp.types import TextContent
+ from sqlalchemy import text
+
+ from docsgpt.agents import tool_executor as module
+ from docsgpt.storage.db.repositories.conversations import ConversationsRepository
+ from docsgpt.storage.db.repositories.users import UsersRepository
+
+ @contextmanager
+ def transaction_connection():
+ yield pg_conn
+
+ UsersRepository(pg_conn).create("mcp-status-user")
+ conversations = ConversationsRepository(pg_conn)
+ conversation = conversations.create("mcp-status-user", name="MCP status")
+ message = conversations.reserve_message(
+ str(conversation["id"]), prompt="Call the tool", placeholder_response=""
+ )
+ executor = ToolExecutor(user="mcp-status-user")
+ executor.message_id = str(message["id"])
+ sdk_result = CallToolResult(
+ content=[TextContent(type="text", text="tool result")],
+ structured_content=None, meta=None, is_error=flag,
+ )
+ # Match MCPTool's public result envelope; the network/OAuth path is not exercised.
+ result = {
+ "content": [item.model_dump() for item in sdk_result.content],
+ "isError": sdk_result.is_error,
+ }
+ tool = Mock(spec=["execute_action"])
+ tool.execute_action.return_value = result
+ monkeypatch.setattr(executor, "_get_or_load_tool", lambda *a, **kw: tool)
+ monkeypatch.setattr(module, "db_session", transaction_connection)
+ monkeypatch.setattr(module, "ToolActionParser", lambda *a, **kw: Mock(
+ parse_args=Mock(return_value=("t1", "test_action", {}))))
+ tools = {"t1": {"id": "test-id", "name": "mcp_tool", "actions": [
+ {"name": "test_action", "parameters": {"properties": {}}}]}}
+
+ events = list(executor.execute(tools, self._make_call(), "MockLLM"))
+ conversations.update_message_by_id(
+ str(message["id"]), {"tool_calls": executor.get_truncated_tool_calls()}
+ )
+ reloaded = ConversationsRepository(pg_conn).get_messages(str(conversation["id"]))
+ stored = reloaded[0]["tool_calls"][0]
+ journal = pg_conn.execute(text(
+ "SELECT status, result FROM tool_call_attempts WHERE call_id = :call_id"
+ ), {"call_id": f"{message['id']}:c1"}).mappings().one()
+
+ assert events[0]["data"]["status"] == "pending"
+ assert events[-1]["data"]["status"] == stored["status"] == expected
+ assert stored["call_id"] == "c1"
+ assert "result_full" not in stored
+ assert "result_full" not in events[-1]["data"]
+ assert journal["status"] == "executed"
+ assert "tool result" in json.dumps(journal["result"])
+ tool.execute_action.assert_called_once()
+
def test_get_truncated_tool_calls(self):
from docsgpt.agents.tool_executor import PERSISTED_RESULT_MAX_LEN
The MCP Apps discovery/visibility prerequisite is ready against main efed1ec5.
The five-file patch below preserves normalized resourceUri and visibility from SDK objects and dictionaries through action discovery, PostgreSQL storage and the connector response. It supports the deprecated flat resource URI as a fallback, keeps unrelated server metadata out of that projection, and follows the stable visibility contract.
App-only tools are excluded from the model's schema and suggested tool names. A guessed legacy name or a stale name mapping is also rejected before connection resolution or tool loading, with the attempt recorded as failed. Missing visibility retains the model/app default; explicitly empty or malformed visibility fails closed. Model-visible writes still use the existing approval path. Existing connections need their actions rescanned to acquire metadata that earlier discovery discarded.
Validation on Linux/Python 3.13.11 with PostgreSQL 16.15:
- 23 new tests: unmodified main has 20 failures / 3 passing controls; the patch passes all 23.
- A real in-process FastMCP server goes through
list_toolsandMCPToolinto the model schema. A real PostgreSQL JSONB roundtrip checks action metadata, connector serialization and the reloaded model toolset. - The complete agent and connector test directories pass: 3,239 passed, 24 skipped.
ruff check .passes. The patch applies to its pinned base and produces the exact tested tree.
This is an independently applicable backend prerequisite, separate from the earlier isError patch. It does not advertise Apps support, add app-call endpoints, fetch/render resource HTML or enable a widget. Remote Excalidraw, browser isolation and the full backend suite remain untested. Next are the typed widget-result/resource contract and the separate-origin sandbox, before the frontend bridge.
Apply-ready patch against efed1ec5
diff --git a/docsgpt/agents/mcp_apps.py b/docsgpt/agents/mcp_apps.py
new file mode 100644
index 000000000..bbf7c01de
--- /dev/null
+++ b/docsgpt/agents/mcp_apps.py
@@ -0,0 +1,61 @@
+"""The discovery-time MCP Apps contract; no rendering or app execution."""
+
+from typing import Any
+
+
+def tool_ui_metadata(meta: Any) -> dict:
+ """Keep only the UI resource reference and visibility from tool metadata.
+
+ Args:
+ meta: A tool's wire ``_meta`` mapping (SDK models call it ``meta``).
+
+ Returns:
+ A detached ``ui`` mapping. Missing visibility keeps the protocol's
+ model/app default; explicitly empty or malformed visibility allows
+ neither. Arbitrary server metadata and resource HTML are not copied.
+ """
+ if not isinstance(meta, dict):
+ return {}
+ raw = meta.get("ui", {})
+ if not isinstance(raw, dict):
+ return {"visibility": []}
+ ui = {}
+ uri = raw.get("resourceUri", meta.get("ui/resourceUri"))
+ if isinstance(uri, str) and uri.startswith("ui://") and len(uri) > 5 and not any(c.isspace() for c in uri):
+ ui["resourceUri"] = uri
+ if "visibility" in raw:
+ visibility = raw["visibility"]
+ ui["visibility"] = (
+ list(dict.fromkeys(visibility))
+ if isinstance(visibility, list) and all(v in ("model", "app") for v in visibility)
+ else []
+ )
+ return ui
+
+
+def model_visible(tool: dict, action: dict) -> bool:
+ """Whether a stored action may be offered to the model.
+
+ Args:
+ tool: The owning tool row; only MCP actions use MCP visibility.
+ action: The discovered/stored action metadata.
+ """
+ if tool.get("name") != "mcp_tool":
+ return True
+ return "model" in tool_ui_metadata(action.get("_meta")).get("visibility", ["model", "app"])
+
+
+def model_action_visible(tool: dict, action_name: str) -> bool:
+ """Check visibility again when resolving a legacy or stale model call.
+
+ Args:
+ tool: The current tool row, rather than a cached name mapping.
+ action_name: The resolved MCP tool name.
+ """
+ if tool.get("name") != "mcp_tool":
+ return True
+ return all(
+ model_visible(tool, a)
+ for a in tool.get("actions") or []
+ if isinstance(a, dict) and a.get("name") == action_name
+ )
diff --git a/docsgpt/agents/tool_executor.py b/docsgpt/agents/tool_executor.py
index 0794189f6..a615ee8b0 100644
--- a/docsgpt/agents/tool_executor.py
+++ b/docsgpt/agents/tool_executor.py
@@ -18,6 +18,7 @@ from docsgpt.agents.default_tools import (
synthesized_default_tools,
)
from docsgpt import tracing
+from docsgpt.agents.mcp_apps import model_action_visible, model_visible
from docsgpt.agents.tool_pins import (
PARAM_SECTIONS,
iter_parameters,
@@ -1023,7 +1024,7 @@ class ToolExecutor:
actions = tool["config"]["actions"].values() if is_api else tool["actions"]
for action in actions:
- if not action.get("active", True):
+ if not action.get("active", True) or not model_visible(tool, action):
continue
tool_name = tool.get("name", "")
if tool_name in dedupable:
@@ -1318,6 +1319,8 @@ class ToolExecutor:
tool_data = tools_dict[tool_id]
arguments = call_args if isinstance(call_args, dict) else {}
+ if not model_action_visible(tool_data, action_name):
+ return None # execute() records a denied call without prompting or loading credentials.
# Client-side tools
if tool_data.get("client_side"):
@@ -1681,7 +1684,7 @@ class ToolExecutor:
else:
actions = tool.get("actions") or []
for action in actions:
- if not isinstance(action, dict) or not action.get("active", True):
+ if not isinstance(action, dict) or not action.get("active", True) or not model_visible(tool, action):
continue
if action.get("name"):
names.add(str(action["name"]))
@@ -1707,7 +1710,8 @@ class ToolExecutor:
names = sorted(
name
for (tool_id, _action), name in self._tool_to_name.items()
- if not scope or tool_id in scope
+ if (not scope or tool_id in scope)
+ and model_action_visible((tools_dict or {}).get(tool_id, {}), _action)
)
if not names:
names = sorted(self._advertisable_action_names(tools_dict or {}))
@@ -1918,6 +1922,19 @@ class ToolExecutor:
"arguments": call_args,
}
tool_data = tools_dict[tool_id]
+ # Discovery filtering alone is insufficient: legacy names and a
+ # previously advertised mapping can still resolve an app-only action.
+ if not model_action_visible(tool_data, action_name):
+ error_message = "This MCP tool is not callable by the model."
+ tool_call_data.update(result=error_message, status="error")
+ if _record_proposed(
+ call_id, tool_data["name"], action_name, call_args if isinstance(call_args, dict) else {},
+ tool_id=tool_data.get("id"), message_id=self.message_id, user_id=self.user, agent_id=self.agent_id,
+ ):
+ _mark_failed(call_id, error_message, message_id=self.message_id, user_id=self.user)
+ yield {"type": "tool_call", "data": dict(tool_call_data)}
+ self.tool_calls.append(tool_call_data)
+ return error_message, call_id
# Name the service a connection-backed tool used, so the chip can show
# its logo ("Searched Notion"). Never the account behind it.
resolved = self._resolve_connection(tool_data)
diff --git a/docsgpt/agents/tools/mcp_tool.py b/docsgpt/agents/tools/mcp_tool.py
index 2dc551150..853ec5781 100644
--- a/docsgpt/agents/tools/mcp_tool.py
+++ b/docsgpt/agents/tools/mcp_tool.py
@@ -46,6 +46,7 @@ from pydantic import AnyHttpUrl, ValidationError
from redis import Redis
from docsgpt.agents.tools.base import Tool
+from docsgpt.agents.mcp_apps import tool_ui_metadata
from docsgpt.llm.tool_images import image_ref
from docsgpt.api.user.tasks import mcp_oauth_task
from docsgpt.cache import get_redis_instance
@@ -461,6 +462,9 @@ class MCPTool(Tool):
annotations = _annotation_hints(getattr(tool, "annotations", None))
if annotations:
tool_dict["annotations"] = annotations
+ ui = tool_ui_metadata(getattr(tool, "meta", None))
+ if ui:
+ tool_dict["_meta"] = {"ui": ui}
tools_dict.append(tool_dict)
elif isinstance(tool, dict):
tools_dict.append(tool)
@@ -898,6 +902,9 @@ class MCPTool(Tool):
annotations = _annotation_hints(tool.get("annotations"))
if annotations:
action["annotations"] = annotations
+ ui = tool_ui_metadata(tool.get("_meta"))
+ if ui:
+ action["_meta"] = {"ui": ui}
actions.append(action)
return actions
diff --git a/docsgpt/connectors/service.py b/docsgpt/connectors/service.py
index dc85ddf5c..1851454dc 100644
--- a/docsgpt/connectors/service.py
+++ b/docsgpt/connectors/service.py
@@ -12,6 +12,7 @@ import json
import sys
from typing import Any, Iterable, Optional
+from docsgpt.agents.mcp_apps import tool_ui_metadata
from docsgpt.connectors import catalog
from docsgpt.connectors.catalog import ConnectorDefinition
from docsgpt.storage.db.repositories.connector_sessions import (
@@ -280,6 +281,7 @@ def serialize_tool(
if not isinstance(action, dict):
continue
access = action_access(row.get("name"), action)
+ ui = tool_ui_metadata(action.get("_meta")) if row.get("name") == "mcp_tool" else {}
actions.append(
{
"name": action.get("name"),
@@ -289,6 +291,7 @@ def serialize_tool(
"parameters": serialize_parameters(action, account_parameters),
# ``{p, scorer}`` while Admin > Guardrails warns on tool descriptions.
"injection": action.get("injection") if isinstance(action.get("injection"), dict) else None,
+ **({"_meta": {"ui": ui}} if ui else {}),
}
)
return {
diff --git a/tests/agents/test_mcp_apps_visibility.py b/tests/agents/test_mcp_apps_visibility.py
new file mode 100644
index 000000000..4a30e588c
--- /dev/null
+++ b/tests/agents/test_mcp_apps_visibility.py
@@ -0,0 +1,186 @@
+"""MCP Apps discovery keeps app-only actions out of model execution."""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import pytest
+from mcp.types import Tool
+
+from docsgpt.agents.tool_executor import ToolExecutor
+import docsgpt.api.user.routes # noqa: F401 -- initialize the existing API/MCP import cycle first.
+from docsgpt.agents.tools.mcp_tool import MCPTool
+
+
+def mcp_tool():
+ with patch.object(MCPTool, "_setup_client"):
+ return MCPTool({"server_url": "", "auth_type": "none"})
+
+
+def action(name, visibility=None, **extra):
+ result = {"name": name, "description": name, "parameters": {"type": "object", "properties": {}}}
+ if visibility is not None:
+ result["_meta"] = {"ui": {"visibility": visibility}}
+ return {**result, **extra}
+
+
+def tools(*actions):
+ return {"1": {"name": "mcp_tool", "config": {}, "actions": list(actions)}}
+
+
+def drain(generator):
+ events = []
+ while True:
+ try:
+ events.append(next(generator))
+ except StopIteration as stopped:
+ return events, stopped.value
+
+
[email protected]
[email protected]("as_dict", [False, True])
+def test_discovery_preserves_only_ui_contract_in_action_metadata(as_dict):
+ meta = {"ui": {"resourceUri": "ui://canvas/view", "visibility": ["app"]}, "private": "not an action field"}
+ sdk_tool = Tool(name="save", description="Save", inputSchema={"type": "object"}, _meta=meta)
+ client = mcp_tool()
+ client.available_tools = client._format_tools([sdk_tool.model_dump(by_alias=True) if as_dict else sdk_tool])
+ assert client.available_tools[0]["_meta"]["ui"] == meta["ui"]
+ result = client.get_actions_metadata()[0]
+ assert result["_meta"] == {"ui": meta["ui"]}
+ assert sdk_tool.meta == meta
+
+
[email protected]
[email protected]("meta, expected", [
+ ({"ui/resourceUri": "ui://legacy/view"}, {"resourceUri": "ui://legacy/view"}),
+ ({"ui": {"resourceUri": "ui://current/view"}, "ui/resourceUri": "ui://legacy/view"},
+ {"resourceUri": "ui://current/view"}),
+ ({"ui": {"resourceUri": "https://example.com/view", "visibility": ["model"]}}, {"visibility": ["model"]}),
+ ({"ui": {"resourceUri": "ui://"}}, {}),
+ ({"ui": {"visibility": []}}, {"visibility": []}),
+ ({"ui": {"visibility": "model"}}, {"visibility": []}),
+ ({"ui": {"visibility": ["model", "other"]}}, {"visibility": []}),
+ ({"ui": None}, {"visibility": []}),
+])
+def test_ui_metadata_normalization(meta, expected):
+ client = mcp_tool()
+ client.available_tools = [{"name": "draw", "_meta": meta}]
+ result = client.get_actions_metadata()[0]
+ assert result.get("_meta", {}).get("ui", {}) == expected
+
+
[email protected]
[email protected]("visibility", [["app"], [], "model", ["model", "invalid"]])
+def test_hidden_actions_are_not_advertised_or_suggested(visibility):
+ executor = ToolExecutor()
+ registered = tools(action("hidden", visibility), action("visible", ["model"]), action("ordinary"))
+ prepared = executor.prepare_tools_for_llm(registered)
+ assert {x["function"]["name"] for x in prepared} == {"visible", "ordinary"}
+ assert executor._advertisable_action_names(registered) == {"visible", "ordinary"}
+ assert "hidden" not in executor._available_tool_names(registered)
+
+
[email protected]
[email protected]("llm", ["OpenAILLM", "GoogleLLM"])
[email protected]("stale_mapping", [False, True])
+def test_hidden_action_cannot_use_legacy_or_stale_name_mapping(monkeypatch, llm, stale_mapping):
+ executor = ToolExecutor()
+ registered = tools(action("save", ["app"], require_approval=True))
+ call_name = "save" if stale_mapping else "save_1"
+ if stale_mapping:
+ executor._name_to_tool[call_name] = ("1", "save")
+ call = SimpleNamespace(name=call_name, id="hidden-call", arguments="{}")
+ resolve = Mock(side_effect=AssertionError("must deny before accessing the connection"))
+ load = Mock(side_effect=AssertionError("must not load or invoke app-only tools"))
+ monkeypatch.setattr(executor, "_resolve_connection", resolve)
+ monkeypatch.setattr(executor, "_get_or_load_tool", load)
+ proposed = Mock(return_value=True)
+ failed = Mock()
+ monkeypatch.setattr("docsgpt.agents.tool_executor._record_proposed", proposed)
+ monkeypatch.setattr("docsgpt.agents.tool_executor._mark_failed", failed)
+ assert executor.check_pause(registered, call, llm) is None
+ events, returned = drain(executor.execute(registered, call, llm))
+ assert events[-1]["data"]["status"] == "error"
+ assert "model" in returned[0].lower()
+ proposed.assert_called_once()
+ failed.assert_called_once()
+ resolve.assert_not_called()
+ load.assert_not_called()
+
+
[email protected]
+def test_model_visible_write_still_requires_existing_approval():
+ executor = ToolExecutor()
+ registered = tools(action("save", ["model"], require_approval=True))
+ executor.prepare_tools_for_llm(registered)
+ call = SimpleNamespace(name="save", id="write-call", arguments="{}")
+ pending = executor.check_pause(registered, call, "OpenAILLM")
+ assert pending["pause_type"] == "awaiting_approval"
+
+
[email protected]
+def test_visibility_does_not_filter_unrelated_tools():
+ registered = tools(action("ordinary", ["app"]))
+ registered["1"]["name"] = "test_tool"
+ assert len(ToolExecutor().prepare_tools_for_llm(registered)) == 1
+
+
[email protected]
+def test_stale_names_are_not_suggested_after_visibility_changes():
+ executor = ToolExecutor()
+ registered = tools(action("save", ["model"]))
+ executor.prepare_tools_for_llm(registered)
+ registered["1"]["actions"][0]["_meta"]["ui"]["visibility"] = ["app"]
+ assert executor._available_tool_names(registered) == "(none available)"
+
+
[email protected]
+def test_ui_contract_survives_real_postgres_tool_reload(pg_conn):
+ from docsgpt.connectors.permissions import apply_default_permissions
+ from docsgpt.connectors.service import _transform_actions, serialize_tool
+ from docsgpt.storage.db.repositories.user_tools import UserToolsRepository
+
+ client = mcp_tool()
+ client.available_tools = client._format_tools([
+ Tool(name="draw", inputSchema={}, _meta={"ui": {"resourceUri": "ui://canvas/view"}}),
+ Tool(name="save", inputSchema={}, _meta={"ui": {"visibility": ["app"]}}),
+ ])
+ actions = apply_default_permissions("mcp_tool", _transform_actions(client.get_actions_metadata()))
+ repo = UserToolsRepository(pg_conn)
+ row = repo.create("visibility-user", "mcp_tool", config={}, actions=actions)
+ stored = repo.get(str(row["id"]), "visibility-user")
+ reloaded = serialize_tool(stored)
+ saved = {a["name"]: a for a in reloaded["actions"]}
+ assert saved["draw"]["_meta"]["ui"]["resourceUri"] == "ui://canvas/view"
+ assert saved["save"]["_meta"]["ui"]["visibility"] == ["app"]
+ assert saved["save"]["permission"] == "ask"
+ prepared = ToolExecutor().prepare_tools_for_llm({str(row["id"]): stored})
+ assert [x["function"]["name"] for x in prepared] == ["draw"]
+
+
[email protected]
+def test_real_fastmcp_discovery_to_model_schema():
+ from fastmcp import Client, FastMCP
+
+ server = FastMCP("visibility-regression")
+
+ @server.tool(meta={"ui": {"resourceUri": "ui://canvas/view", "visibility": ["model"]}})
+ def draw() -> str:
+ return "Canvas ready"
+
+ @server.tool(meta={"ui": {"visibility": ["app"]}})
+ def save() -> str:
+ raise AssertionError("discovery must never invoke save")
+
+ @server.tool()
+ def ordinary() -> str:
+ return "Text only"
+
+ client = mcp_tool()
+ client._client = Client(server)
+ discovered = asyncio.run(client._execute_with_client("list_tools"))
+ assert {x["name"] for x in discovered} == {"draw", "save", "ordinary"}
+ registered = tools(*client.get_actions_metadata())
+ prepared = ToolExecutor().prepare_tools_for_llm(registered)
+ assert {x["function"]["name"] for x in prepared} == {"draw", "ordinary"}
+ assert next(x for x in registered["1"]["actions"] if x["name"] == "draw")["_meta"]["ui"]["resourceUri"] == "ui://canvas/view"
Backend progress for the harness/result-contract stage, based on current main 32a0f2c4a79c3526c0bcecb95dbeba8900cb3a62. This rebases the previously posted discovery/visibility prerequisite and adds the next bounded slice.
- MCP results retain
structuredContentalongside text content and preserveisErrorfor failure status. - Calls with a UI resource reference carry the typed
CallToolResultand resource/tool identifier in the stream event and reload projection, subject to the existing 400k-character result ceiling. text/html;profile=mcp-appresource bodies are reduced to a URI/type descriptor; HTML is not copied into the model result or conversation tool-call row.
Focused validation on Linux/Python 3.13: 29 selected tests passed, Ruff passed on all changed Python files, and git diff --check passed. This is the backend contract slice; the authenticated resource endpoint, separate-origin sandbox, and frontend host/rendering remain later stages.
diff --git a/docsgpt/agents/mcp_apps.py b/docsgpt/agents/mcp_apps.py
new file mode 100644
index 000000000..bbf7c01de
--- /dev/null
+++ b/docsgpt/agents/mcp_apps.py
@@ -0,0 +1,61 @@
+"""The discovery-time MCP Apps contract; no rendering or app execution."""
+
+from typing import Any
+
+
+def tool_ui_metadata(meta: Any) -> dict:
+ """Keep only the UI resource reference and visibility from tool metadata.
+
+ Args:
+ meta: A tool's wire ``_meta`` mapping (SDK models call it ``meta``).
+
+ Returns:
+ A detached ``ui`` mapping. Missing visibility keeps the protocol's
+ model/app default; explicitly empty or malformed visibility allows
+ neither. Arbitrary server metadata and resource HTML are not copied.
+ """
+ if not isinstance(meta, dict):
+ return {}
+ raw = meta.get("ui", {})
+ if not isinstance(raw, dict):
+ return {"visibility": []}
+ ui = {}
+ uri = raw.get("resourceUri", meta.get("ui/resourceUri"))
+ if isinstance(uri, str) and uri.startswith("ui://") and len(uri) > 5 and not any(c.isspace() for c in uri):
+ ui["resourceUri"] = uri
+ if "visibility" in raw:
+ visibility = raw["visibility"]
+ ui["visibility"] = (
+ list(dict.fromkeys(visibility))
+ if isinstance(visibility, list) and all(v in ("model", "app") for v in visibility)
+ else []
+ )
+ return ui
+
+
+def model_visible(tool: dict, action: dict) -> bool:
+ """Whether a stored action may be offered to the model.
+
+ Args:
+ tool: The owning tool row; only MCP actions use MCP visibility.
+ action: The discovered/stored action metadata.
+ """
+ if tool.get("name") != "mcp_tool":
+ return True
+ return "model" in tool_ui_metadata(action.get("_meta")).get("visibility", ["model", "app"])
+
+
+def model_action_visible(tool: dict, action_name: str) -> bool:
+ """Check visibility again when resolving a legacy or stale model call.
+
+ Args:
+ tool: The current tool row, rather than a cached name mapping.
+ action_name: The resolved MCP tool name.
+ """
+ if tool.get("name") != "mcp_tool":
+ return True
+ return all(
+ model_visible(tool, a)
+ for a in tool.get("actions") or []
+ if isinstance(a, dict) and a.get("name") == action_name
+ )
diff --git a/docsgpt/agents/tool_executor.py b/docsgpt/agents/tool_executor.py
index b06a48141..b8ee951c4 100644
--- a/docsgpt/agents/tool_executor.py
+++ b/docsgpt/agents/tool_executor.py
@@ -18,6 +18,7 @@ from docsgpt.agents.default_tools import (
synthesized_default_tools,
)
from docsgpt import tracing
+from docsgpt.agents.mcp_apps import model_action_visible, model_visible
from docsgpt.agents.tool_pins import (
PARAM_SECTIONS,
iter_parameters,
@@ -338,6 +339,8 @@ def result_status(result: Any) -> str:
"""
if not isinstance(result, dict):
return "completed"
+ if result.get("isError") is True or result.get("is_error") is True:
+ return "error"
if result.get("status") == "error" or result.get("error"):
return "error"
code = result.get("status_code")
@@ -1067,7 +1070,7 @@ class ToolExecutor:
actions = tool["config"]["actions"].values() if is_api else tool["actions"]
for action in actions:
- if not action.get("active", True):
+ if not action.get("active", True) or not model_visible(tool, action):
continue
tool_name = tool.get("name", "")
if tool_name in dedupable:
@@ -1368,6 +1371,8 @@ class ToolExecutor:
tool_data = tools_dict[tool_id]
arguments = call_args if isinstance(call_args, dict) else {}
+ if not model_action_visible(tool_data, action_name):
+ return None # execute() records a denied call without prompting or loading credentials.
# Client-side tools
if tool_data.get("client_side"):
@@ -1731,7 +1736,7 @@ class ToolExecutor:
else:
actions = tool.get("actions") or []
for action in actions:
- if not isinstance(action, dict) or not action.get("active", True):
+ if not isinstance(action, dict) or not action.get("active", True) or not model_visible(tool, action):
continue
if action.get("name"):
names.add(str(action["name"]))
@@ -1757,7 +1762,8 @@ class ToolExecutor:
names = sorted(
name
for (tool_id, _action), name in self._tool_to_name.items()
- if not scope or tool_id in scope
+ if (not scope or tool_id in scope)
+ and model_action_visible((tools_dict or {}).get(tool_id, {}), _action)
)
if not names:
names = sorted(self._advertisable_action_names(tools_dict or {}))
@@ -1968,6 +1974,19 @@ class ToolExecutor:
"arguments": call_args,
}
tool_data = tools_dict[tool_id]
+ # Discovery filtering alone is insufficient: legacy names and a
+ # previously advertised mapping can still resolve an app-only action.
+ if not model_action_visible(tool_data, action_name):
+ error_message = "This MCP tool is not callable by the model."
+ tool_call_data.update(result=error_message, status="error")
+ if _record_proposed(
+ call_id, tool_data["name"], action_name, call_args if isinstance(call_args, dict) else {},
+ tool_id=tool_data.get("id"), message_id=self.message_id, user_id=self.user, agent_id=self.agent_id,
+ ):
+ _mark_failed(call_id, error_message, message_id=self.message_id, user_id=self.user)
+ yield {"type": "tool_call", "data": dict(tool_call_data)}
+ self.tool_calls.append(tool_call_data)
+ return error_message, call_id
# Name the service a connection-backed tool used, so the chip can show
# its logo ("Searched Notion"). Never the account behind it.
resolved = self._resolve_connection(tool_data)
@@ -2203,6 +2222,32 @@ class ToolExecutor:
status = result_status(result)
result = self._guardrail_tool_result(result, tool_data.get("name", ""), action_name)
+ # Keep the typed CallToolResult available to the MCP Apps event/reload
+ # path, but never copy the HTML resource itself into a model/message row.
+ # The resource is fetched separately by its URI in a later host stage.
+ if tool_data.get("name") == "mcp_tool" and isinstance(result, dict):
+ from docsgpt.agents.mcp_apps import tool_ui_metadata
+
+ ui_meta = tool_ui_metadata(action_data.get("_meta"))
+ if ui_meta.get("resourceUri"):
+ typed_result = {
+ key: result[key]
+ for key in ("content", "structuredContent", "isError")
+ if key in result
+ }
+ encoded_result = json.dumps(typed_result, ensure_ascii=False, separators=(",", ":"))
+ if len(encoded_result) <= RESULT_FULL_MAX_CHARS:
+ tool_call_data["mcp_result"] = typed_result
+ tool_call_data["ui"] = {
+ "resourceUri": ui_meta["resourceUri"],
+ "toolId": str(tool_data.get("id") or tool_id),
+ }
+ else:
+ logger.warning(
+ "MCP App result exceeds the %s-character conversation limit; omitting UI payload",
+ RESULT_FULL_MAX_CHARS,
+ )
+
get_artifact_id = getattr(tool, "get_artifact_id", None) if tool_data["name"] != "api_tool" else None
artifact_id = None
@@ -2542,7 +2587,7 @@ class ToolExecutor:
# after a reload as it did live.
_PRESERVED_TOOL_CALL_KEYS = (
"artifacts", "device_id", "connector_key", "connector_name", "access", "sent_arguments", "images",
- "job_id", "error", "error_type",
+ "job_id", "error", "error_type", "mcp_result", "ui",
)
def _collect_native_parts(self, tool: Any, result: Any, tool_call_data: Dict) -> Any:
diff --git a/docsgpt/agents/tools/mcp_tool.py b/docsgpt/agents/tools/mcp_tool.py
index 2dc551150..cfb95afbc 100644
--- a/docsgpt/agents/tools/mcp_tool.py
+++ b/docsgpt/agents/tools/mcp_tool.py
@@ -46,6 +46,7 @@ from pydantic import AnyHttpUrl, ValidationError
from redis import Redis
from docsgpt.agents.tools.base import Tool
+from docsgpt.agents.mcp_apps import tool_ui_metadata
from docsgpt.llm.tool_images import image_ref
from docsgpt.api.user.tasks import mcp_oauth_task
from docsgpt.cache import get_redis_instance
@@ -461,6 +462,9 @@ class MCPTool(Tool):
annotations = _annotation_hints(getattr(tool, "annotations", None))
if annotations:
tool_dict["annotations"] = annotations
+ ui = tool_ui_metadata(getattr(tool, "meta", None))
+ if ui:
+ tool_dict["_meta"] = {"ui": ui}
tools_dict.append(tool_dict)
elif isinstance(tool, dict):
tools_dict.append(tool)
@@ -689,7 +693,17 @@ class MCPTool(Tool):
elif resource is not None:
entry = {"type": "resource", "uri": str(getattr(resource, "uri", "")), "mimeType": mime_type}
text = getattr(resource, "text", None)
- entry.update({"text": text} if text is not None else {"note": "binary content, not shown"})
+ is_mcp_app_html = (
+ mime_type.split(";", 1)[0].strip().lower() == "text/html"
+ and any(
+ part.strip().lower() == "profile=mcp-app"
+ for part in mime_type.split(";")[1:]
+ )
+ )
+ if is_mcp_app_html:
+ entry["note"] = "MCP App HTML is not included in the tool result"
+ else:
+ entry.update({"text": text} if text is not None else {"note": "binary content, not shown"})
content_list.append(entry)
elif kind == "resource_link":
content_list.append(
@@ -699,16 +713,22 @@ class MCPTool(Tool):
content_list.append({"type": "audio", "mimeType": mime_type, "note": "audio, not shown"})
else:
content_list.append({"type": "unknown", "content": str(item)})
- if not content_list:
- # Some servers (Airtable) answer only in structured content and leave ``content`` empty.
- structured = getattr(result, "structured_content", None) or getattr(result, "structuredContent", None)
- if structured:
+ structured = getattr(result, "structured_content", None)
+ if structured is None:
+ structured = getattr(result, "structuredContent", None)
+ if structured is not None:
+ # Keep the typed MCP result alongside the text projection used by
+ # existing model adapters. Some servers (Airtable) leave content empty.
+ if not content_list and structured:
content_list.append({"type": "text", "text": json.dumps(structured, default=str)})
# FastMCP's client result names it ``is_error``; the MCP type ``isError``.
is_error = getattr(result, "is_error", None)
if not isinstance(is_error, bool):
is_error = bool(getattr(result, "isError", False))
- return {"content": content_list, "isError": is_error}
+ formatted = {"content": content_list, "isError": is_error}
+ if structured is not None:
+ formatted["structuredContent"] = structured
+ return formatted
def _queue_image(self, data: str, action_name: str) -> Dict:
"""Queue a base64 image the server returned; the entry that stands for it in the result."""
@@ -898,6 +918,9 @@ class MCPTool(Tool):
annotations = _annotation_hints(tool.get("annotations"))
if annotations:
action["annotations"] = annotations
+ ui = tool_ui_metadata(tool.get("_meta"))
+ if ui:
+ action["_meta"] = {"ui": ui}
actions.append(action)
return actions
diff --git a/docsgpt/connectors/service.py b/docsgpt/connectors/service.py
index 0dd321342..3906f43be 100644
--- a/docsgpt/connectors/service.py
+++ b/docsgpt/connectors/service.py
@@ -12,6 +12,7 @@ import json
import sys
from typing import Any, Iterable, Optional
+from docsgpt.agents.mcp_apps import tool_ui_metadata
from docsgpt.connectors import catalog
from docsgpt.connectors.catalog import ConnectorDefinition
from docsgpt.storage.db.repositories.connector_sessions import (
@@ -280,6 +281,7 @@ def serialize_tool(
if not isinstance(action, dict):
continue
access = action_access(row.get("name"), action)
+ ui = tool_ui_metadata(action.get("_meta")) if row.get("name") == "mcp_tool" else {}
actions.append(
{
"name": action.get("name"),
@@ -289,6 +291,7 @@ def serialize_tool(
"parameters": serialize_parameters(action, account_parameters),
# ``{p, scorer}`` while Admin > Guardrails warns on tool descriptions.
"injection": action.get("injection") if isinstance(action.get("injection"), dict) else None,
+ **({"_meta": {"ui": ui}} if ui else {}),
}
)
return {
diff --git a/tests/agents/test_mcp_apps_visibility.py b/tests/agents/test_mcp_apps_visibility.py
new file mode 100644
index 000000000..4a30e588c
--- /dev/null
+++ b/tests/agents/test_mcp_apps_visibility.py
@@ -0,0 +1,186 @@
+"""MCP Apps discovery keeps app-only actions out of model execution."""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import pytest
+from mcp.types import Tool
+
+from docsgpt.agents.tool_executor import ToolExecutor
+import docsgpt.api.user.routes # noqa: F401 -- initialize the existing API/MCP import cycle first.
+from docsgpt.agents.tools.mcp_tool import MCPTool
+
+
+def mcp_tool():
+ with patch.object(MCPTool, "_setup_client"):
+ return MCPTool({"server_url": "", "auth_type": "none"})
+
+
+def action(name, visibility=None, **extra):
+ result = {"name": name, "description": name, "parameters": {"type": "object", "properties": {}}}
+ if visibility is not None:
+ result["_meta"] = {"ui": {"visibility": visibility}}
+ return {**result, **extra}
+
+
+def tools(*actions):
+ return {"1": {"name": "mcp_tool", "config": {}, "actions": list(actions)}}
+
+
+def drain(generator):
+ events = []
+ while True:
+ try:
+ events.append(next(generator))
+ except StopIteration as stopped:
+ return events, stopped.value
+
+
[email protected]
[email protected]("as_dict", [False, True])
+def test_discovery_preserves_only_ui_contract_in_action_metadata(as_dict):
+ meta = {"ui": {"resourceUri": "ui://canvas/view", "visibility": ["app"]}, "private": "not an action field"}
+ sdk_tool = Tool(name="save", description="Save", inputSchema={"type": "object"}, _meta=meta)
+ client = mcp_tool()
+ client.available_tools = client._format_tools([sdk_tool.model_dump(by_alias=True) if as_dict else sdk_tool])
+ assert client.available_tools[0]["_meta"]["ui"] == meta["ui"]
+ result = client.get_actions_metadata()[0]
+ assert result["_meta"] == {"ui": meta["ui"]}
+ assert sdk_tool.meta == meta
+
+
[email protected]
[email protected]("meta, expected", [
+ ({"ui/resourceUri": "ui://legacy/view"}, {"resourceUri": "ui://legacy/view"}),
+ ({"ui": {"resourceUri": "ui://current/view"}, "ui/resourceUri": "ui://legacy/view"},
+ {"resourceUri": "ui://current/view"}),
+ ({"ui": {"resourceUri": "https://example.com/view", "visibility": ["model"]}}, {"visibility": ["model"]}),
+ ({"ui": {"resourceUri": "ui://"}}, {}),
+ ({"ui": {"visibility": []}}, {"visibility": []}),
+ ({"ui": {"visibility": "model"}}, {"visibility": []}),
+ ({"ui": {"visibility": ["model", "other"]}}, {"visibility": []}),
+ ({"ui": None}, {"visibility": []}),
+])
+def test_ui_metadata_normalization(meta, expected):
+ client = mcp_tool()
+ client.available_tools = [{"name": "draw", "_meta": meta}]
+ result = client.get_actions_metadata()[0]
+ assert result.get("_meta", {}).get("ui", {}) == expected
+
+
[email protected]
[email protected]("visibility", [["app"], [], "model", ["model", "invalid"]])
+def test_hidden_actions_are_not_advertised_or_suggested(visibility):
+ executor = ToolExecutor()
+ registered = tools(action("hidden", visibility), action("visible", ["model"]), action("ordinary"))
+ prepared = executor.prepare_tools_for_llm(registered)
+ assert {x["function"]["name"] for x in prepared} == {"visible", "ordinary"}
+ assert executor._advertisable_action_names(registered) == {"visible", "ordinary"}
+ assert "hidden" not in executor._available_tool_names(registered)
+
+
[email protected]
[email protected]("llm", ["OpenAILLM", "GoogleLLM"])
[email protected]("stale_mapping", [False, True])
+def test_hidden_action_cannot_use_legacy_or_stale_name_mapping(monkeypatch, llm, stale_mapping):
+ executor = ToolExecutor()
+ registered = tools(action("save", ["app"], require_approval=True))
+ call_name = "save" if stale_mapping else "save_1"
+ if stale_mapping:
+ executor._name_to_tool[call_name] = ("1", "save")
+ call = SimpleNamespace(name=call_name, id="hidden-call", arguments="{}")
+ resolve = Mock(side_effect=AssertionError("must deny before accessing the connection"))
+ load = Mock(side_effect=AssertionError("must not load or invoke app-only tools"))
+ monkeypatch.setattr(executor, "_resolve_connection", resolve)
+ monkeypatch.setattr(executor, "_get_or_load_tool", load)
+ proposed = Mock(return_value=True)
+ failed = Mock()
+ monkeypatch.setattr("docsgpt.agents.tool_executor._record_proposed", proposed)
+ monkeypatch.setattr("docsgpt.agents.tool_executor._mark_failed", failed)
+ assert executor.check_pause(registered, call, llm) is None
+ events, returned = drain(executor.execute(registered, call, llm))
+ assert events[-1]["data"]["status"] == "error"
+ assert "model" in returned[0].lower()
+ proposed.assert_called_once()
+ failed.assert_called_once()
+ resolve.assert_not_called()
+ load.assert_not_called()
+
+
[email protected]
+def test_model_visible_write_still_requires_existing_approval():
+ executor = ToolExecutor()
+ registered = tools(action("save", ["model"], require_approval=True))
+ executor.prepare_tools_for_llm(registered)
+ call = SimpleNamespace(name="save", id="write-call", arguments="{}")
+ pending = executor.check_pause(registered, call, "OpenAILLM")
+ assert pending["pause_type"] == "awaiting_approval"
+
+
[email protected]
+def test_visibility_does_not_filter_unrelated_tools():
+ registered = tools(action("ordinary", ["app"]))
+ registered["1"]["name"] = "test_tool"
+ assert len(ToolExecutor().prepare_tools_for_llm(registered)) == 1
+
+
[email protected]
+def test_stale_names_are_not_suggested_after_visibility_changes():
+ executor = ToolExecutor()
+ registered = tools(action("save", ["model"]))
+ executor.prepare_tools_for_llm(registered)
+ registered["1"]["actions"][0]["_meta"]["ui"]["visibility"] = ["app"]
+ assert executor._available_tool_names(registered) == "(none available)"
+
+
[email protected]
+def test_ui_contract_survives_real_postgres_tool_reload(pg_conn):
+ from docsgpt.connectors.permissions import apply_default_permissions
+ from docsgpt.connectors.service import _transform_actions, serialize_tool
+ from docsgpt.storage.db.repositories.user_tools import UserToolsRepository
+
+ client = mcp_tool()
+ client.available_tools = client._format_tools([
+ Tool(name="draw", inputSchema={}, _meta={"ui": {"resourceUri": "ui://canvas/view"}}),
+ Tool(name="save", inputSchema={}, _meta={"ui": {"visibility": ["app"]}}),
+ ])
+ actions = apply_default_permissions("mcp_tool", _transform_actions(client.get_actions_metadata()))
+ repo = UserToolsRepository(pg_conn)
+ row = repo.create("visibility-user", "mcp_tool", config={}, actions=actions)
+ stored = repo.get(str(row["id"]), "visibility-user")
+ reloaded = serialize_tool(stored)
+ saved = {a["name"]: a for a in reloaded["actions"]}
+ assert saved["draw"]["_meta"]["ui"]["resourceUri"] == "ui://canvas/view"
+ assert saved["save"]["_meta"]["ui"]["visibility"] == ["app"]
+ assert saved["save"]["permission"] == "ask"
+ prepared = ToolExecutor().prepare_tools_for_llm({str(row["id"]): stored})
+ assert [x["function"]["name"] for x in prepared] == ["draw"]
+
+
[email protected]
+def test_real_fastmcp_discovery_to_model_schema():
+ from fastmcp import Client, FastMCP
+
+ server = FastMCP("visibility-regression")
+
+ @server.tool(meta={"ui": {"resourceUri": "ui://canvas/view", "visibility": ["model"]}})
+ def draw() -> str:
+ return "Canvas ready"
+
+ @server.tool(meta={"ui": {"visibility": ["app"]}})
+ def save() -> str:
+ raise AssertionError("discovery must never invoke save")
+
+ @server.tool()
+ def ordinary() -> str:
+ return "Text only"
+
+ client = mcp_tool()
+ client._client = Client(server)
+ discovered = asyncio.run(client._execute_with_client("list_tools"))
+ assert {x["name"] for x in discovered} == {"draw", "save", "ordinary"}
+ registered = tools(*client.get_actions_metadata())
+ prepared = ToolExecutor().prepare_tools_for_llm(registered)
+ assert {x["function"]["name"] for x in prepared} == {"draw", "ordinary"}
+ assert next(x for x in registered["1"]["actions"] if x["name"] == "draw")["_meta"]["ui"]["resourceUri"] == "ui://canvas/view"
diff --git a/tests/agents/test_tool_call_projection.py b/tests/agents/test_tool_call_projection.py
index 32405674b..782acf6de 100644
--- a/tests/agents/test_tool_call_projection.py
+++ b/tests/agents/test_tool_call_projection.py
@@ -53,6 +53,19 @@ class TestTruncatedToolCallsKeepsWhatTheUiNeeds:
projected = self._executor(device_id="windows-8e15").get_truncated_tool_calls()
assert projected[0]["device_id"] == "windows-8e15"
+ def test_keeps_typed_mcp_result_and_resource_reference(self):
+ typed_result = {
+ "content": [{"type": "text", "text": "Canvas created"}],
+ "structuredContent": {"canvasId": "canvas-1"},
+ "isError": False,
+ }
+ ui = {"resourceUri": "ui://canvas/view", "toolId": "connection-1"}
+
+ projected = self._executor(mcp_result=typed_result, ui=ui).get_truncated_tool_calls()
+
+ assert projected[0]["mcp_result"] == typed_result
+ assert projected[0]["ui"] == ui
+
def test_omits_the_keys_entirely_when_absent(self):
"""A plain tool call must not grow null keys in every persisted row."""
projected = self._executor().get_truncated_tool_calls()
diff --git a/tests/agents/test_tool_executor.py b/tests/agents/test_tool_executor.py
index 76cb3d21a..e75198823 100644
--- a/tests/agents/test_tool_executor.py
+++ b/tests/agents/test_tool_executor.py
@@ -1068,6 +1068,48 @@ class TestToolExecutorExecute:
assert "pending" in statuses
assert "completed" in statuses
+ def test_mcp_app_result_is_available_in_event_and_reload_projection(self, mock_tool_manager, monkeypatch):
+ typed_result = {
+ "content": [{"type": "text", "text": "Canvas created"}],
+ "structuredContent": {"canvasId": "canvas-1"},
+ "isError": False,
+ }
+ mock_tool_manager.load_tool.return_value.execute_action.return_value = typed_result
+ monkeypatch.setattr(
+ "docsgpt.agents.tool_executor.ToolActionParser",
+ lambda _cls, **kw: Mock(parse_args=Mock(return_value=("t1", "draw", {}))),
+ )
+ monkeypatch.setattr("docsgpt.agents.tool_executor._record_proposed", lambda *args, **kwargs: False)
+ monkeypatch.setattr("docsgpt.agents.tool_executor._mark_executed", Mock())
+
+ tools_dict = {
+ "t1": {
+ "id": "connection-1",
+ "name": "mcp_tool",
+ "config": {"server_url": "https://mcp.example.test"},
+ "actions": [{
+ "name": "draw",
+ "description": "Draw a canvas",
+ "parameters": {"type": "object", "properties": {}},
+ "_meta": {"ui": {"resourceUri": "ui://canvas/view"}},
+ }],
+ }
+ }
+ executor = ToolExecutor(user="test_user")
+ events = []
+ gen = executor.execute(tools_dict, self._make_call(name="draw_t1", call_id="mcp1"), "MockLLM")
+ while True:
+ try:
+ events.append(next(gen))
+ except StopIteration:
+ break
+
+ completed = next(event["data"] for event in events if event.get("type") == "tool_call" and event["data"].get("status") == "completed")
+ assert completed["mcp_result"] == typed_result
+ assert completed["ui"] == {"resourceUri": "ui://canvas/view", "toolId": "connection-1"}
+ assert executor.get_truncated_tool_calls()[0]["mcp_result"] == typed_result
+ assert executor.get_truncated_tool_calls()[0]["ui"] == completed["ui"]
+
def test_a_redacted_failure_still_persists_as_an_error(self, mock_tool, mock_tool_manager, monkeypatch):
from docsgpt.guardrails.config import GuardrailsConfig
from docsgpt.guardrails.engine import GuardrailEngine
@@ -1153,6 +1195,9 @@ class TestToolExecutorExecute:
assert result_status({"error": "input artifact A9 not found"}) == "error"
assert result_status({"status": "ok", "artifact_id": "x"}) == "completed"
assert result_status({"error": None, "status": "ok"}) == "completed"
+ assert result_status({"isError": True, "content": []}) == "error"
+ assert result_status({"is_error": True, "content": []}) == "error"
+ assert result_status({"isError": False, "content": []}) == "completed"
assert result_status("plain text result") == "completed"
def test_result_status_reads_http_status_codes(self):
diff --git a/tests/agents/tools/test_mcp_tool.py b/tests/agents/tools/test_mcp_tool.py
index b498883aa..5f1b2dbbf 100644
--- a/tests/agents/tools/test_mcp_tool.py
+++ b/tests/agents/tools/test_mcp_tool.py
@@ -529,7 +529,57 @@ class TestFormatResult:
text = SimpleNamespace(type="text", text="one base")
result = SimpleNamespace(content=[text], structured_content={"bases": []}, is_error=False)
- assert tool._format_result(result)["content"] == [{"type": "text", "text": "one base"}]
+ formatted = tool._format_result(result)
+ assert formatted["content"] == [{"type": "text", "text": "one base"}]
+ assert formatted["structuredContent"] == {"bases": []}
+
+ @pytest.mark.parametrize("field", ["structured_content", "structuredContent"])
+ def test_structured_result_is_preserved_with_text_and_error_status(self, mcp_config, field):
+ from types import SimpleNamespace
+
+ tool = _make_tool(mcp_config)
+ text = SimpleNamespace(type="text", text="Canvas created")
+ result = SimpleNamespace(content=[text], is_error=True)
+ setattr(result, field, {"url": "https://example.test/canvas", "elements": [{"id": "e1"}]})
+
+ formatted = tool._format_result(result)
+
+ assert formatted == {
+ "content": [{"type": "text", "text": "Canvas created"}],
+ "structuredContent": {"url": "https://example.test/canvas", "elements": [{"id": "e1"}]},
+ "isError": True,
+ }
+
+ def test_mcp_app_html_resource_is_not_flattened_into_model_result(self, mcp_config):
+ from types import SimpleNamespace
+
+ from mcp.types import EmbeddedResource, TextResourceContents
+
+ html = "<script>private widget bootstrap</script>" * 100
+ tool = _make_tool(mcp_config)
+ result = SimpleNamespace(
+ content=[EmbeddedResource(
+ type="resource",
+ resource=TextResourceContents(
+ uri="ui://canvas/view",
+ mimeType="text/html;profile=mcp-app",
+ text=html,
+ ),
+ )],
+ structured_content={"status": "ready"},
+ is_error=False,
+ )
+
+ formatted = tool._format_result(result)
+
+ assert formatted["content"] == [{
+ "type": "resource",
+ "uri": "ui://canvas/view",
+ "mimeType": "text/html;profile=mcp-app",
+ "note": "MCP App HTML is not included in the tool result",
+ }]
+ assert formatted["structuredContent"] == {"status": "ready"}
+ assert html not in str(formatted)
def test_an_image_is_shown_to_the_model_not_inlined(self, mcp_config):
import base64
Follow-up to the typed-result patch above: I found and fixed an omission in its HTML classifier. A resource with text/html;profile="mcp-app" retained its HTML because the previous check compared the literal parameter spelling. The same issue affects whitespace around =. MIME parameters may be quoted.
The incremental patch below uses Python's standard MIME parser. Three new parameter-spelling cases fail against the previous patch; the canonical spelling and three non-App text-resource controls pass. All eight new tests pass with the correction.
I also validated a real in-process FastMCP call_tool through MCPTool, the executor's completed stream event, its reload projection, and a real PostgreSQL JSONB conversation write/read. The structured result and UI reference survive; the widget HTML is absent. Connection loading and the separate execution journal are replaced in that test; it does not test remote authentication or resource fetching.
Validation on current main bfa593d4fc85104544f6bd69b650a2d4b2c122a1 with the earlier typed-result patch plus this supplement: 761 passed, 21 skipped across the affected agent test files and connectors; full ruff check . and git diff --check passed. Linux/Python 3.13.11, PostgreSQL 16.15. Full backend, browser, resource endpoint and sandbox/renderer remain outside this result.
Incremental patch: apply after the linked typed-result patch
diff --git a/docsgpt/agents/tools/mcp_tool.py b/docsgpt/agents/tools/mcp_tool.py
index cfb95afbc29ddc88c54772e1fc02c96b83bac93b..0f79234189b542acbe4e67cb22cbac146af394fd 100644
--- a/docsgpt/agents/tools/mcp_tool.py
+++ b/docsgpt/agents/tools/mcp_tool.py
@@ -5,6 +5,7 @@ import hashlib
import json
import logging
import time
+from email.message import Message
from typing import Any, Callable, Dict, List, Optional
from urllib.parse import parse_qs, urlparse
@@ -693,12 +694,11 @@ class MCPTool(Tool):
elif resource is not None:
entry = {"type": "resource", "uri": str(getattr(resource, "uri", "")), "mimeType": mime_type}
text = getattr(resource, "text", None)
+ content_type = Message()
+ content_type["Content-Type"] = mime_type
is_mcp_app_html = (
- mime_type.split(";", 1)[0].strip().lower() == "text/html"
- and any(
- part.strip().lower() == "profile=mcp-app"
- for part in mime_type.split(";")[1:]
- )
+ content_type.get_content_type() == "text/html"
+ and content_type.get_param("profile") == "mcp-app"
)
if is_mcp_app_html:
entry["note"] = "MCP App HTML is not included in the tool result"
diff --git a/tests/agents/test_mcp_apps_result_contract.py b/tests/agents/test_mcp_apps_result_contract.py
new file mode 100644
index 0000000000000000000000000000000000000000..42309199e5202085a4a652b63ad8ebc456e6c2e5
--- /dev/null
+++ b/tests/agents/test_mcp_apps_result_contract.py
@@ -0,0 +1,100 @@
+"""MCP App bodies stay outside the model and persisted tool-call results."""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+from fastmcp import Client, FastMCP
+from mcp.types import CallToolResult, EmbeddedResource, TextResourceContents
+
+from docsgpt.agents.tool_executor import ToolExecutor
+import docsgpt.api.user.routes # noqa: F401 -- initialize the API/MCP import cycle.
+from docsgpt.agents.tools.mcp_tool import MCPTool
+
+
+def make_tool():
+ """Use an in-process client without configuring network credentials."""
+ with patch.object(MCPTool, "_setup_client"):
+ return MCPTool({"server_url": "", "auth_type": "none"})
+
+
+def app_result(mime_type):
+ """Build a wire result with HTML and a separate structured result."""
+ return CallToolResult(
+ content=[EmbeddedResource(
+ type="resource",
+ resource=TextResourceContents(
+ uri="ui://canvas/view", mimeType=mime_type, text="<script>widget-only</script>",
+ ),
+ )],
+ structuredContent={"canvasId": "canvas-1", "elements": []},
+ isError=False,
+ )
+
+
[email protected]
[email protected]("mime_type", [
+ "text/html;profile=mcp-app",
+ 'text/html;profile="mcp-app"',
+ 'TEXT/HTML; PROFILE = "mcp-app"; charset=utf-8',
+ 'text/html; charset="utf-8"; profile="mcp-app"',
+])
+def test_mcp_app_mime_parameters_do_not_expose_html(mime_type):
+ result = make_tool()._format_result(app_result(mime_type))
+ assert "widget-only" not in str(result)
+ assert result["content"][0]["uri"] == "ui://canvas/view"
+ assert result["structuredContent"] == {"canvasId": "canvas-1", "elements": []}
+
+
[email protected]
[email protected]("mime_type", ["text/plain", "text/html;profile=other", "text/html"])
+def test_non_app_text_resources_keep_their_content(mime_type):
+ result = make_tool()._format_result(app_result(mime_type))
+ assert result["content"][0]["text"] == "<script>widget-only</script>"
+
+
[email protected]
+def test_real_fastmcp_result_survives_conversation_jsonb_reload(pg_conn, monkeypatch):
+ from docsgpt.storage.db.repositories.conversations import ConversationsRepository
+
+ server = FastMCP("result-contract")
+
+ @server.tool(meta={"ui": {"resourceUri": "ui://canvas/view"}})
+ def draw() -> CallToolResult:
+ return app_result('text/html;profile="mcp-app"')
+
+ client = make_tool()
+ client._client = Client(server)
+ asyncio.run(client._execute_with_client("list_tools"))
+ wire_result = asyncio.run(client._execute_with_client("call_tool", "draw"))
+ formatted = client._format_result(wire_result)
+ assert "widget-only" not in str(formatted)
+ assert formatted["structuredContent"]["canvasId"] == "canvas-1"
+ assert formatted["isError"] is False
+ ui = client.get_actions_metadata()[0]["_meta"]["ui"]
+ executor = ToolExecutor()
+ registered = {"1": {
+ "id": "connection-1", "name": "mcp_tool", "config": {},
+ "actions": client.get_actions_metadata(),
+ }}
+ advertised = executor.prepare_tools_for_llm(registered)
+ # Replace only connection loading and the separate execution journal;
+ # actual MCP execution, formatting, stream and conversation storage run.
+ client.server_url = "in-process"
+ monkeypatch.setattr(executor, "_get_or_load_tool", lambda *args, **kwargs: client)
+ monkeypatch.setattr("docsgpt.agents.tool_executor._record_proposed", lambda *args, **kwargs: False)
+ call = SimpleNamespace(name=advertised[0]["function"]["name"], arguments="{}", id="draw-call")
+ events = list(executor.execute(registered, call, "OpenAILLM"))
+ completed = next(event["data"] for event in events
+ if event.get("type") == "tool_call" and event["data"].get("status") == "completed")
+ assert completed["mcp_result"] == formatted
+ assert completed["ui"] == {**ui, "toolId": "connection-1"}
+ projected = executor.get_truncated_tool_calls()
+ repo = ConversationsRepository(pg_conn)
+ conversation = repo.create("result-contract-user", name="MCP result round trip")
+ repo.append_message(str(conversation["id"]), {"prompt": "Draw", "response": "Done", "tool_calls": projected})
+ reloaded = repo.get_messages(str(conversation["id"]))[0]["tool_calls"][0]
+ assert reloaded["mcp_result"] == formatted
+ assert reloaded["ui"] == {"resourceUri": "ui://canvas/view", "toolId": "connection-1"}
+ assert "widget-only" not in str(reloaded)
@Protocol-zero-0, please move the backend patches into reviewable PRs rather than posting more code in issue comments. Another PR may be waiting on this work; we need a clear dependency and something we can review.
- Open a small PR for the first backend prerequisite, with regression tests and validation results. If it is not ready, open a draft PR and list what remains.
- Link any PR blocked by this work and explain which prerequisite it needs.
- Post the next milestone for the resource endpoints, sandbox and UI, and say whether anything is blocking you.
Follow CONTRIBUTING.md; include a screenshot or short recording when the UI is available. Keep each prerequisite independently reviewable rather than waiting for the whole feature.
Automated triage. A maintainer will follow up.
The first backend prerequisite is isolated as a two-file error-status fix against main 104cf6a52: recognize MCP isError: true in the streamed and persisted tool-call status while preserving the invocation journal's executed semantics.
The nine regressions give 3 failures / 6 passes on unmodified main and 9 passes with the fix. The full executor and MCP implementation test files pass together (250 passed, 21 skipped); full Ruff and diff checks pass. The regression path includes real PostgreSQL JSONB storage/reload, with the tool/network response and action parser stubbed. The PR branch and description are prepared; publication is pending, so there is no upstream PR link yet.
Dependency order for #2913: error status; discovery/visibility; typed tool results and UI-reference persistence; authenticated resource endpoints; separate-origin sandbox and renderer. The next resource-endpoint milestone is an authorized resource read with ownership checks and tests, followed by sandbox/renderer integration and a UI recording when available. Those endpoint/UI stages are not implemented yet.
I checked the existing open PRs. #2947 explicitly leaves inline create_view rendering to #2913; I have not confirmed that its preset work is blocked on this prerequisite. I will keep each backend prerequisite independently reviewable and link its PR rather than adding more code patches here.