Skip to content

Conversation

JoeCastrom
Copy link

@JoeCastrom JoeCastrom commented Sep 19, 2025

MCP UI Integration for LobeChat

MCP UI extends the Model Context Protocol (MCP) by allowing server tool calls to return not just plain text, but also UI elements such as raw HTML or embeddable iFrame URLs. It further provides a communication channel between the client and embedded UIs via message passing.

Several popular clients—such as Postman and Goose by Block—already support this capability.
This PR brings equivalent MCP UI integration to LobeChat, enabling secure, interactive, and accessible experiences.

💻 变更类型 | Change Type

  • ✨ feat
  • 🐛 fix
  • ♻️ refactor
  • 💄 style
  • 👷 build
  • ⚡️ perf
  • ✅ test
  • 📝 docs
  • 🔨 chore

🔀 变更说明 | Description of Change

This PR adds comprehensive MCP (Model Context Protocol) UI integration support to LobeChat, enabling rich interactive content rendering from MCP servers.

💡 Key Features

  • 🖼️ Rich UI Rendering: Support for HTML, URL, and iframe content types
  • 🔒 Secure Sandboxing: Sandboxed iframe execution with restricted permissions
  • 📱 Responsive Design: Auto-sizing with accessibility features
  • 🔧 Type Safety: Complete TypeScript support with proper interfaces
  • 🔄 Backward Compatibility: Zero breaking changes to existing functionality

🏗️ Architecture

Data Flow

  MCP Server Response → extractUIResources() → Base64 Encoding → Database Storage
                                      ↓
  UI Resources → McpUIRender → Sandboxed Iframe → User Interface

Security Features

  • Sandboxed iframe with allow-scripts allow-same-origin allow-forms
  • Data URI encoding prevents external resource loading
  • Height limits (800px max) prevent UI breaking
  • Content validation and error boundaries

📁 Files Changed

New Files (2)

  • src/tools/mcp-ui/Render/index.tsx - Main UI renderer component
  • src/tools/mcp-ui/utils/extractUIResources.ts - Resource extraction utilities

Modified Files (8)

  • src/services/mcp.ts - UI resource processing & integration
  • src/features/PluginsUI/Render/index.tsx - Added 'mcp-ui' render case
  • src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx - MCP tool detection
  • packages/types/src/tool/index.ts - Extended LobeToolRenderType
  • packages/types/src/message/tools.ts - Added McpUIResource interface
  • packages/database/src/schemas/message.ts - Updated schema for mcp-ui type
  • src/store/chat/slices/message/action.ts - Database compatibility layer
  • src/store/chat/slices/plugin/action.ts - Type transformation

🧪 Testing

  • ✅ Functional testing with weather widgets
  • ✅ Auto-sizing and responsive behavior
  • ✅ Error handling and fallbacks
  • ✅ TypeScript compilation (0 errors)
  • ✅ Security boundary validation

🔧 Implementation Highlights

  1. Smart Detection: Uses identifier patterns for MCP tool recognition
  2. Database Compatibility: Transforms 'mcp-ui' → 'builtin' for storage
  3. Clean Integration: Minimal changes leveraging existing architecture

📝 补充信息 | Additional Information

📸 Demo

Example MCP Server that has UI Resources as HTML

Name: mcp-aharvard
Transport Type: Streamable HTTP
URL: https://mcp-aharvard.netlify.app/mcp

Before MCP UI:
before

After MCP UI Integration:
after

✅ Summary

This PR introduces secure MCP UI rendering to LobeChat, enabling rich interactive content such as widgets, dashboards, and HTML-based components from MCP servers—while maintaining strict security boundaries and backward compatibility.

Summary by Sourcery

Add comprehensive MCP UI integration to LobeChat by extracting UI resources from server responses, securely rendering them as HTML/URL/iframe elements, and updating the tool pipeline, types, and storage without breaking existing functionality

New Features:

  • Enable extraction and rendering of MCP UI resources (HTML, URL, iframe) within LobeChat
  • Introduce a new 'mcp-ui' render type with secure sandboxed iframe support and auto-resizing
  • Extend message processing to encode, store, and transform MCP UI resources within chat responses

Enhancements:

  • Update TypeScript interfaces, tool manifests, and database schema to support MCP UI resources
  • Preserve backward compatibility by mapping 'mcp-ui' tool types to existing builtin storage format
  • Refine plugin and tool rendering logic to detect and display MCP UI content when present

Tests:

  • Add example test cases demonstrating HTML, URL, and iframe MCP UI resource formats

- Add MCP UI resource extraction and rendering system
- Support HTML, URL, and iframe content types with sandboxed rendering
- Hide tool inspector when UI resources are present
- Add type safety with TypeScript definitions
- Support multiple UI resource formats and encoding patterns
Copy link

vercel bot commented Sep 19, 2025

@JoeCastrom is attempting to deploy a commit to the LobeHub OSS Team on Vercel.

A member of the Team first needs to authorize it.

@dosubot dosubot bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Sep 19, 2025
@lobehubbot
Copy link
Member

👍 @JoeCastrom

Thank you for raising your pull request and contributing to our Community
Please make sure you have followed our contributing guidelines. We will review it as soon as possible.
If you encounter any problems, please feel free to connect with us.
非常感谢您提出拉取请求并为我们的社区做出贡献,请确保您已经遵循了我们的贡献指南,我们会尽快审查它。
如果您遇到任何问题,请随时与我们联系。

Copy link
Contributor

gru-agent bot commented Sep 19, 2025

TestGru Assignment

Summary

Link CommitId Status Reason
Detail 4bbeaf7 ✅ Finished

History Assignment

Files

File Pull Request
src/store/chat/slices/plugin/action.ts ❌ Failed (I failed to setup the environment.)
src/store/chat/slices/message/action.ts ❌ Failed (I failed to setup the environment.)
src/services/mcp.ts ❌ Failed (I failed to setup the environment.)

Tip

You can @gru-agent and leave your feedback. TestGru will make adjustments based on your input

@dosubot dosubot bot added the 🌠 Feature Request New feature or request | 特性与建议 label Sep 19, 2025
Copy link
Contributor

sourcery-ai bot commented Sep 19, 2025

Reviewer's Guide

This PR implements full MCP UI integration by extracting and encoding UI resources from MCP responses, extending service logic, updating rendering components, adjusting state persistence, and introducing new types, utilities, and sandboxed UI rendering components while preserving backward compatibility.

Sequence diagram for MCP UI resource extraction and rendering

sequenceDiagram
    participant MCPServer
    participant MCPService
    participant extractUIResources()
    participant Database
    participant McpUIRender
    participant User
    MCPServer->>MCPService: Send response (may contain UI resources)
    MCPService->>extractUIResources(): Extract text and UI resources
    extractUIResources()-->>MCPService: Return {textContent, uiResources}
    MCPService->>Database: Store encoded UI resources (Base64)
    User->>McpUIRender: View message with UI resources
    McpUIRender->>User: Render HTML/iframe/URL in sandboxed UI
Loading

Entity relationship diagram for MCP UI resource data model changes

erDiagram
    MESSAGE ||--o| MESSAGE_PLUGIN : contains
    MESSAGE_PLUGIN {
      text tool_call_id
      text type
      text api_name
      text identifier
      json args
      json result
      json error
    }
    MESSAGE_PLUGIN ||--|{ MCP_UI_RESOURCE : has
    MCP_UI_RESOURCE {
      string content
      string type
      json metadata
    }
Loading

Class diagram for new and updated types for MCP UI integration

classDiagram
    class McpUIResource {
      +string content
      +string type ("html"|"url"|"iframe")
      +metadata: Record<string, any>
    }
    class LobeTool {
      +type: LobeToolRenderType
    }
    class LobeToolRenderType {
      <<union>>
      builtin
      mcp-ui
      ...
    }
    class BuiltinToolManifest {
      +api
      +identifier
      +meta
      +systemRole
      +type
    }
    McpUIResource <|-- BuiltinToolManifest
    LobeTool --> LobeToolRenderType
Loading

File-Level Changes

Change Details Files
Service layer extraction and encoding of MCP UI resources
  • Invoke extractUIResources in MCPService to separate text and UI data
  • Base64-encode UI resources and append marker to response
  • Conditionally include minimal text or pure UI marker based on content
src/services/mcp.ts
Integration of MCP UI rendering in client components
  • Add 'mcp-ui' case in PluginRender to use McpUIRender
  • Enhance CustomRender to detect MCP tools and choose 'mcp-ui' renderType
  • Modify Tool inspector to hide details and show UI for MCP responses
src/features/PluginsUI/Render/index.tsx
src/features/Conversation/Messages/Assistant/Tool/Render/CustomRender.tsx
src/features/Conversation/Messages/Assistant/Tool/index.tsx
State management adjustments for database compatibility
  • Implement transformToolsForDB to map 'mcp-ui' to 'builtin' before saving
  • Update plugin action handlers to convert 'mcp-ui' tool types on updates
src/store/chat/slices/message/action.ts
src/store/chat/slices/plugin/action.ts
TypeScript and schema extensions for MCP UI
  • Define McpUIResource interface and extend LobeToolRenderType with 'mcp-ui'
  • Add 'mcp-ui' to messagePlugins enum in database schema
packages/types/src/message/tools.ts
packages/types/src/tool/index.ts
packages/database/src/schemas/message.ts
Added utilities, manifest, and rendering components for MCP UI
  • Create extractUIResources and hasUIResources utilities to parse UI data
  • Implement McpUIRender component with sandboxed iframe and responsive sizing
  • Introduce McpUIManifest and register it in tools index and renders map
  • Provide test examples for HTML, URL, and iframe resources
src/tools/mcp-ui/utils/extractUIResources.ts
src/tools/mcp-ui/Render/index.tsx
src/tools/mcp-ui/index.ts
src/tools/index.ts
src/tools/renders.ts
src/tools/mcp-ui/test-example.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/tools/mcp-ui/utils/extractUIResources.ts:17` </location>
<code_context>
+  // Parse text content for ui:// prefixed resources
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Regex may not match all valid ui:// resource URIs due to use of \S+.

The current pattern may fail for URIs with spaces or special characters. Please update the regex to handle a wider range of valid URI formats.

```suggestion
    const uiResourceRegex = /ui:\/\/([^\s'"]+)/g;
```
</issue_to_address>

### Comment 2
<location> `src/tools/mcp-ui/utils/extractUIResources.ts:23-32` </location>
<code_context>
+**Changes:** Added 'mcp-ui' case to plugin rendering switch
+```typescript
+case 'mcp-ui': {
+  try {
+    const { extractUIResources } = require('@/tools/mcp-ui/utils/extractUIResources');
+    const { textContent, uiResources } = extractUIResources(content);
</code_context>

<issue_to_address>
**suggestion:** atob usage may throw for non-base64 strings, but fallback only checks for http URLs.

The current fallback may not handle non-base64, non-http URIs. Please consider expanding the fallback logic or add logging for unsupported formats.
</issue_to_address>

### Comment 3
<location> `src/tools/mcp-ui/Render/index.tsx:60` </location>
<code_context>
+
+### Iframe Sandbox Configuration
+```typescript
+sandbox="allow-scripts allow-same-origin allow-forms"
+```
+- **allow-scripts:** Enable JavaScript for interactive content
</code_context>

<issue_to_address>
**🚨 issue (security):** Allowing 'allow-same-origin' in sandbox may introduce security risks.

Review if 'allow-same-origin' is essential; removing it can reduce exposure to malicious iframe content.
</issue_to_address>

### Comment 4
<location> `src/tools/mcp-ui/Render/index.tsx:39-48` </location>
<code_context>
+              onLoad={(e) => {
</code_context>

<issue_to_address>
**nitpick:** Auto-resizing iframe based on content may fail for cross-origin data.

Document the cross-origin limitation and consider implementing a more reliable fallback for iframe height when content cannot be accessed.
</issue_to_address>

### Comment 5
<location> `src/services/mcp.ts:78-79` </location>
<code_context>
+
+      // If there are UI resources, encode them into the response string
+      if (uiResources.length > 0) {
+        // Encode UI resources as base64 JSON and append to content
+        const encodedResources = btoa(JSON.stringify({ uiResources }));
+
+        // Exclude verbose UI resource text from LLM context
</code_context>

<issue_to_address>
**issue (bug_risk):** btoa may throw for non-ASCII content in UI resources.

btoa will fail if UI resources include non-ASCII characters. Use a base64 encoding method that supports UTF-8, such as Buffer or a suitable library, to prevent runtime errors.
</issue_to_address>

### Comment 6
<location> `src/tools/mcp-ui/utils/extractUIResources.ts:67` </location>
<code_context>
        const resource = item.resource;

</code_context>

<issue_to_address>
**suggestion (code-quality):** Prefer object destructuring when accessing and using properties. ([`use-object-destructuring`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/use-object-destructuring))

```suggestion
        const {resource} = item;
```

<br/><details><summary>Explanation</summary>Object destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the [Airbnb Javascript Style Guide](https://airbnb.io/javascript/#destructuring--object)
</details>
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.


// Parse text content for ui:// prefixed resources
if (textContent) {
const uiResourceRegex = /ui:\/\/(\S+)/g;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Regex may not match all valid ui:// resource URIs due to use of \S+.

The current pattern may fail for URIs with spaces or special characters. Please update the regex to handle a wider range of valid URI formats.

Suggested change
const uiResourceRegex = /ui:\/\/(\S+)/g;
const uiResourceRegex = /ui:\/\/([^\s'"]+)/g;

Comment on lines +23 to +32
try {
// Decode if it's base64 encoded
const decodedContent = atob(resourceUri);
const parsedResource = JSON.parse(decodedContent);

if (parsedResource.type && parsedResource.content) {
uiResources.push({
content: parsedResource.content,
metadata: parsedResource.metadata,
type: parsedResource.type,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: atob usage may throw for non-base64 strings, but fallback only checks for http URLs.

The current fallback may not handle non-base64, non-http URIs. Please consider expanding the fallback logic or add logging for unsupported formats.

Comment on lines +78 to +79
// Encode UI resources as base64 JSON and append to content
const encodedResources = btoa(JSON.stringify({ uiResources }));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): btoa may throw for non-ASCII content in UI resources.

btoa will fail if UI resources include non-ASCII characters. Use a base64 encoding method that supports UTF-8, such as Buffer or a suitable library, to prevent runtime errors.

textContent += (textContent ? '\n' : '') + item.text;
} else if (item.type === 'resource' && item.resource) {
// Extract UI resource from MCP resource object
const resource = item.resource;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Prefer object destructuring when accessing and using properties. (use-object-destructuring)

Suggested change
const resource = item.resource;
const {resource} = item;


ExplanationObject destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the Airbnb Javascript Style Guide

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🌠 Feature Request New feature or request | 特性与建议 size:XXL This PR changes 1000+ lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants