From 74e7eb6e652d0c93113362fda32a30ddc40a7979 Mon Sep 17 00:00:00 2001 From: chrishayuk Date: Sun, 1 Mar 2026 02:12:32 +0000 Subject: [PATCH 1/4] improving mcp-apps --- LICENSE | 189 ++++++++++++++++++++++++ README.md | 2 +- license.md | 8 - pyproject.toml | 6 +- server_config.json | 3 + src/mcp_cli/apps/host.py | 23 ++- src/mcp_cli/apps/host_page.py | 23 +++ src/mcp_cli/chat/tool_processor.py | 13 ++ src/mcp_cli/dashboard/bridge.py | 41 +++++ src/mcp_cli/dashboard/static/shell.html | 93 +++++++++++- src/mcp_cli/tools/manager.py | 5 + tests/apps/test_host.py | 88 +++++++++++ tests/dashboard/test_bridge_extended.py | 91 ++++++++++++ 13 files changed, 566 insertions(+), 19 deletions(-) create mode 100644 LICENSE delete mode 100644 license.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..ea226ed1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,189 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by the Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding any notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 0e87fb1f..397fa8cb 100644 --- a/README.md +++ b/README.md @@ -1425,7 +1425,7 @@ pytest --cov=mcp_cli --cov-report=html ## πŸ“œ License -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. +This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details. ## πŸ™ Acknowledgments diff --git a/license.md b/license.md deleted file mode 100644 index 371e6299..00000000 --- a/license.md +++ /dev/null @@ -1,8 +0,0 @@ -# Released under MIT License -Copyright (c) Chris Hay. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 5980f937..960d3ea7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,11 +8,9 @@ version = "0.17" description = "A cli for the Model Context Provider" requires-python = ">=3.11" readme = "README.md" -authors = [ - { name = "Chris Hay", email = "chrishayuk@somejunkmailbox.com" } -] +authors = [] keywords = ["llm", "openai", "claude", "mcp", "cli"] -license = {text = "MIT"} +license = {text = "Apache-2.0"} dependencies = [ "asyncio>=3.4.3", "chuk-ai-planner>=0.2", diff --git a/server_config.json b/server_config.json index cc46273a..2b1eb0ec 100644 --- a/server_config.json +++ b/server_config.json @@ -83,6 +83,9 @@ "her": { "url": "https://her.chukai.io/mcp" }, + "chart": { + "url": "https://chart.chukai.io/mcp" + }, "view_demo": { "url": "https://mcp-view-demo.fly.dev/mcp" } diff --git a/src/mcp_cli/apps/host.py b/src/mcp_cli/apps/host.py index 78600daa..4fc35af9 100644 --- a/src/mcp_cli/apps/host.py +++ b/src/mcp_cli/apps/host.py @@ -73,6 +73,7 @@ async def launch_app( resource_uri: str, server_name: str, tool_result: Any = None, + open_browser: bool = True, ) -> AppInfo: """Launch an MCP App in the browser. @@ -105,6 +106,17 @@ async def launch_app( ) html_content = self._extract_html(resource) + # Fallback: retry without server filter (server may be registered + # under a different transport name than the tool namespace). + if not html_content and server_name: + logger.debug( + "Retrying resource %s without server filter (was: %s)", + resource_uri, + server_name, + ) + resource = await self.tool_manager.read_resource(resource_uri) + html_content = self._extract_html(resource) + if not html_content: raise RuntimeError( f"Could not fetch UI resource {resource_uri} from {server_name}" @@ -138,7 +150,7 @@ async def launch_app( await self._start_server(app_info, bridge, tool_result) # Open browser - if DEFAULT_APP_AUTO_OPEN_BROWSER: + if open_browser and DEFAULT_APP_AUTO_OPEN_BROWSER: try: webbrowser.open(app_info.url) logger.info("Opened MCP App for %s at %s", tool_name, app_info.url) @@ -272,7 +284,10 @@ async def _start_server( def process_request( connection: ServerConnection, request: Request ) -> Response | None: - if request.path == "/" or request.path == "": + # Strip query string for path matching (?embedded=1 etc.) + path = request.path.split("?", 1)[0] + + if path == "/" or path == "": return Response( http.HTTPStatus.OK, "OK", @@ -284,7 +299,7 @@ def process_request( ), host_page_bytes, ) - if request.path == "/app": + if path == "/app": return Response( http.HTTPStatus.OK, "OK", @@ -296,7 +311,7 @@ def process_request( ), app_html_bytes, ) - if request.path != "/ws": + if path != "/ws": body = b"Not Found" return Response( http.HTTPStatus.NOT_FOUND, diff --git a/src/mcp_cli/apps/host_page.py b/src/mcp_cli/apps/host_page.py index def6b6e8..2ee70345 100644 --- a/src/mcp_cli/apps/host_page.py +++ b/src/mcp_cli/apps/host_page.py @@ -289,6 +289,29 @@ }}, INIT_TIMEOUT); }} + // ---- Embedded mode (hide host header when inside dashboard panel) ---- + if (new URLSearchParams(window.location.search).has("embedded")) {{ + document.getElementById("header").style.display = "none"; + document.getElementById("app-container").style.height = "100vh"; + document.body.style.background = "transparent"; + }} + + // ---- Relay viewport changes to inner app iframe ---- + // When embedded in a dashboard panel the outer iframe may start hidden + // (display:none β†’ 0Γ—0 viewport). Canvas-based apps (charts, maps) + // initialise at the wrong size and need an explicit resize kick once + // real dimensions arrive. A ResizeObserver on the root element catches + // every viewport change β€” including the initial 0β†’actual transition. + if (typeof ResizeObserver !== "undefined") {{ + new ResizeObserver(function() {{ + try {{ + if (iframe.contentWindow) {{ + iframe.contentWindow.dispatchEvent(new Event("resize")); + }} + }} catch(e) {{}} + }}).observe(document.documentElement); + }} + // ---- Boot ---- connectWs(); startInitTimer(); diff --git a/src/mcp_cli/chat/tool_processor.py b/src/mcp_cli/chat/tool_processor.py index 6a10492e..fe8a8e84 100644 --- a/src/mcp_cli/chat/tool_processor.py +++ b/src/mcp_cli/chat/tool_processor.py @@ -1026,14 +1026,27 @@ async def _check_and_launch_app(self, tool_name: str, result: Any) -> None: return # No running app for this URI β€” launch a new one + has_dashboard = ( + getattr(self.context, "dashboard_bridge", None) is not None + ) logger.info("Tool %s has MCP App UI at %s", tool_name, resource_uri) app_info = await app_host.launch_app( tool_name=tool_name, resource_uri=resource_uri, server_name=server_name, tool_result=result, + open_browser=not has_dashboard, ) logger.info("MCP App opened at %s", app_info.url) + + # Notify dashboard to embed the app as a panel + if has_dashboard: + dash_bridge = getattr(self.context, "dashboard_bridge", None) + if dash_bridge is not None: + try: + await dash_bridge.on_app_launched(app_info) + except Exception as exc: + logger.debug("Dashboard on_app_launched error: %s", exc) return # ── Case 2: no resourceUri β€” route ui_patch to running app ─── diff --git a/src/mcp_cli/dashboard/bridge.py b/src/mcp_cli/dashboard/bridge.py index 1afab2b4..b693c46b 100644 --- a/src/mcp_cli/dashboard/bridge.py +++ b/src/mcp_cli/dashboard/bridge.py @@ -71,6 +71,8 @@ def __init__( self._seen_view_ids: set[str] = set() # Pending tool approval futures keyed by call_id self._pending_approvals: dict[str, asyncio.Future[bool]] = {} + # Running MCP Apps (for replay on client reconnect) + self._running_apps: dict[str, dict[str, Any]] = {} # Dual-mode: router-managed vs direct-wiring if isinstance(server, AgentRouter): @@ -218,6 +220,39 @@ async def on_view_registry_update(self, views: list[dict[str, Any]]) -> None: _envelope("VIEW_REGISTRY", {"agent_id": self.agent_id, "views": views}) ) + async def on_app_launched(self, app_info: Any) -> None: + """Notify dashboard that an MCP App launched β€” embed as panel.""" + payload: dict[str, Any] = { + "agent_id": self.agent_id, + "tool_name": app_info.tool_name, + "url": app_info.url, + "port": app_info.port, + "server_name": app_info.server_name, + "resource_uri": app_info.resource_uri, + "state": ( + app_info.state.value + if hasattr(app_info.state, "value") + else str(app_info.state) + ), + "timestamp": _now(), + } + self._running_apps[app_info.tool_name] = payload + await self._broadcast(_envelope("APP_LAUNCHED", payload)) + + async def on_app_closed(self, tool_name: str) -> None: + """Notify dashboard that an MCP App closed.""" + self._running_apps.pop(tool_name, None) + await self._broadcast( + _envelope( + "APP_CLOSED", + { + "agent_id": self.agent_id, + "tool_name": tool_name, + "timestamp": _now(), + }, + ) + ) + async def _discover_view(self, meta_ui: dict[str, Any], server_name: str) -> None: """Register a new view from a _meta.ui block and broadcast VIEW_REGISTRY.""" view_id: str = meta_ui["view"] @@ -270,6 +305,9 @@ async def _on_client_connected(self, ws: Any) -> None: await ws.send( _json.dumps(_envelope("ACTIVITY_HISTORY", {"events": activity})) ) + # APP replay for reconnecting clients + for app_payload in self._running_apps.values(): + await ws.send(_json.dumps(_envelope("APP_LAUNCHED", app_payload))) except Exception as exc: logger.debug("Error sending initial state to new client: %s", exc) @@ -385,6 +423,9 @@ async def _on_browser_message(self, msg: dict[str, Any]) -> None: await self._handle_delete_session(msg) elif msg_type == "RENAME_SESSION": await self._handle_rename_session(msg) + elif msg_type == "REQUEST_APP_LIST": + for app_payload in self._running_apps.values(): + await self._broadcast(_envelope("APP_LAUNCHED", app_payload)) else: logger.debug("Dashboard received unknown message type: %s", msg_type) diff --git a/src/mcp_cli/dashboard/static/shell.html b/src/mcp_cli/dashboard/static/shell.html index be278448..fa770954 100644 --- a/src/mcp_cli/dashboard/static/shell.html +++ b/src/mcp_cli/dashboard/static/shell.html @@ -819,6 +819,14 @@

Tool Confirmation Required

rebuildAddPanelMenu(); break; + // ── MCP App lifecycle ────────────────────────────────────── + case 'APP_LAUNCHED': + handleAppLaunched(msg.payload); + break; + case 'APP_CLOSED': + handleAppClosed(msg.payload); + break; + // ── Agent lifecycle messages ─────────────────────────────── case 'AGENT_LIST': handleAgentList(msg.payload); @@ -932,9 +940,20 @@

Tool Confirmation Required

if (viewPool.has(viewId)) return viewPool.get(viewId); const view = { iframe: null, ready: false, accepts: [], _readyTimeout: null }; const iframe = document.createElement('iframe'); - iframe.sandbox = 'allow-scripts allow-same-origin allow-forms'; + // App iframes load cross-origin host pages β€” need permissive sandbox + if (viewId.startsWith('app:')) { + iframe.sandbox = 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox'; + } else { + iframe.sandbox = 'allow-scripts allow-same-origin allow-forms'; + } iframe.allow = ''; - iframe.src = srcForView(viewId); + // App views: append ?embedded=1 to hide the host page header (dashboard panel + // already provides its own header). srcForView returns the raw URL so pop-out + // still shows the standalone host header. + const viewUrl = srcForView(viewId); + iframe.src = viewId.startsWith('app:') && viewUrl + ? viewUrl + (viewUrl.includes('?') ? '&' : '?') + 'embedded=1' + : viewUrl; iframe.dataset.viewId = viewId; view.iframe = iframe; viewPool.set(viewId, view); @@ -951,6 +970,8 @@

Tool Confirmation Required

// No reparenting β€” iframe stays in #view-overlay. // syncViewPositions() will position it over the panel body. requestAnimationFrame(() => syncViewPositions()); + // App views use JSON-RPC, not mcp-dashboard READY β€” skip timeout + if (viewId.startsWith('app:')) { view.ready = true; return; } // Start ready timeout only for first load if (!view.ready && !view._readyTimeout) { view._readyTimeout = setTimeout(() => { @@ -1747,6 +1768,74 @@

Tool Confirmation Required

setTimeout(() => toast.remove(), duration || 5000); } +// ================================================================ +// MCP App panel handlers +// ================================================================ + +function handleAppLaunched(payload) { + const toolName = payload.tool_name; + const appUrl = payload.url; + const viewId = 'app:' + toolName; + + // Already registered β€” update URL and refresh iframe + const existing = viewRegistry.find(v => v.id === viewId); + if (existing) { + existing.url = appUrl; + const view = viewPool.get(viewId); + if (view && view.iframe) { + view.iframe.src = appUrl + (appUrl.includes('?') ? '&' : '?') + 'embedded=1'; + } + showToast('info', 'App updated: ' + toolName); + return; + } + + // Register as new view + viewRegistry.push({ + id: viewId, + name: toolName.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()), + source: payload.server_name || 'app', + icon: '\u{1F5A5}', + type: 'app', + url: appUrl, + }); + rebuildAddPanelMenu(); + + // Auto-create panel + addPanelWithView(viewId); + + // Mark auto-ready (app uses JSON-RPC, not mcp-dashboard READY) + const view = viewPool.get(viewId); + if (view) { + view.ready = true; + if (view._readyTimeout) { clearTimeout(view._readyTimeout); view._readyTimeout = null; } + } + + showToast('success', 'App launched: ' + toolName); +} + +function handleAppClosed(payload) { + const viewId = 'app:' + payload.tool_name; + + viewRegistry = viewRegistry.filter(v => v.id !== viewId); + + // Close hosting panel + for (const [panelId, panel] of Object.entries(panels)) { + if (panel.viewId === viewId) { closePanel(panelId); break; } + } + + // Clean up iframe and popout + const view = viewPool.get(viewId); + if (view && view.iframe) view.iframe.remove(); + viewPool.delete(viewId); + + const popout = popoutWindows.get(viewId); + if (popout && !popout.win.closed) { popout.win.close(); clearInterval(popout.intervalId); } + popoutWindows.delete(viewId); + + rebuildAddPanelMenu(); + showToast('info', 'App closed: ' + payload.tool_name); +} + // ================================================================ // Tool approval dialog // ================================================================ diff --git a/src/mcp_cli/tools/manager.py b/src/mcp_cli/tools/manager.py index 0f7a1c68..9dc2f479 100644 --- a/src/mcp_cli/tools/manager.py +++ b/src/mcp_cli/tools/manager.py @@ -1284,12 +1284,17 @@ async def read_resource( Resource content dict from the server. """ if not self.stream_manager: + logger.debug("read_resource: no stream_manager available") return {} try: result: dict[str, Any] = await self.stream_manager.read_resource( uri, server_name ) + if not result: + logger.debug( + "read_resource returned empty for %s (server=%s)", uri, server_name + ) return result except Exception as e: logger.error("Error reading resource %s from %s: %s", uri, server_name, e) diff --git a/tests/apps/test_host.py b/tests/apps/test_host.py index 1832d129..5f89fdaf 100644 --- a/tests/apps/test_host.py +++ b/tests/apps/test_host.py @@ -993,6 +993,36 @@ async def capture_serve(handler, host_addr, port, process_request=None): assert response is not None assert response.status_code == http.HTTPStatus.OK + @pytest.mark.asyncio + async def test_process_request_serves_root_with_query_string(self): + """The process_request closure returns 200 for '/?embedded=1'.""" + from unittest.mock import MagicMock, patch + from mcp_cli.apps.bridge import AppBridge + import http + + host, info = self._make_host_and_app_info() + bridge = AppBridge(info, host.tool_manager) + + captured_process_request = None + + async def capture_serve(handler, host_addr, port, process_request=None): + nonlocal captured_process_request + captured_process_request = process_request + return MagicMock() + + with patch("mcp_cli.apps.host.ws_serve", side_effect=capture_serve): + await host._start_server(info, bridge) + + assert captured_process_request is not None + + fake_conn = MagicMock() + fake_req = MagicMock() + fake_req.path = "/?embedded=1" + + response = captured_process_request(fake_conn, fake_req) + assert response is not None + assert response.status_code == http.HTTPStatus.OK + @pytest.mark.asyncio async def test_process_request_serves_empty_path_as_root(self): """The process_request closure treats '' the same as '/'.""" @@ -1363,3 +1393,61 @@ def test_dict_with_none_blob_returns_empty(self): """A dict entry with text=None and blob=None returns empty string.""" resource = {"contents": [{"text": None, "blob": None}]} assert AppHostServer._extract_html(resource) == "" + + +# ── LaunchApp browser control ──────────────────────────────────────────── + + +class TestLaunchAppBrowserControl: + """Verify the open_browser parameter controls webbrowser.open() calls.""" + + @pytest.mark.asyncio + async def test_open_browser_false_suppresses_webbrowser(self): + """When open_browser=False, webbrowser.open should not be called.""" + from unittest.mock import AsyncMock, patch + + host = AppHostServer(FakeToolManager()) + browser_calls: list[str] = [] + + with ( + patch.object(host, "_start_server", new=AsyncMock()), + patch.object( + host, "_find_available_port", new=AsyncMock(return_value=9999) + ), + patch("mcp_cli.apps.host.webbrowser") as mock_wb, + ): + mock_wb.open = lambda url: browser_calls.append(url) + app_info = await host.launch_app( + tool_name="test_tool", + resource_uri="ui://test/app.html", + server_name="test_server", + open_browser=False, + ) + + assert app_info.port == 9999 + assert browser_calls == [] + + @pytest.mark.asyncio + async def test_open_browser_true_calls_webbrowser(self): + """When open_browser=True (default), webbrowser.open should be called.""" + from unittest.mock import AsyncMock, patch + + host = AppHostServer(FakeToolManager()) + browser_calls: list[str] = [] + + with ( + patch.object(host, "_start_server", new=AsyncMock()), + patch.object( + host, "_find_available_port", new=AsyncMock(return_value=9999) + ), + patch("mcp_cli.apps.host.webbrowser") as mock_wb, + ): + mock_wb.open = lambda url: browser_calls.append(url) + await host.launch_app( + tool_name="test_tool", + resource_uri="ui://test/app.html", + server_name="test_server", + ) + + assert len(browser_calls) == 1 + assert "9999" in browser_calls[0] diff --git a/tests/dashboard/test_bridge_extended.py b/tests/dashboard/test_bridge_extended.py index 90395f14..c9f9bee1 100644 --- a/tests/dashboard/test_bridge_extended.py +++ b/tests/dashboard/test_bridge_extended.py @@ -896,3 +896,94 @@ async def test_bad_file_logged_not_crashed(self): assert ctx.attachment_staging.count == 0 # Text should still be queued assert bridge._input_queue.qsize() == 1 + + +# --------------------------------------------------------------------------- +# MCP App lifecycle (APP_LAUNCHED / APP_CLOSED) +# --------------------------------------------------------------------------- + + +class TestAppLifecycle: + """Tests for on_app_launched, on_app_closed, and replay on connect.""" + + @staticmethod + def _make_app_info(): + info = MagicMock() + info.tool_name = "show_chart" + info.url = "http://localhost:9470" + info.port = 9470 + info.server_name = "demo" + info.resource_uri = "ui://demo/chart.html" + info.state = MagicMock(value="ready") + return info + + @pytest.mark.asyncio + async def test_on_app_launched_broadcasts(self): + bridge, server = _make_bridge() + app_info = self._make_app_info() + + await bridge.on_app_launched(app_info) + + server.broadcast.assert_awaited_once() + msg = server.broadcast.call_args[0][0] + assert msg["protocol"] == "mcp-dashboard" + assert msg["type"] == "APP_LAUNCHED" + assert msg["payload"]["tool_name"] == "show_chart" + assert msg["payload"]["url"] == "http://localhost:9470" + assert msg["payload"]["port"] == 9470 + assert msg["payload"]["server_name"] == "demo" + + @pytest.mark.asyncio + async def test_on_app_closed_broadcasts(self): + bridge, server = _make_bridge() + app_info = self._make_app_info() + await bridge.on_app_launched(app_info) + + server.broadcast.reset_mock() + await bridge.on_app_closed("show_chart") + + server.broadcast.assert_awaited_once() + msg = server.broadcast.call_args[0][0] + assert msg["type"] == "APP_CLOSED" + assert msg["payload"]["tool_name"] == "show_chart" + + @pytest.mark.asyncio + async def test_on_app_closed_removes_from_running(self): + bridge, server = _make_bridge() + app_info = self._make_app_info() + await bridge.on_app_launched(app_info) + assert "show_chart" in bridge._running_apps + + await bridge.on_app_closed("show_chart") + assert "show_chart" not in bridge._running_apps + + @pytest.mark.asyncio + async def test_running_apps_replayed_on_connect(self): + bridge, server = _make_bridge() + app_info = self._make_app_info() + await bridge.on_app_launched(app_info) + + # Simulate client connect + ws = AsyncMock() + await bridge._on_client_connected(ws) + + # Parse all sent messages + sent = [json.loads(c.args[0]) for c in ws.send.call_args_list] + app_msgs = [m for m in sent if m.get("type") == "APP_LAUNCHED"] + assert len(app_msgs) == 1 + assert app_msgs[0]["payload"]["tool_name"] == "show_chart" + assert app_msgs[0]["payload"]["url"] == "http://localhost:9470" + + @pytest.mark.asyncio + async def test_request_app_list_replays_running(self): + bridge, server = _make_bridge() + app_info = self._make_app_info() + await bridge.on_app_launched(app_info) + + server.broadcast.reset_mock() + await bridge._on_browser_message({"type": "REQUEST_APP_LIST"}) + + server.broadcast.assert_awaited_once() + msg = server.broadcast.call_args[0][0] + assert msg["type"] == "APP_LAUNCHED" + assert msg["payload"]["tool_name"] == "show_chart" From 24c951b649ad590ebe80e33e9a67de9a82be8282 Mon Sep 17 00:00:00 2001 From: chrishayuk Date: Sun, 1 Mar 2026 14:53:32 +0000 Subject: [PATCH 2/4] improved apps rendering --- src/mcp_cli/apps/host.py | 40 ++++++++++++++++++++++++++- src/mcp_cli/apps/host_page.py | 44 ++++++++++++++++-------------- src/mcp_cli/chat/tool_processor.py | 40 +++++++++++++++++++++++++++ src/mcp_cli/tools/models.py | 11 ++++++++ 4 files changed, 114 insertions(+), 21 deletions(-) diff --git a/src/mcp_cli/apps/host.py b/src/mcp_cli/apps/host.py index 4fc35af9..bbb63553 100644 --- a/src/mcp_cli/apps/host.py +++ b/src/mcp_cli/apps/host.py @@ -74,6 +74,7 @@ async def launch_app( server_name: str, tool_result: Any = None, open_browser: bool = True, + view_url: str | None = None, ) -> AppInfo: """Launch an MCP App in the browser. @@ -81,6 +82,9 @@ async def launch_app( 2. Start a local HTTP + WebSocket server 3. Open the user's default browser 4. Push the initial tool result once the WebSocket connects + + ``view_url`` is an optional direct HTTPS fallback used when + ``resources/read`` for the ``resource_uri`` fails. """ # Close any previous instance of this tool's app if tool_name in self._apps: @@ -117,6 +121,16 @@ async def launch_app( resource = await self.tool_manager.read_resource(resource_uri) html_content = self._extract_html(resource) + # Last resort: use viewUrl (direct HTTPS) if resources/read failed. + if not html_content and view_url: + logger.info( + "resources/read failed for %s, falling back to viewUrl %s", + resource_uri, + view_url, + ) + html_content, resource = await self._fetch_http_resource(view_url) + resource_uri = view_url # update URI for app info + if not html_content: raise RuntimeError( f"Could not fetch UI resource {resource_uri} from {server_name}" @@ -278,7 +292,31 @@ async def _start_server( init_timeout=DEFAULT_APP_INIT_TIMEOUT, ) host_page_bytes = host_page.encode("utf-8") - app_html_bytes = app_info.html_content.encode("utf-8") + + # Inject viewport-filling CSS into the app HTML. MCP App views + # are often designed for Claude.ai's inline display (fixed aspect + # ratio). When hosted inside an iframe panel, the root element + # chain needs to fill 100% height so canvas-based apps (Chart.js, + # Leaflet, D3) can use the available space. + app_html = app_info.html_content + _fill_css = ( + "" + ) + if "" in app_html: + app_html = app_html.replace("", _fill_css + "", 1) + elif "