Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ yarn add @mcp-ui/server @mcp-ui/client
return (
<HtmlResource
resource={mcpResource.resource}
onUiAction={(tool, params) => {
console.log('Action:', tool, params);
onUiAction={(result) => {
console.log('Action:', result);
return { status: 'ok' };
}}
/>
Expand Down
15 changes: 10 additions & 5 deletions docs/src/guide/client/html-resource.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,21 @@ import type { Resource } from '@modelcontextprotocol/sdk/types';

export interface HtmlResourceProps {
resource: Partial<Resource>;
onUiAction?: (
tool: string,
params: Record<string, unknown>,
) => Promise<any>;
onUiAction?: (result: UiActionResult) => Promise<any>;
style?: React.CSSProperties;
}
```

- **`resource`**: The resource object from an `HtmlResourceBlock`. It should include `uri`, `mimeType`, and either `text` or `blob`.
- **`onUiAction`**: An optional callback that fires when the iframe content (for `ui://` resources) posts a message to your app. The message should look like `{ tool: string, params: Record<string, unknown> }`.
- **`onUiAction`**: An optional callback that fires when the iframe content (for `ui://` resources) posts a message to your app. The message should look like:
```typescript
{ type: 'tool', payload: { toolName: string, params: Record<string, unknown> } } |
{ type: 'intent', payload: { intent: string, params: Record<string, unknown> } } |
{ type: 'prompt', payload: { prompt: string } } |
{ type: 'notification', payload: { message: string } } |
{ type: 'link', payload: { url: string } } |
```
If you don't provide a callback for a specific type, the default handler will be used.
- **`style`** (optional): Custom styles for the iframe.

## How It Works
Expand Down
29 changes: 20 additions & 9 deletions docs/src/guide/client/usage-examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pnpm add @mcp-ui/client react @modelcontextprotocol/sdk

```tsx
import React, { useState } from 'react';
import { HtmlResource } from '@mcp-ui/client';
import { HtmlResource, UiActionResult } from '@mcp-ui/client';

// Simulate fetching an MCP resource block
const fetchMcpResource = async (id: string): Promise<HtmlResource> => {
Expand All @@ -24,12 +24,12 @@ const fetchMcpResource = async (id: string): Promise<HtmlResource> => {
resource: {
uri: 'ui://example/direct-html',
mimeType: 'text/html',
text: "<h1>Direct HTML via Text</h1><p>Content loaded directly.</p><button onclick=\"window.parent.postMessage({tool: 'uiInteraction', params: { action: 'directClick', value: Date.now() }}, '*')\">Click Me (Direct)</button>",
text: "<h1>Direct HTML via Text</h1><p>Content loaded directly.</p><button onclick=\"window.parent.postMessage({ type: 'tool', payload: { toolName: 'uiInteraction', params: { action: 'directClick', value: Date.now() } } }, '*')\">Click Me (Direct)</button>",
},
};
} else if (id === 'blob') {
const html =
"<h1>HTML from Blob</h1><p>Content was Base64 encoded.</p><button onclick=\"window.parent.postMessage({tool: 'uiInteraction', params: { action: 'blobClick', value: 'test' }}, '*')\">Click Me (Blob)</button>";
"<h1>HTML from Blob</h1><p>Content was Base64 encoded.</p><button onclick=\"window.parent.postMessage({ type: 'tool', payload: { toolName: 'uiInteraction', params: { action: 'blobClick', value: 'test' } } }, '*')\">Click Me (Blob)</button>";
return {
type: 'resource',
resource: {
Expand Down Expand Up @@ -72,12 +72,23 @@ const App: React.FC = () => {
setLoading(false);
};

const handleGenericMcpAction = async (
tool: string,
params: Record<string, unknown>,
) => {
console.log(`Action received in host app - Tool: ${tool}, Params:`, params);
setLastAction({ tool, params });
const handleGenericMcpAction = async (result: UiActionResult) => {
if (result.type === 'tool') {
console.log(`Action received in host app - Tool: ${result.payload.toolName}, Params:`, result.payload.params);
setLastAction({ tool: result.payload.toolName, params: result.payload.params });
} else if (result.type === 'prompt') {
console.log(`Prompt received in host app:`, result.payload.prompt);
setLastAction({ prompt: result.payload.prompt });
} else if (result.type === 'link') {
console.log(`Link received in host app:`, result.payload.url);
setLastAction({ url: result.payload.url });
} else if (result.type === 'intent') {
console.log(`Intent received in host app:`, result.payload.intent);
setLastAction({ intent: result.payload.intent });
} else if (result.type === 'notification') {
console.log(`Notification received in host app:`, result.payload.message);
setLastAction({ message: result.payload.message });
}
return {
status: 'Action handled by host application',
receivedParams: params,
Expand Down
17 changes: 12 additions & 5 deletions docs/src/guide/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,18 @@ function App() {
setMcpData(fakeMcpResponse);
}, []);

const handleResourceAction = async (
tool: string,
params: Record<string, unknown>,
) => {
console.log(`Action from resource (tool: ${tool}):`, params);
const handleResourceAction = async (result: UiActionResult) => {
if (result.type === 'tool') {
console.log(`Action from resource (tool: ${result.payload.toolName}):`, result.payload.params);
} else if (result.type === 'prompt') {
console.log(`Prompt from resource:`, result.payload.prompt);
} else if (result.type === 'link') {
console.log(`Link from resource:`, result.payload.url);
} else if (result.type === 'intent') {
console.log(`Intent from resource:`, result.payload.intent);
} else if (result.type === 'notification') {
console.log(`Notification from resource:`, result.payload.message);
}
// Add your handling logic (e.g., initiate followup tool call)
return { status: 'Action received by client' };
};
Expand Down
5 changes: 4 additions & 1 deletion docs/src/guide/protocol-details.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ For `ui://` resources, you can use `window.parent.postMessage` to send data or a
const data = { action: 'formData', value: 'someValue' };
// IMPORTANT: Always specify the targetOrigin for security!
// Use '*' only if the parent origin is unknown or variable and security implications are understood.
window.parent.postMessage({ tool: 'myCustomTool', params: data }, '*');
window.parent.postMessage(
{ type: 'tool', payload: { toolName: 'myCustomTool', params: data } },
'*',
);
}
</script>
```
Expand Down
4 changes: 2 additions & 2 deletions examples/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ yarn add @mcp-ui/server @mcp-ui/client
return (
<HtmlResource
resource={mcpResource.resource}
onUiAction={(tool, params) => {
console.log('Action:', tool, params);
onUiAction={(result) => {
console.log('Action:', result);
return { status: 'ok' };
}}
/>
Expand Down
13 changes: 8 additions & 5 deletions examples/server/app/graph/graph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -402,11 +402,14 @@ const CustomAvatarXAxisTick = (props: {
// @ts-expect-error - window is not typed correctly
if (memberInfo && window.parent) {
const message = {
tool: 'show_user_status',
params: {
id: memberInfo.id,
name: memberInfo.name,
avatarUrl: memberInfo.avatarUrl,
type: 'tool',
payload: {
toolName: 'show_user_status',
params: {
id: memberInfo.id,
name: memberInfo.name,
avatarUrl: memberInfo.avatarUrl,
},
},
};
// @ts-expect-error - window is not typed correctly
Expand Down
9 changes: 6 additions & 3 deletions examples/server/app/user/user.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@ export function User({ user }: { user: UserInfo }) {
// @ts-expect-error - window is not typed correctly
if (user.id && window.parent) {
const message = {
tool: 'nudge_team_member',
params: {
name: user.name,
type: 'tool',
payload: {
toolName: 'nudge_team_member',
params: {
name: user.name,
},
},
};
// @ts-expect-error - window is not typed correctly
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"@testing-library/jest-dom": "^6.1.5",
"@testing-library/react": "^14.1.2",
"@types/jest": "^29.5.11",
"@types/node": "^22.0.0",
"@types/node": "^22.15.18",
"@typescript-eslint/eslint-plugin": "^6.13.2",
"@typescript-eslint/parser": "^6.13.2",
"@vitejs/plugin-react-swc": "^3.9.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ yarn add @mcp-ui/server @mcp-ui/client
return (
<HtmlResource
resource={mcpResource.resource}
onUiAction={(tool, params) => {
console.log('Action:', tool, params);
onUiAction={(result) => {
console.log('Action:', result);
return { status: 'ok' };
}}
/>
Expand Down
21 changes: 12 additions & 9 deletions packages/client/src/components/HtmlResource.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import React, { useEffect, useRef, useState } from 'react';
import type { Resource } from '@modelcontextprotocol/sdk/types.js';
import { UiActionResult } from '../types';

export interface RenderHtmlResourceProps {
resource: Partial<Resource>;
onUiAction?: (
tool: string,
params: Record<string, unknown>,
) => Promise<unknown>;
onUiAction?: (result: UiActionResult) => Promise<unknown>;
style?: React.CSSProperties;
}

Expand Down Expand Up @@ -129,13 +127,18 @@ export const HtmlResource: React.FC<RenderHtmlResourceProps> = ({
function handleMessage(event: MessageEvent) {
// Only process the message if it came from this specific iframe
if (
onUiAction &&
iframeRef.current &&
event.source === iframeRef.current.contentWindow &&
event.data?.tool
event.source === iframeRef.current.contentWindow
) {
onUiAction(event.data.tool, event.data.params || {}).catch((err) => {
console.error('Error from onUiAction in RenderHtmlResource:', err);
const uiActionResult = event.data as UiActionResult;
if (!uiActionResult) {
return;
}
onUiAction?.(uiActionResult)?.catch((err) => {
console.error(
'Error handling UI action result in RenderHtmlResource:',
err,
);
});
}
}
Expand Down
Loading