mcp-ui 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
@@ -0,0 +1 @@
1
+ 3.13
mcp_ui-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [year] [fullname]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
mcp_ui-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,306 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-ui
3
+ Version: 0.1.0
4
+ Summary: A Python SDK for building MCP UI resources (iframe, panels, text blocks, etc.) in a type-safe way.
5
+ Project-URL: Homepage, https://github.com/jameszokah/mcp-ui
6
+ Project-URL: Repository, https://github.com/jameszokah/mcp-ui
7
+ Project-URL: Issues, https://github.com/jameszokah/mcp-ui/issues
8
+ Project-URL: Documentation, https://github.com/jameszokah/mcp-ui#readme
9
+ Author-email: James Zokah <jameszokah@gmail.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,chat,iframe,mcp,python,sdk,ui
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+
25
+
26
+ # MCP-UI Python SDK
27
+
28
+ This library is a Python port of the MCP-UI TypeScript SDK.
29
+ It provides strongly typed helpers for creating UI resources and UI actions in MCP servers, with good DX (developer experience), type safety, and MCP-compatible JSON output.
30
+
31
+ ---
32
+
33
+ ## 📦 Installation
34
+
35
+ \`\`\`bash
36
+ pip install mcp-ui
37
+ \`\`\`
38
+
39
+ ---
40
+
41
+ ## 🚀 Core Concepts
42
+
43
+ ### What is a UI Resource?
44
+ A **UI resource** is a unit of UI data (e.g., an HTML snippet, iframe, or Remote DOM script) that MCP clients can render.
45
+ This SDK helps you create them consistently with correct metadata and encodings.
46
+
47
+ ### What is a UI Action?
48
+ A **UI action result** represents an action the MCP client should take (e.g., open a link, show a prompt, call a tool).
49
+
50
+ ---
51
+
52
+ ## 🔧 Usage
53
+
54
+ ### 1. Creating a UI Resource
55
+
56
+ #### Raw HTML
57
+
58
+ \`\`\`python
59
+ from mcp_ui import RawHtmlContent, CreateUIResourceOptions, create_ui_resource
60
+
61
+ options = CreateUIResourceOptions(
62
+ uri="ui://demo/html",
63
+ content=RawHtmlContent(type="rawHtml", htmlString="<h1>Hello MCP</h1>"),
64
+ encoding="text"
65
+ )
66
+
67
+ resource = create_ui_resource(options)
68
+ print(resource)
69
+ \`\`\`
70
+
71
+ **Output:**
72
+
73
+ \`\`\`json
74
+ {
75
+ "type": "resource",
76
+ "resource": {
77
+ "uri": "ui://demo/html",
78
+ "mimeType": "text/html",
79
+ "text": "<h1>Hello MCP</h1>",
80
+ "blob": null,
81
+ "_meta": null
82
+ }
83
+ }
84
+ \`\`\`
85
+
86
+ #### External URL (iframe)
87
+
88
+ \`\`\`python
89
+ from mcp_ui import ExternalUrlContent, CreateUIResourceOptions, create_ui_resource
90
+
91
+ options = CreateUIResourceOptions(
92
+ uri="ui://demo/frame",
93
+ content=ExternalUrlContent(type="externalUrl", iframeUrl="https://example.com"),
94
+ encoding="text"
95
+ )
96
+
97
+ iframe_res = create_ui_resource(options)
98
+ \`\`\`
99
+
100
+ **Output:**
101
+
102
+ \`\`\`json
103
+ {
104
+ "type": "resource",
105
+ "resource": {
106
+ "uri": "ui://demo/frame",
107
+ "mimeType": "text/uri-list",
108
+ "text": "https://example.com",
109
+ "blob": null,
110
+ "_meta": null
111
+ }
112
+ }
113
+ \`\`\`
114
+
115
+ #### Remote DOM (React)
116
+
117
+ \`\`\`python
118
+ from mcp_ui import RemoteDomContent, CreateUIResourceOptions, create_ui_resource
119
+
120
+ options = CreateUIResourceOptions(
121
+ uri="ui://demo/react",
122
+ content=RemoteDomContent(type="remoteDom", script="console.log('Hello')", framework="react"),
123
+ encoding="blob"
124
+ )
125
+
126
+ remote_res = create_ui_resource(options)
127
+ \`\`\`
128
+
129
+ **Output (blob is Base64-encoded):**
130
+
131
+ \`\`\`json
132
+ {
133
+ "type": "resource",
134
+ "resource": {
135
+ "uri": "ui://demo/react",
136
+ "mimeType": "application/vnd.mcp-ui.remote-dom+javascript; framework=react",
137
+ "blob": "Y29uc29sZS5sb2coJ0hlbGxvJyk=",
138
+ "text": null,
139
+ "_meta": null
140
+ }
141
+ }
142
+ \`\`\`
143
+
144
+ ---
145
+
146
+ ### 2. Adding Metadata
147
+
148
+ You can attach metadata to resources. Keys are automatically prefixed with \`mcpui.dev/ui-\`.
149
+
150
+ \`\`\`python
151
+ options = CreateUIResourceOptions(
152
+ uri="ui://demo/meta",
153
+ content=RawHtmlContent(type="rawHtml", htmlString="<p>Meta Example</p>"),
154
+ encoding="text",
155
+ uiMetadata={"PREFERRED_FRAME_SIZE": {"width": 500, "height": 300}}
156
+ )
157
+
158
+ meta_res = create_ui_resource(options)
159
+ \`\`\`
160
+
161
+ **Output includes \`_meta\`:**
162
+
163
+ \`\`\`json
164
+ {
165
+ "type": "resource",
166
+ "resource": {
167
+ "uri": "ui://demo/meta",
168
+ "mimeType": "text/html",
169
+ "text": "<p>Meta Example</p>",
170
+ "blob": null,
171
+ "_meta": {
172
+ "mcpui.dev/ui-preferred-frame-size": { "width": 500, "height": 300 }
173
+ }
174
+ }
175
+ }
176
+ \`\`\`
177
+
178
+ ---
179
+
180
+ ### 3. UI Action Results
181
+
182
+ #### Tool Call
183
+
184
+ \`\`\`python
185
+ from mcp_ui import ui_action_result_tool_call
186
+ action = ui_action_result_tool_call("searchTool", {"query": "MCP SDK"})
187
+ \`\`\`
188
+
189
+ **Output:**
190
+
191
+ \`\`\`json
192
+ {
193
+ "type": "tool",
194
+ "payload": {
195
+ "toolName": "searchTool",
196
+ "params": { "query": "MCP SDK" }
197
+ }
198
+ }
199
+ \`\`\`
200
+
201
+ #### Prompt
202
+
203
+ \`\`\`python
204
+ from mcp_ui import ui_action_result_prompt
205
+ action = ui_action_result_prompt("Please confirm your choice")
206
+ \`\`\`
207
+
208
+ **Output:**
209
+
210
+ \`\`\`json
211
+ {
212
+ "type": "prompt",
213
+ "payload": { "prompt": "Please confirm your choice" }
214
+ }
215
+ \`\`\`
216
+
217
+ #### Link
218
+
219
+ \`\`\`python
220
+ from mcp_ui import ui_action_result_link
221
+ action = ui_action_result_link("https://example.com")
222
+ \`\`\`
223
+
224
+ **Output:**
225
+
226
+ \`\`\`json
227
+ {
228
+ "type": "link",
229
+ "payload": { "url": "https://example.com" }
230
+ }
231
+ \`\`\`
232
+
233
+ #### Intent
234
+
235
+ \`\`\`python
236
+ from mcp_ui import ui_action_result_intent
237
+ action = ui_action_result_intent("share", {"platform": "twitter"})
238
+ \`\`\`
239
+
240
+ **Output:**
241
+
242
+ \`\`\`json
243
+ {
244
+ "type": "intent",
245
+ "payload": {
246
+ "intent": "share",
247
+ "params": { "platform": "twitter" }
248
+ }
249
+ }
250
+ \`\`\`
251
+
252
+ #### Notification
253
+
254
+ \`\`\`python
255
+ from mcp_ui import ui_action_result_notification
256
+ action = ui_action_result_notification("Saved successfully!")
257
+ \`\`\`
258
+
259
+ **Output:**
260
+
261
+ \`\`\`json
262
+ {
263
+ "type": "notify",
264
+ "payload": { "message": "Saved successfully!" }
265
+ }
266
+ \`\`\`
267
+
268
+ ---
269
+
270
+ ## 📖 API Reference
271
+
272
+ ### create_ui_resource(options: CreateUIResourceOptions) → Dict[str, Any]
273
+ Creates a UI resource for MCP. Returns a JSON-serializable dict.
274
+
275
+ **Parameters:**
276
+ - \`uri\`: must start with \`ui://\`
277
+ - \`content\`: one of \`RawHtmlContent\`, \`ExternalUrlContent\`, \`RemoteDomContent\`
278
+ - \`encoding\`: \`"text"\` or \`"blob"\`
279
+ - \`uiMetadata\`: UI-specific metadata (auto-prefixed)
280
+ - \`metadata\`: General metadata
281
+ - \`resourceProps\`: Extra resource fields
282
+
283
+ **Type System:**
284
+ - **Content payloads**:
285
+ - RawHtmlContent(htmlString)
286
+ - ExternalUrlContent(iframeUrl)
287
+ - RemoteDomContent(script, framework)
288
+ - **Resource encodings**:
289
+ - HTMLTextContent (text string)
290
+ - Base64BlobContent (blob string, base64)
291
+ - **UI Action Results**:
292
+ - tool, prompt, link, intent, notify
293
+
294
+ ---
295
+
296
+ ## ⚙️ Notes
297
+
298
+ - Internally uses dataclasses for type safety, but always returns dicts (via \`asdict()\`) for MCP compatibility.
299
+ - Enforces URI format (\`ui://\` prefix).
300
+ - Auto-encodes blob resources in Base64.
301
+
302
+ ---
303
+
304
+ ## 📄 License
305
+
306
+ MIT – same as the original MCP-UI SDK.
mcp_ui-0.1.0/README.md ADDED
@@ -0,0 +1,282 @@
1
+
2
+ # MCP-UI Python SDK
3
+
4
+ This library is a Python port of the MCP-UI TypeScript SDK.
5
+ It provides strongly typed helpers for creating UI resources and UI actions in MCP servers, with good DX (developer experience), type safety, and MCP-compatible JSON output.
6
+
7
+ ---
8
+
9
+ ## 📦 Installation
10
+
11
+ \`\`\`bash
12
+ pip install mcp-ui
13
+ \`\`\`
14
+
15
+ ---
16
+
17
+ ## 🚀 Core Concepts
18
+
19
+ ### What is a UI Resource?
20
+ A **UI resource** is a unit of UI data (e.g., an HTML snippet, iframe, or Remote DOM script) that MCP clients can render.
21
+ This SDK helps you create them consistently with correct metadata and encodings.
22
+
23
+ ### What is a UI Action?
24
+ A **UI action result** represents an action the MCP client should take (e.g., open a link, show a prompt, call a tool).
25
+
26
+ ---
27
+
28
+ ## 🔧 Usage
29
+
30
+ ### 1. Creating a UI Resource
31
+
32
+ #### Raw HTML
33
+
34
+ \`\`\`python
35
+ from mcp_ui import RawHtmlContent, CreateUIResourceOptions, create_ui_resource
36
+
37
+ options = CreateUIResourceOptions(
38
+ uri="ui://demo/html",
39
+ content=RawHtmlContent(type="rawHtml", htmlString="<h1>Hello MCP</h1>"),
40
+ encoding="text"
41
+ )
42
+
43
+ resource = create_ui_resource(options)
44
+ print(resource)
45
+ \`\`\`
46
+
47
+ **Output:**
48
+
49
+ \`\`\`json
50
+ {
51
+ "type": "resource",
52
+ "resource": {
53
+ "uri": "ui://demo/html",
54
+ "mimeType": "text/html",
55
+ "text": "<h1>Hello MCP</h1>",
56
+ "blob": null,
57
+ "_meta": null
58
+ }
59
+ }
60
+ \`\`\`
61
+
62
+ #### External URL (iframe)
63
+
64
+ \`\`\`python
65
+ from mcp_ui import ExternalUrlContent, CreateUIResourceOptions, create_ui_resource
66
+
67
+ options = CreateUIResourceOptions(
68
+ uri="ui://demo/frame",
69
+ content=ExternalUrlContent(type="externalUrl", iframeUrl="https://example.com"),
70
+ encoding="text"
71
+ )
72
+
73
+ iframe_res = create_ui_resource(options)
74
+ \`\`\`
75
+
76
+ **Output:**
77
+
78
+ \`\`\`json
79
+ {
80
+ "type": "resource",
81
+ "resource": {
82
+ "uri": "ui://demo/frame",
83
+ "mimeType": "text/uri-list",
84
+ "text": "https://example.com",
85
+ "blob": null,
86
+ "_meta": null
87
+ }
88
+ }
89
+ \`\`\`
90
+
91
+ #### Remote DOM (React)
92
+
93
+ \`\`\`python
94
+ from mcp_ui import RemoteDomContent, CreateUIResourceOptions, create_ui_resource
95
+
96
+ options = CreateUIResourceOptions(
97
+ uri="ui://demo/react",
98
+ content=RemoteDomContent(type="remoteDom", script="console.log('Hello')", framework="react"),
99
+ encoding="blob"
100
+ )
101
+
102
+ remote_res = create_ui_resource(options)
103
+ \`\`\`
104
+
105
+ **Output (blob is Base64-encoded):**
106
+
107
+ \`\`\`json
108
+ {
109
+ "type": "resource",
110
+ "resource": {
111
+ "uri": "ui://demo/react",
112
+ "mimeType": "application/vnd.mcp-ui.remote-dom+javascript; framework=react",
113
+ "blob": "Y29uc29sZS5sb2coJ0hlbGxvJyk=",
114
+ "text": null,
115
+ "_meta": null
116
+ }
117
+ }
118
+ \`\`\`
119
+
120
+ ---
121
+
122
+ ### 2. Adding Metadata
123
+
124
+ You can attach metadata to resources. Keys are automatically prefixed with \`mcpui.dev/ui-\`.
125
+
126
+ \`\`\`python
127
+ options = CreateUIResourceOptions(
128
+ uri="ui://demo/meta",
129
+ content=RawHtmlContent(type="rawHtml", htmlString="<p>Meta Example</p>"),
130
+ encoding="text",
131
+ uiMetadata={"PREFERRED_FRAME_SIZE": {"width": 500, "height": 300}}
132
+ )
133
+
134
+ meta_res = create_ui_resource(options)
135
+ \`\`\`
136
+
137
+ **Output includes \`_meta\`:**
138
+
139
+ \`\`\`json
140
+ {
141
+ "type": "resource",
142
+ "resource": {
143
+ "uri": "ui://demo/meta",
144
+ "mimeType": "text/html",
145
+ "text": "<p>Meta Example</p>",
146
+ "blob": null,
147
+ "_meta": {
148
+ "mcpui.dev/ui-preferred-frame-size": { "width": 500, "height": 300 }
149
+ }
150
+ }
151
+ }
152
+ \`\`\`
153
+
154
+ ---
155
+
156
+ ### 3. UI Action Results
157
+
158
+ #### Tool Call
159
+
160
+ \`\`\`python
161
+ from mcp_ui import ui_action_result_tool_call
162
+ action = ui_action_result_tool_call("searchTool", {"query": "MCP SDK"})
163
+ \`\`\`
164
+
165
+ **Output:**
166
+
167
+ \`\`\`json
168
+ {
169
+ "type": "tool",
170
+ "payload": {
171
+ "toolName": "searchTool",
172
+ "params": { "query": "MCP SDK" }
173
+ }
174
+ }
175
+ \`\`\`
176
+
177
+ #### Prompt
178
+
179
+ \`\`\`python
180
+ from mcp_ui import ui_action_result_prompt
181
+ action = ui_action_result_prompt("Please confirm your choice")
182
+ \`\`\`
183
+
184
+ **Output:**
185
+
186
+ \`\`\`json
187
+ {
188
+ "type": "prompt",
189
+ "payload": { "prompt": "Please confirm your choice" }
190
+ }
191
+ \`\`\`
192
+
193
+ #### Link
194
+
195
+ \`\`\`python
196
+ from mcp_ui import ui_action_result_link
197
+ action = ui_action_result_link("https://example.com")
198
+ \`\`\`
199
+
200
+ **Output:**
201
+
202
+ \`\`\`json
203
+ {
204
+ "type": "link",
205
+ "payload": { "url": "https://example.com" }
206
+ }
207
+ \`\`\`
208
+
209
+ #### Intent
210
+
211
+ \`\`\`python
212
+ from mcp_ui import ui_action_result_intent
213
+ action = ui_action_result_intent("share", {"platform": "twitter"})
214
+ \`\`\`
215
+
216
+ **Output:**
217
+
218
+ \`\`\`json
219
+ {
220
+ "type": "intent",
221
+ "payload": {
222
+ "intent": "share",
223
+ "params": { "platform": "twitter" }
224
+ }
225
+ }
226
+ \`\`\`
227
+
228
+ #### Notification
229
+
230
+ \`\`\`python
231
+ from mcp_ui import ui_action_result_notification
232
+ action = ui_action_result_notification("Saved successfully!")
233
+ \`\`\`
234
+
235
+ **Output:**
236
+
237
+ \`\`\`json
238
+ {
239
+ "type": "notify",
240
+ "payload": { "message": "Saved successfully!" }
241
+ }
242
+ \`\`\`
243
+
244
+ ---
245
+
246
+ ## 📖 API Reference
247
+
248
+ ### create_ui_resource(options: CreateUIResourceOptions) → Dict[str, Any]
249
+ Creates a UI resource for MCP. Returns a JSON-serializable dict.
250
+
251
+ **Parameters:**
252
+ - \`uri\`: must start with \`ui://\`
253
+ - \`content\`: one of \`RawHtmlContent\`, \`ExternalUrlContent\`, \`RemoteDomContent\`
254
+ - \`encoding\`: \`"text"\` or \`"blob"\`
255
+ - \`uiMetadata\`: UI-specific metadata (auto-prefixed)
256
+ - \`metadata\`: General metadata
257
+ - \`resourceProps\`: Extra resource fields
258
+
259
+ **Type System:**
260
+ - **Content payloads**:
261
+ - RawHtmlContent(htmlString)
262
+ - ExternalUrlContent(iframeUrl)
263
+ - RemoteDomContent(script, framework)
264
+ - **Resource encodings**:
265
+ - HTMLTextContent (text string)
266
+ - Base64BlobContent (blob string, base64)
267
+ - **UI Action Results**:
268
+ - tool, prompt, link, intent, notify
269
+
270
+ ---
271
+
272
+ ## ⚙️ Notes
273
+
274
+ - Internally uses dataclasses for type safety, but always returns dicts (via \`asdict()\`) for MCP compatibility.
275
+ - Enforces URI format (\`ui://\` prefix).
276
+ - Auto-encodes blob resources in Base64.
277
+
278
+ ---
279
+
280
+ ## 📄 License
281
+
282
+ MIT – same as the original MCP-UI SDK.
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "mcp-ui"
3
+ version = "0.1.0"
4
+ description = "A Python SDK for building MCP UI resources (iframe, panels, text blocks, etc.) in a type-safe way."
5
+ readme = "README.md"
6
+ license = { text = "MIT" }
7
+ authors = [{ name = "James Zokah", email = "jameszokah@gmail.com" }]
8
+ requires-python = ">=3.9"
9
+ keywords = ["mcp", "ui", "sdk", "python", "iframe", "chat", "agents"]
10
+
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.8",
15
+ "Programming Language :: Python :: 3.9",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Operating System :: OS Independent",
21
+ ]
22
+
23
+ [tool.uv]
24
+ dev-dependencies = ["pytest"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/jameszokah/mcp-ui"
28
+ Repository = "https://github.com/jameszokah/mcp-ui"
29
+ Issues = "https://github.com/jameszokah/mcp-ui/issues"
30
+ Documentation = "https://github.com/jameszokah/mcp-ui#readme"
31
+
32
+ [build-system]
33
+ requires = ["hatchling"]
34
+ build-backend = "hatchling.build"
35
+
36
+ # ✅ Tell Hatchling to include the package inside `src/mcp_ui`
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/mcp_ui"]
39
+
40
+
41
+ [tool.pyright]
42
+ include = ["src"]
43
+ extraPaths = ["src"]
@@ -0,0 +1,9 @@
1
+ from importlib.metadata import version, PackageNotFoundError
2
+
3
+ try:
4
+ __version__ = version("mcp-ui")
5
+ except PackageNotFoundError:
6
+ # fallback for local dev without install
7
+ __version__ = "0.0.0"
8
+
9
+ from .core import *
@@ -0,0 +1,234 @@
1
+
2
+
3
+ from __future__ import annotations
4
+ from dataclasses import dataclass, field, asdict
5
+ from typing import Any, Dict, Literal, Optional, Union
6
+ import base64
7
+
8
+ # --------------------------
9
+ # Types & Constants
10
+ # --------------------------
11
+
12
+ URI = str # Must start with "ui://"
13
+
14
+ MimeType = Literal[
15
+ "text/html",
16
+ "text/uri-list",
17
+ "application/vnd.mcp-ui.remote-dom+javascript; framework=react",
18
+ "application/vnd.mcp-ui.remote-dom+javascript; framework=webcomponents",
19
+ ]
20
+
21
+ UIMetadataKey = {
22
+ "PREFERRED_FRAME_SIZE": "preferred-frame-size",
23
+ "INITIAL_RENDER_DATA": "initial-render-data",
24
+ }
25
+
26
+ UI_METADATA_PREFIX = "mcpui.dev/ui-"
27
+
28
+ InternalMessageType = {
29
+ "UI_MESSAGE_RECEIVED": "ui-message-received",
30
+ "UI_MESSAGE_RESPONSE": "ui-message-response",
31
+ "UI_SIZE_CHANGE": "ui-size-change",
32
+ "UI_LIFECYCLE_IFRAME_READY": "ui-lifecycle-iframe-ready",
33
+ "UI_LIFECYCLE_IFRAME_RENDER_DATA": "ui-lifecycle-iframe-render-data",
34
+ }
35
+
36
+ ReservedUrlParams = {
37
+ "WAIT_FOR_RENDER_DATA": "waitForRenderData",
38
+ }
39
+
40
+
41
+ # --------------------------
42
+ # Resource Content Payloads
43
+ # --------------------------
44
+
45
+ @dataclass
46
+ class RawHtmlContent:
47
+ type: Literal["rawHtml"]
48
+ htmlString: str
49
+
50
+
51
+ @dataclass
52
+ class ExternalUrlContent:
53
+ type: Literal["externalUrl"]
54
+ iframeUrl: str
55
+
56
+
57
+ @dataclass
58
+ class RemoteDomContent:
59
+ type: Literal["remoteDom"]
60
+ script: str
61
+ framework: Literal["react", "webcomponents"]
62
+
63
+
64
+ ResourceContentPayload = Union[RawHtmlContent, ExternalUrlContent, RemoteDomContent]
65
+
66
+
67
+ # --------------------------
68
+ # Resource Representations
69
+ # --------------------------
70
+
71
+ @dataclass
72
+ class HTMLTextContent:
73
+ uri: URI
74
+ mimeType: MimeType
75
+ text: str
76
+ blob: Optional[str] = None
77
+ _meta: Optional[Dict[str, Any]] = None
78
+
79
+
80
+ @dataclass
81
+ class Base64BlobContent:
82
+ uri: URI
83
+ mimeType: MimeType
84
+ blob: str
85
+ text: Optional[str] = None
86
+ _meta: Optional[Dict[str, Any]] = None
87
+
88
+
89
+ UIResource = Dict[str, Union[str, HTMLTextContent, Base64BlobContent]]
90
+
91
+
92
+ @dataclass
93
+ class CreateUIResourceOptions:
94
+ uri: URI
95
+ content: ResourceContentPayload
96
+ encoding: Literal["text", "blob"]
97
+ uiMetadata: Optional[Dict[str, Any]] = None
98
+ metadata: Optional[Dict[str, Any]] = None
99
+ resourceProps: Optional[Dict[str, Any]] = None
100
+
101
+
102
+ # --------------------------
103
+ # Utils
104
+ # --------------------------
105
+
106
+ def utf8_to_base64(s: str) -> str:
107
+ return base64.b64encode(s.encode("utf-8")).decode("utf-8")
108
+
109
+
110
+ def get_additional_resource_props(options: CreateUIResourceOptions) -> Dict[str, Any]:
111
+ props = dict(options.resourceProps or {})
112
+
113
+ if options.uiMetadata or options.metadata:
114
+ ui_prefixed_metadata = {
115
+ f"{UI_METADATA_PREFIX}{k}": v for k, v in (options.uiMetadata or {}).items()
116
+ }
117
+ props["_meta"] = {
118
+ **ui_prefixed_metadata,
119
+ **(options.metadata or {}),
120
+ **props.get("_meta", {}),
121
+ }
122
+
123
+ return props
124
+
125
+
126
+ # --------------------------
127
+ # Resource Factory
128
+ # --------------------------
129
+
130
+ def create_ui_resource(options: CreateUIResourceOptions) -> Dict[str, Any]:
131
+ if not options.uri.startswith("ui://"):
132
+ raise ValueError("MCP-UI SDK: URI must start with 'ui://'.")
133
+
134
+ if isinstance(options.content, RawHtmlContent):
135
+ actual_content = options.content.htmlString
136
+ mime_type: MimeType = "text/html"
137
+
138
+ elif isinstance(options.content, ExternalUrlContent):
139
+ actual_content = options.content.iframeUrl
140
+ mime_type = "text/uri-list"
141
+
142
+ elif isinstance(options.content, RemoteDomContent):
143
+ actual_content = options.content.script
144
+ mime_type = (
145
+ f"application/vnd.mcp-ui.remote-dom+javascript; framework={options.content.framework}" # type: ignore
146
+ )
147
+
148
+ else:
149
+ raise ValueError(f"MCP-UI SDK: Invalid content.type: {options.content}")
150
+
151
+ if options.encoding == "text":
152
+ resource = HTMLTextContent(
153
+ uri=options.uri,
154
+ mimeType=mime_type,
155
+ text=actual_content,
156
+ **get_additional_resource_props(options),
157
+ )
158
+ elif options.encoding == "blob":
159
+ resource = Base64BlobContent(
160
+ uri=options.uri,
161
+ mimeType=mime_type,
162
+ blob=utf8_to_base64(actual_content),
163
+ **get_additional_resource_props(options),
164
+ )
165
+ else:
166
+ raise ValueError(f"MCP-UI SDK: Invalid encoding type: {options.encoding}")
167
+
168
+ # ✅ return a dict so MCP can consume it
169
+ return {
170
+ "type": "resource",
171
+ "resource": asdict(resource),
172
+ }
173
+
174
+ # --------------------------
175
+ # UI Action Results
176
+ # --------------------------
177
+
178
+ @dataclass
179
+ class UIActionResultToolCall:
180
+ type: Literal["tool"] = "tool"
181
+ payload: Dict[str, Any] = field(default_factory=dict)
182
+
183
+
184
+ @dataclass
185
+ class UIActionResultPrompt:
186
+ type: Literal["prompt"] = "prompt"
187
+ payload: Dict[str, str] = field(default_factory=dict)
188
+
189
+
190
+ @dataclass
191
+ class UIActionResultLink:
192
+ type: Literal["link"] = "link"
193
+ payload: Dict[str, str] = field(default_factory=dict)
194
+
195
+
196
+ @dataclass
197
+ class UIActionResultIntent:
198
+ type: Literal["intent"] = "intent"
199
+ payload: Dict[str, Any] = field(default_factory=dict)
200
+
201
+
202
+ @dataclass
203
+ class UIActionResultNotification:
204
+ type: Literal["notify"] = "notify"
205
+ payload: Dict[str, str] = field(default_factory=dict)
206
+
207
+
208
+ UIActionResult = Union[
209
+ UIActionResultToolCall,
210
+ UIActionResultPrompt,
211
+ UIActionResultLink,
212
+ UIActionResultIntent,
213
+ UIActionResultNotification,
214
+ ]
215
+
216
+
217
+ def ui_action_result_tool_call(tool_name: str, params: Dict[str, Any]) -> UIActionResultToolCall:
218
+ return UIActionResultToolCall(payload={"toolName": tool_name, "params": params})
219
+
220
+
221
+ def ui_action_result_prompt(prompt: str) -> UIActionResultPrompt:
222
+ return UIActionResultPrompt(payload={"prompt": prompt})
223
+
224
+
225
+ def ui_action_result_link(url: str) -> UIActionResultLink:
226
+ return UIActionResultLink(payload={"url": url})
227
+
228
+
229
+ def ui_action_result_intent(intent: str, params: Dict[str, Any]) -> UIActionResultIntent:
230
+ return UIActionResultIntent(payload={"intent": intent, "params": params})
231
+
232
+
233
+ def ui_action_result_notification(message: str) -> UIActionResultNotification:
234
+ return UIActionResultNotification(payload={"message": message})
@@ -0,0 +1,234 @@
1
+
2
+
3
+ from __future__ import annotations
4
+ from dataclasses import dataclass, field, asdict
5
+ from typing import Any, Dict, Literal, Optional, Union
6
+ import base64
7
+
8
+ # --------------------------
9
+ # Types & Constants
10
+ # --------------------------
11
+
12
+ URI = str # Must start with "ui://"
13
+
14
+ MimeType = Literal[
15
+ "text/html",
16
+ "text/uri-list",
17
+ "application/vnd.mcp-ui.remote-dom+javascript; framework=react",
18
+ "application/vnd.mcp-ui.remote-dom+javascript; framework=webcomponents",
19
+ ]
20
+
21
+ UIMetadataKey = {
22
+ "PREFERRED_FRAME_SIZE": "preferred-frame-size",
23
+ "INITIAL_RENDER_DATA": "initial-render-data",
24
+ }
25
+
26
+ UI_METADATA_PREFIX = "mcpui.dev/ui-"
27
+
28
+ InternalMessageType = {
29
+ "UI_MESSAGE_RECEIVED": "ui-message-received",
30
+ "UI_MESSAGE_RESPONSE": "ui-message-response",
31
+ "UI_SIZE_CHANGE": "ui-size-change",
32
+ "UI_LIFECYCLE_IFRAME_READY": "ui-lifecycle-iframe-ready",
33
+ "UI_LIFECYCLE_IFRAME_RENDER_DATA": "ui-lifecycle-iframe-render-data",
34
+ }
35
+
36
+ ReservedUrlParams = {
37
+ "WAIT_FOR_RENDER_DATA": "waitForRenderData",
38
+ }
39
+
40
+
41
+ # --------------------------
42
+ # Resource Content Payloads
43
+ # --------------------------
44
+
45
+ @dataclass
46
+ class RawHtmlContent:
47
+ type: Literal["rawHtml"]
48
+ htmlString: str
49
+
50
+
51
+ @dataclass
52
+ class ExternalUrlContent:
53
+ type: Literal["externalUrl"]
54
+ iframeUrl: str
55
+
56
+
57
+ @dataclass
58
+ class RemoteDomContent:
59
+ type: Literal["remoteDom"]
60
+ script: str
61
+ framework: Literal["react", "webcomponents"]
62
+
63
+
64
+ ResourceContentPayload = Union[RawHtmlContent, ExternalUrlContent, RemoteDomContent]
65
+
66
+
67
+ # --------------------------
68
+ # Resource Representations
69
+ # --------------------------
70
+
71
+ @dataclass
72
+ class HTMLTextContent:
73
+ uri: URI
74
+ mimeType: MimeType
75
+ text: str
76
+ blob: Optional[str] = None
77
+ _meta: Optional[Dict[str, Any]] = None
78
+
79
+
80
+ @dataclass
81
+ class Base64BlobContent:
82
+ uri: URI
83
+ mimeType: MimeType
84
+ blob: str
85
+ text: Optional[str] = None
86
+ _meta: Optional[Dict[str, Any]] = None
87
+
88
+
89
+ UIResource = Dict[str, Union[str, HTMLTextContent, Base64BlobContent]]
90
+
91
+
92
+ @dataclass
93
+ class CreateUIResourceOptions:
94
+ uri: URI
95
+ content: ResourceContentPayload
96
+ encoding: Literal["text", "blob"]
97
+ uiMetadata: Optional[Dict[str, Any]] = None
98
+ metadata: Optional[Dict[str, Any]] = None
99
+ resourceProps: Optional[Dict[str, Any]] = None
100
+
101
+
102
+ # --------------------------
103
+ # Utils
104
+ # --------------------------
105
+
106
+ def utf8_to_base64(s: str) -> str:
107
+ return base64.b64encode(s.encode("utf-8")).decode("utf-8")
108
+
109
+
110
+ def get_additional_resource_props(options: CreateUIResourceOptions) -> Dict[str, Any]:
111
+ props = dict(options.resourceProps or {})
112
+
113
+ if options.uiMetadata or options.metadata:
114
+ ui_prefixed_metadata = {
115
+ f"{UI_METADATA_PREFIX}{k}": v for k, v in (options.uiMetadata or {}).items()
116
+ }
117
+ props["_meta"] = {
118
+ **ui_prefixed_metadata,
119
+ **(options.metadata or {}),
120
+ **props.get("_meta", {}),
121
+ }
122
+
123
+ return props
124
+
125
+
126
+ # --------------------------
127
+ # Resource Factory
128
+ # --------------------------
129
+
130
+ def create_ui_resource(options: CreateUIResourceOptions) -> Dict[str, Any]:
131
+ if not options.uri.startswith("ui://"):
132
+ raise ValueError("MCP-UI SDK: URI must start with 'ui://'.")
133
+
134
+ if isinstance(options.content, RawHtmlContent):
135
+ actual_content = options.content.htmlString
136
+ mime_type: MimeType = "text/html"
137
+
138
+ elif isinstance(options.content, ExternalUrlContent):
139
+ actual_content = options.content.iframeUrl
140
+ mime_type = "text/uri-list"
141
+
142
+ elif isinstance(options.content, RemoteDomContent):
143
+ actual_content = options.content.script
144
+ mime_type = (
145
+ f"application/vnd.mcp-ui.remote-dom+javascript; framework={options.content.framework}" # type: ignore
146
+ )
147
+
148
+ else:
149
+ raise ValueError(f"MCP-UI SDK: Invalid content.type: {options.content}")
150
+
151
+ if options.encoding == "text":
152
+ resource = HTMLTextContent(
153
+ uri=options.uri,
154
+ mimeType=mime_type,
155
+ text=actual_content,
156
+ **get_additional_resource_props(options),
157
+ )
158
+ elif options.encoding == "blob":
159
+ resource = Base64BlobContent(
160
+ uri=options.uri,
161
+ mimeType=mime_type,
162
+ blob=utf8_to_base64(actual_content),
163
+ **get_additional_resource_props(options),
164
+ )
165
+ else:
166
+ raise ValueError(f"MCP-UI SDK: Invalid encoding type: {options.encoding}")
167
+
168
+ # ✅ return a dict so MCP can consume it
169
+ return {
170
+ "type": "resource",
171
+ "resource": asdict(resource),
172
+ }
173
+
174
+ # --------------------------
175
+ # UI Action Results
176
+ # --------------------------
177
+
178
+ @dataclass
179
+ class UIActionResultToolCall:
180
+ type: Literal["tool"] = "tool"
181
+ payload: Dict[str, Any] = field(default_factory=dict)
182
+
183
+
184
+ @dataclass
185
+ class UIActionResultPrompt:
186
+ type: Literal["prompt"] = "prompt"
187
+ payload: Dict[str, str] = field(default_factory=dict)
188
+
189
+
190
+ @dataclass
191
+ class UIActionResultLink:
192
+ type: Literal["link"] = "link"
193
+ payload: Dict[str, str] = field(default_factory=dict)
194
+
195
+
196
+ @dataclass
197
+ class UIActionResultIntent:
198
+ type: Literal["intent"] = "intent"
199
+ payload: Dict[str, Any] = field(default_factory=dict)
200
+
201
+
202
+ @dataclass
203
+ class UIActionResultNotification:
204
+ type: Literal["notify"] = "notify"
205
+ payload: Dict[str, str] = field(default_factory=dict)
206
+
207
+
208
+ UIActionResult = Union[
209
+ UIActionResultToolCall,
210
+ UIActionResultPrompt,
211
+ UIActionResultLink,
212
+ UIActionResultIntent,
213
+ UIActionResultNotification,
214
+ ]
215
+
216
+
217
+ def ui_action_result_tool_call(tool_name: str, params: Dict[str, Any]) -> UIActionResultToolCall:
218
+ return UIActionResultToolCall(payload={"toolName": tool_name, "params": params})
219
+
220
+
221
+ def ui_action_result_prompt(prompt: str) -> UIActionResultPrompt:
222
+ return UIActionResultPrompt(payload={"prompt": prompt})
223
+
224
+
225
+ def ui_action_result_link(url: str) -> UIActionResultLink:
226
+ return UIActionResultLink(payload={"url": url})
227
+
228
+
229
+ def ui_action_result_intent(intent: str, params: Dict[str, Any]) -> UIActionResultIntent:
230
+ return UIActionResultIntent(payload={"intent": intent, "params": params})
231
+
232
+
233
+ def ui_action_result_notification(message: str) -> UIActionResultNotification:
234
+ return UIActionResultNotification(payload={"message": message})
@@ -0,0 +1,72 @@
1
+
2
+ import pytest
3
+
4
+ from mcp_ui import (
5
+ create_ui_resource,
6
+ RawHtmlContent,
7
+ ExternalUrlContent,
8
+ RemoteDomContent,
9
+ ui_action_result_tool_call,
10
+ ui_action_result_prompt,
11
+ ui_action_result_link,
12
+ ui_action_result_intent,
13
+ ui_action_result_notification,
14
+ CreateUIResourceOptions,
15
+ )
16
+
17
+
18
+ def test_create_ui_resource_with_html():
19
+ options = CreateUIResourceOptions(
20
+ uri="ui://test-html",
21
+ content=RawHtmlContent(type="rawHtml", htmlString="<h1>Hello</h1>"),
22
+ encoding="text",
23
+ )
24
+ resource = create_ui_resource(options)
25
+
26
+ assert resource["type"] == "resource"
27
+ assert resource["resource"]["mimeType"] == "text/html"
28
+ assert resource["resource"]["text"] == "<h1>Hello</h1>"
29
+
30
+
31
+ def test_create_ui_resource_with_external_url():
32
+ options = CreateUIResourceOptions(
33
+ uri="ui://test-url",
34
+ content=ExternalUrlContent(type="externalUrl", iframeUrl="https://example.com"),
35
+ encoding="text",
36
+ )
37
+ resource = create_ui_resource(options)
38
+
39
+ assert resource["resource"]["mimeType"] == "text/uri-list"
40
+ assert resource["resource"]["text"] == "https://example.com"
41
+
42
+
43
+ def test_create_ui_resource_with_remote_dom_blob():
44
+ options = CreateUIResourceOptions(
45
+ uri="ui://test-remote",
46
+ content=RemoteDomContent(type="remoteDom", script="console.log('hi')", framework="react"),
47
+ encoding="blob",
48
+ )
49
+ resource = create_ui_resource(options)
50
+
51
+ assert resource["resource"]["mimeType"].startswith(
52
+ "application/vnd.mcp-ui.remote-dom+javascript; framework=react"
53
+ )
54
+ assert "blob" in resource["resource"]
55
+
56
+
57
+ def test_ui_action_results():
58
+ tool_call = ui_action_result_tool_call("myTool", {"param": 1})
59
+ assert tool_call.payload["toolName"] == "myTool"
60
+
61
+ prompt = ui_action_result_prompt("Enter value")
62
+ assert prompt.payload["prompt"] == "Enter value"
63
+
64
+ link = ui_action_result_link("https://example.com")
65
+ assert link.payload["url"] == "https://example.com"
66
+
67
+ intent = ui_action_result_intent("open", {"id": 123})
68
+ assert intent.payload["intent"] == "open"
69
+ assert intent.payload["params"]["id"] == 123
70
+
71
+ notification = ui_action_result_notification("Done!")
72
+ assert notification.payload["message"] == "Done!"
mcp_ui-0.1.0/uv.lock ADDED
@@ -0,0 +1,8 @@
1
+ version = 1
2
+ revision = 1
3
+ requires-python = ">=3.8"
4
+
5
+ [[package]]
6
+ name = "mcp-ui"
7
+ version = "0.1.0"
8
+ source = { editable = "." }