@json-render/mcp 0.11.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Vercel Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # @json-render/mcp
2
+
3
+ MCP Apps integration for [json-render](https://github.com/vercel-labs/json-render). Serve json-render UIs as interactive MCP Apps inside Claude, ChatGPT, Cursor, VS Code, and other MCP-capable clients.
4
+
5
+ ## What are MCP Apps?
6
+
7
+ [MCP Apps](https://modelcontextprotocol.io/docs/extensions/apps) is an extension to the Model Context Protocol that lets MCP servers return interactive HTML UIs rendered directly inside chat conversations. Instead of text-only tool responses, users get full interactive interfaces -- dashboards, forms, data visualizations -- embedded inline.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @json-render/mcp @json-render/core @modelcontextprotocol/sdk
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ### 1. Define your catalog
18
+
19
+ ```ts
20
+ import { defineCatalog } from "@json-render/core";
21
+ import { schema } from "@json-render/react/schema";
22
+ import { shadcnComponentDefinitions } from "@json-render/shadcn/catalog";
23
+
24
+ const catalog = defineCatalog(schema, {
25
+ components: { ...shadcnComponentDefinitions },
26
+ actions: {},
27
+ });
28
+ ```
29
+
30
+ ### 2. Create the MCP server
31
+
32
+ ```ts
33
+ import { createMcpApp } from "@json-render/mcp";
34
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
35
+ import fs from "node:fs";
36
+
37
+ const server = createMcpApp({
38
+ name: "My Dashboard",
39
+ version: "1.0.0",
40
+ catalog,
41
+ html: fs.readFileSync("dist/index.html", "utf-8"),
42
+ });
43
+
44
+ await server.connect(new StdioServerTransport());
45
+ ```
46
+
47
+ ### 3. Build the UI (iframe)
48
+
49
+ Create a React app that uses `useJsonRenderApp` from `@json-render/mcp/app`:
50
+
51
+ ```tsx
52
+ import { useJsonRenderApp } from "@json-render/mcp/app";
53
+ import { JSONUIProvider, Renderer } from "@json-render/react";
54
+
55
+ function McpAppView({ registry }) {
56
+ const { spec, loading, connected, error } = useJsonRenderApp();
57
+
58
+ if (error) return <div>Error: {error.message}</div>;
59
+ if (!spec) return <div>Waiting for spec...</div>;
60
+
61
+ return (
62
+ <JSONUIProvider registry={registry} initialState={spec.state ?? {}}>
63
+ <Renderer spec={spec} registry={registry} loading={loading} />
64
+ </JSONUIProvider>
65
+ );
66
+ }
67
+ ```
68
+
69
+ Bundle with Vite + `vite-plugin-singlefile` into a single HTML file, then pass it to `createMcpApp` as the `html` option.
70
+
71
+ ### 4. Connect to a client
72
+
73
+ Add to `.cursor/mcp.json` or Claude Desktop config:
74
+
75
+ ```json
76
+ {
77
+ "mcpServers": {
78
+ "my-app": {
79
+ "command": "node",
80
+ "args": ["./server.js", "--stdio"]
81
+ }
82
+ }
83
+ }
84
+ ```
85
+
86
+ ## API Reference
87
+
88
+ ### Server Side (main export)
89
+
90
+ #### `createMcpApp(options)`
91
+
92
+ Creates a fully-configured `McpServer` with a json-render tool and UI resource.
93
+
94
+ | Option | Type | Description |
95
+ |--------|------|-------------|
96
+ | `name` | `string` | Server name shown in client UIs |
97
+ | `version` | `string` | Server version |
98
+ | `catalog` | `Catalog` | json-render catalog defining available components |
99
+ | `html` | `string` | Bundled HTML for the iframe UI |
100
+ | `tool` | `McpToolOptions` | Optional tool name/title/description overrides |
101
+
102
+ #### `registerJsonRenderTool(server, options)`
103
+
104
+ Register a json-render tool on an existing `McpServer`.
105
+
106
+ #### `registerJsonRenderResource(server, options)`
107
+
108
+ Register a json-render UI resource on an existing `McpServer`.
109
+
110
+ ### Client Side (`@json-render/mcp/app`)
111
+
112
+ #### `useJsonRenderApp(options?)`
113
+
114
+ React hook for the iframe-side app. Connects to the MCP host, receives tool results, and maintains the current json-render spec.
115
+
116
+ Returns `{ spec, loading, connected, connecting, error, app, callServerTool }`.
117
+
118
+ #### `buildAppHtml(options)`
119
+
120
+ Generate a self-contained HTML string from bundled JS/CSS for use as a UI resource.
121
+
122
+ ## Client Support
123
+
124
+ MCP Apps are supported by Claude, ChatGPT, VS Code (Copilot), Cursor, Goose, and Postman.
package/dist/app.d.mts ADDED
@@ -0,0 +1,91 @@
1
+ import { Spec } from '@json-render/core';
2
+ import { App } from '@modelcontextprotocol/ext-apps';
3
+
4
+ /**
5
+ * Options for the `useJsonRenderApp` hook.
6
+ */
7
+ interface UseJsonRenderAppOptions {
8
+ /** App name shown during initialization. Defaults to `"json-render"`. */
9
+ name?: string;
10
+ /** App version. Defaults to `"1.0.0"`. */
11
+ version?: string;
12
+ }
13
+ /**
14
+ * Return value of `useJsonRenderApp`.
15
+ */
16
+ interface UseJsonRenderAppReturn {
17
+ /** The current json-render spec (null until the first tool result). */
18
+ spec: Spec | null;
19
+ /** Whether the app is still connecting to the host. */
20
+ connecting: boolean;
21
+ /** Whether the app is connected to the host. */
22
+ connected: boolean;
23
+ /** Connection error, if any. */
24
+ error: Error | null;
25
+ /** Whether the spec is still being received / parsed. */
26
+ loading: boolean;
27
+ /** The underlying MCP App instance. */
28
+ app: App | null;
29
+ /**
30
+ * Call a tool on the MCP server and update the spec from the result.
31
+ * Useful for refresh / drill-down interactions.
32
+ */
33
+ callServerTool: (name: string, args?: Record<string, unknown>) => Promise<void>;
34
+ }
35
+ /**
36
+ * React hook that connects to the MCP host, listens for tool results,
37
+ * and maintains the current json-render spec.
38
+ *
39
+ * Follows the official MCP Apps pattern: create an `App` instance,
40
+ * register the `ontoolresult` handler, then call `app.connect()`
41
+ * which internally creates a PostMessageTransport to the host.
42
+ */
43
+ declare function useJsonRenderApp(options?: UseJsonRenderAppOptions): UseJsonRenderAppReturn;
44
+
45
+ /**
46
+ * Options for `buildAppHtml`.
47
+ */
48
+ interface BuildAppHtmlOptions {
49
+ /** Title for the HTML page. Defaults to `"json-render"`. */
50
+ title?: string;
51
+ /**
52
+ * Inline CSS to inject into the page `<style>` tag.
53
+ * Use this to include Tailwind output or custom styles.
54
+ */
55
+ css?: string;
56
+ /**
57
+ * Bundled JavaScript for the app entry point.
58
+ * This should be the output of a bundler (Vite, esbuild, etc.)
59
+ * that bundles your React app, registry, and the
60
+ * `useJsonRenderApp` hook into a single script.
61
+ */
62
+ js: string;
63
+ /**
64
+ * Additional `<head>` content (meta tags, font links, etc.).
65
+ */
66
+ head?: string;
67
+ }
68
+ /**
69
+ * Build a self-contained HTML string for an MCP App UI resource.
70
+ *
71
+ * The resulting HTML is designed to be served as a `ui://` resource
72
+ * via `registerJsonRenderResource` or `createMcpApp`.
73
+ *
74
+ * Typically you'd use a bundler (Vite + `vite-plugin-singlefile`, or
75
+ * esbuild) to produce the `js` and `css` strings, then pass them here.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * import { buildAppHtml } from "@json-render/mcp/app";
80
+ * import { readFileSync } from "node:fs";
81
+ *
82
+ * const html = buildAppHtml({
83
+ * title: "Dashboard",
84
+ * js: readFileSync("dist/app.js", "utf-8"),
85
+ * css: readFileSync("dist/app.css", "utf-8"),
86
+ * });
87
+ * ```
88
+ */
89
+ declare function buildAppHtml(options: BuildAppHtmlOptions): string;
90
+
91
+ export { type BuildAppHtmlOptions, type UseJsonRenderAppOptions, type UseJsonRenderAppReturn, buildAppHtml, useJsonRenderApp };
package/dist/app.d.ts ADDED
@@ -0,0 +1,91 @@
1
+ import { Spec } from '@json-render/core';
2
+ import { App } from '@modelcontextprotocol/ext-apps';
3
+
4
+ /**
5
+ * Options for the `useJsonRenderApp` hook.
6
+ */
7
+ interface UseJsonRenderAppOptions {
8
+ /** App name shown during initialization. Defaults to `"json-render"`. */
9
+ name?: string;
10
+ /** App version. Defaults to `"1.0.0"`. */
11
+ version?: string;
12
+ }
13
+ /**
14
+ * Return value of `useJsonRenderApp`.
15
+ */
16
+ interface UseJsonRenderAppReturn {
17
+ /** The current json-render spec (null until the first tool result). */
18
+ spec: Spec | null;
19
+ /** Whether the app is still connecting to the host. */
20
+ connecting: boolean;
21
+ /** Whether the app is connected to the host. */
22
+ connected: boolean;
23
+ /** Connection error, if any. */
24
+ error: Error | null;
25
+ /** Whether the spec is still being received / parsed. */
26
+ loading: boolean;
27
+ /** The underlying MCP App instance. */
28
+ app: App | null;
29
+ /**
30
+ * Call a tool on the MCP server and update the spec from the result.
31
+ * Useful for refresh / drill-down interactions.
32
+ */
33
+ callServerTool: (name: string, args?: Record<string, unknown>) => Promise<void>;
34
+ }
35
+ /**
36
+ * React hook that connects to the MCP host, listens for tool results,
37
+ * and maintains the current json-render spec.
38
+ *
39
+ * Follows the official MCP Apps pattern: create an `App` instance,
40
+ * register the `ontoolresult` handler, then call `app.connect()`
41
+ * which internally creates a PostMessageTransport to the host.
42
+ */
43
+ declare function useJsonRenderApp(options?: UseJsonRenderAppOptions): UseJsonRenderAppReturn;
44
+
45
+ /**
46
+ * Options for `buildAppHtml`.
47
+ */
48
+ interface BuildAppHtmlOptions {
49
+ /** Title for the HTML page. Defaults to `"json-render"`. */
50
+ title?: string;
51
+ /**
52
+ * Inline CSS to inject into the page `<style>` tag.
53
+ * Use this to include Tailwind output or custom styles.
54
+ */
55
+ css?: string;
56
+ /**
57
+ * Bundled JavaScript for the app entry point.
58
+ * This should be the output of a bundler (Vite, esbuild, etc.)
59
+ * that bundles your React app, registry, and the
60
+ * `useJsonRenderApp` hook into a single script.
61
+ */
62
+ js: string;
63
+ /**
64
+ * Additional `<head>` content (meta tags, font links, etc.).
65
+ */
66
+ head?: string;
67
+ }
68
+ /**
69
+ * Build a self-contained HTML string for an MCP App UI resource.
70
+ *
71
+ * The resulting HTML is designed to be served as a `ui://` resource
72
+ * via `registerJsonRenderResource` or `createMcpApp`.
73
+ *
74
+ * Typically you'd use a bundler (Vite + `vite-plugin-singlefile`, or
75
+ * esbuild) to produce the `js` and `css` strings, then pass them here.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * import { buildAppHtml } from "@json-render/mcp/app";
80
+ * import { readFileSync } from "node:fs";
81
+ *
82
+ * const html = buildAppHtml({
83
+ * title: "Dashboard",
84
+ * js: readFileSync("dist/app.js", "utf-8"),
85
+ * css: readFileSync("dist/app.css", "utf-8"),
86
+ * });
87
+ * ```
88
+ */
89
+ declare function buildAppHtml(options: BuildAppHtmlOptions): string;
90
+
91
+ export { type BuildAppHtmlOptions, type UseJsonRenderAppOptions, type UseJsonRenderAppReturn, buildAppHtml, useJsonRenderApp };
package/dist/app.js ADDED
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/app.ts
21
+ var app_exports = {};
22
+ __export(app_exports, {
23
+ buildAppHtml: () => buildAppHtml,
24
+ useJsonRenderApp: () => useJsonRenderApp
25
+ });
26
+ module.exports = __toCommonJS(app_exports);
27
+
28
+ // src/use-json-render-app.ts
29
+ var import_react = require("react");
30
+ var import_ext_apps = require("@modelcontextprotocol/ext-apps");
31
+ function parseSpecFromToolResult(result) {
32
+ const textContent = result.content?.find(
33
+ (c) => c.type === "text"
34
+ );
35
+ if (!textContent?.text) return null;
36
+ try {
37
+ const parsed = JSON.parse(textContent.text);
38
+ if (parsed && typeof parsed === "object" && "spec" in parsed) {
39
+ return parsed.spec;
40
+ }
41
+ return parsed;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+ function useJsonRenderApp(options = {}) {
47
+ const { name = "json-render", version = "1.0.0" } = options;
48
+ const [spec, setSpec] = (0, import_react.useState)(null);
49
+ const [loading, setLoading] = (0, import_react.useState)(true);
50
+ const [connected, setConnected] = (0, import_react.useState)(false);
51
+ const [error, setError] = (0, import_react.useState)(null);
52
+ const appRef = (0, import_react.useRef)(null);
53
+ (0, import_react.useEffect)(() => {
54
+ const app = new import_ext_apps.App({ name, version });
55
+ appRef.current = app;
56
+ app.ontoolresult = (result) => {
57
+ const parsed = parseSpecFromToolResult(result);
58
+ if (parsed) {
59
+ setSpec(parsed);
60
+ setLoading(false);
61
+ }
62
+ };
63
+ app.connect().then(() => {
64
+ setConnected(true);
65
+ }).catch((err) => {
66
+ setError(err instanceof Error ? err : new Error(String(err)));
67
+ });
68
+ return () => {
69
+ app.close().catch(() => {
70
+ });
71
+ };
72
+ }, []);
73
+ const callServerTool = (0, import_react.useCallback)(
74
+ async (toolName, args = {}) => {
75
+ if (!appRef.current) return;
76
+ setLoading(true);
77
+ try {
78
+ const result = await appRef.current.callServerTool({
79
+ name: toolName,
80
+ arguments: args
81
+ });
82
+ const parsed = parseSpecFromToolResult(result);
83
+ if (parsed) setSpec(parsed);
84
+ } finally {
85
+ setLoading(false);
86
+ }
87
+ },
88
+ []
89
+ );
90
+ return {
91
+ spec,
92
+ connecting: !connected && !error,
93
+ connected,
94
+ error,
95
+ loading,
96
+ app: appRef.current,
97
+ callServerTool
98
+ };
99
+ }
100
+
101
+ // src/build-app-html.ts
102
+ function buildAppHtml(options) {
103
+ const { title = "json-render", css = "", js, head = "" } = options;
104
+ return `<!DOCTYPE html>
105
+ <html lang="en">
106
+ <head>
107
+ <meta charset="UTF-8" />
108
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
109
+ <title>${escapeHtml(title)}</title>
110
+ ${head}
111
+ <style>${css}</style>
112
+ </head>
113
+ <body>
114
+ <div id="root"></div>
115
+ <script type="module">${js}</script>
116
+ </body>
117
+ </html>`;
118
+ }
119
+ function escapeHtml(str) {
120
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
121
+ }
122
+ // Annotate the CommonJS export names for ESM import in node:
123
+ 0 && (module.exports = {
124
+ buildAppHtml,
125
+ useJsonRenderApp
126
+ });
127
+ //# sourceMappingURL=app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/app.ts","../src/use-json-render-app.ts","../src/build-app-html.ts"],"sourcesContent":["/**\n * Client-side (iframe) utilities for rendering json-render specs\n * inside an MCP App view.\n *\n * This module is intended to run **inside the sandboxed iframe** that\n * MCP hosts render. It connects to the host via the MCP Apps protocol,\n * receives tool results containing json-render specs, and provides\n * React hooks / helpers to render them.\n *\n * @example\n * ```tsx\n * import { useJsonRenderApp } from \"@json-render/mcp/app\";\n * import { Renderer } from \"@json-render/react\";\n *\n * function McpAppView({ registry }) {\n * const { spec, loading } = useJsonRenderApp();\n * return <Renderer spec={spec} registry={registry} loading={loading} />;\n * }\n * ```\n *\n * @packageDocumentation\n */\n\nexport { useJsonRenderApp } from \"./use-json-render-app.js\";\nexport type {\n UseJsonRenderAppOptions,\n UseJsonRenderAppReturn,\n} from \"./use-json-render-app.js\";\nexport { buildAppHtml } from \"./build-app-html.js\";\nexport type { BuildAppHtmlOptions } from \"./build-app-html.js\";\n","import { useState, useEffect, useCallback, useRef } from \"react\";\nimport type { Spec } from \"@json-render/core\";\nimport { App } from \"@modelcontextprotocol/ext-apps\";\n\n/**\n * Options for the `useJsonRenderApp` hook.\n */\nexport interface UseJsonRenderAppOptions {\n /** App name shown during initialization. Defaults to `\"json-render\"`. */\n name?: string;\n /** App version. Defaults to `\"1.0.0\"`. */\n version?: string;\n}\n\n/**\n * Return value of `useJsonRenderApp`.\n */\nexport interface UseJsonRenderAppReturn {\n /** The current json-render spec (null until the first tool result). */\n spec: Spec | null;\n /** Whether the app is still connecting to the host. */\n connecting: boolean;\n /** Whether the app is connected to the host. */\n connected: boolean;\n /** Connection error, if any. */\n error: Error | null;\n /** Whether the spec is still being received / parsed. */\n loading: boolean;\n /** The underlying MCP App instance. */\n app: App | null;\n /**\n * Call a tool on the MCP server and update the spec from the result.\n * Useful for refresh / drill-down interactions.\n */\n callServerTool: (\n name: string,\n args?: Record<string, unknown>,\n ) => Promise<void>;\n}\n\ninterface ToolResultContent {\n type: string;\n text?: string;\n}\n\nfunction parseSpecFromToolResult(result: {\n content?: ToolResultContent[];\n}): Spec | null {\n const textContent = result.content?.find(\n (c: ToolResultContent) => c.type === \"text\",\n );\n if (!textContent?.text) return null;\n try {\n const parsed = JSON.parse(textContent.text);\n if (parsed && typeof parsed === \"object\" && \"spec\" in parsed) {\n return parsed.spec as Spec;\n }\n return parsed as Spec;\n } catch {\n return null;\n }\n}\n\n/**\n * React hook that connects to the MCP host, listens for tool results,\n * and maintains the current json-render spec.\n *\n * Follows the official MCP Apps pattern: create an `App` instance,\n * register the `ontoolresult` handler, then call `app.connect()`\n * which internally creates a PostMessageTransport to the host.\n */\nexport function useJsonRenderApp(\n options: UseJsonRenderAppOptions = {},\n): UseJsonRenderAppReturn {\n const { name = \"json-render\", version = \"1.0.0\" } = options;\n\n const [spec, setSpec] = useState<Spec | null>(null);\n const [loading, setLoading] = useState(true);\n const [connected, setConnected] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const appRef = useRef<App | null>(null);\n\n useEffect(() => {\n const app = new App({ name, version });\n appRef.current = app;\n\n app.ontoolresult = (result: { content?: ToolResultContent[] }) => {\n const parsed = parseSpecFromToolResult(result);\n if (parsed) {\n setSpec(parsed);\n setLoading(false);\n }\n };\n\n // Let the App class handle transport creation internally,\n // matching the official MCP Apps quickstart pattern.\n app\n .connect()\n .then(() => {\n setConnected(true);\n })\n .catch((err: unknown) => {\n setError(err instanceof Error ? err : new Error(String(err)));\n });\n\n return () => {\n app.close().catch(() => {});\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const callServerTool = useCallback(\n async (toolName: string, args: Record<string, unknown> = {}) => {\n if (!appRef.current) return;\n setLoading(true);\n try {\n const result = await appRef.current.callServerTool({\n name: toolName,\n arguments: args,\n });\n const parsed = parseSpecFromToolResult(result);\n if (parsed) setSpec(parsed);\n } finally {\n setLoading(false);\n }\n },\n [],\n );\n\n return {\n spec,\n connecting: !connected && !error,\n connected,\n error,\n loading,\n app: appRef.current,\n callServerTool,\n };\n}\n","/**\n * Options for `buildAppHtml`.\n */\nexport interface BuildAppHtmlOptions {\n /** Title for the HTML page. Defaults to `\"json-render\"`. */\n title?: string;\n /**\n * Inline CSS to inject into the page `<style>` tag.\n * Use this to include Tailwind output or custom styles.\n */\n css?: string;\n /**\n * Bundled JavaScript for the app entry point.\n * This should be the output of a bundler (Vite, esbuild, etc.)\n * that bundles your React app, registry, and the\n * `useJsonRenderApp` hook into a single script.\n */\n js: string;\n /**\n * Additional `<head>` content (meta tags, font links, etc.).\n */\n head?: string;\n}\n\n/**\n * Build a self-contained HTML string for an MCP App UI resource.\n *\n * The resulting HTML is designed to be served as a `ui://` resource\n * via `registerJsonRenderResource` or `createMcpApp`.\n *\n * Typically you'd use a bundler (Vite + `vite-plugin-singlefile`, or\n * esbuild) to produce the `js` and `css` strings, then pass them here.\n *\n * @example\n * ```ts\n * import { buildAppHtml } from \"@json-render/mcp/app\";\n * import { readFileSync } from \"node:fs\";\n *\n * const html = buildAppHtml({\n * title: \"Dashboard\",\n * js: readFileSync(\"dist/app.js\", \"utf-8\"),\n * css: readFileSync(\"dist/app.css\", \"utf-8\"),\n * });\n * ```\n */\nexport function buildAppHtml(options: BuildAppHtmlOptions): string {\n const { title = \"json-render\", css = \"\", js, head = \"\" } = options;\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${escapeHtml(title)}</title>\n ${head}\n <style>${css}</style>\n</head>\n<body>\n <div id=\"root\"></div>\n <script type=\"module\">${js}</script>\n</body>\n</html>`;\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAyD;AAEzD,sBAAoB;AA2CpB,SAAS,wBAAwB,QAEjB;AACd,QAAM,cAAc,OAAO,SAAS;AAAA,IAClC,CAAC,MAAyB,EAAE,SAAS;AAAA,EACvC;AACA,MAAI,CAAC,aAAa,KAAM,QAAO;AAC/B,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,YAAY,IAAI;AAC1C,QAAI,UAAU,OAAO,WAAW,YAAY,UAAU,QAAQ;AAC5D,aAAO,OAAO;AAAA,IAChB;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAUO,SAAS,iBACd,UAAmC,CAAC,GACZ;AACxB,QAAM,EAAE,OAAO,eAAe,UAAU,QAAQ,IAAI;AAEpD,QAAM,CAAC,MAAM,OAAO,QAAI,uBAAsB,IAAI;AAClD,QAAM,CAAC,SAAS,UAAU,QAAI,uBAAS,IAAI;AAC3C,QAAM,CAAC,WAAW,YAAY,QAAI,uBAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAuB,IAAI;AACrD,QAAM,aAAS,qBAAmB,IAAI;AAEtC,8BAAU,MAAM;AACd,UAAM,MAAM,IAAI,oBAAI,EAAE,MAAM,QAAQ,CAAC;AACrC,WAAO,UAAU;AAEjB,QAAI,eAAe,CAAC,WAA8C;AAChE,YAAM,SAAS,wBAAwB,MAAM;AAC7C,UAAI,QAAQ;AACV,gBAAQ,MAAM;AACd,mBAAW,KAAK;AAAA,MAClB;AAAA,IACF;AAIA,QACG,QAAQ,EACR,KAAK,MAAM;AACV,mBAAa,IAAI;AAAA,IACnB,CAAC,EACA,MAAM,CAAC,QAAiB;AACvB,eAAS,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;AAAA,IAC9D,CAAC;AAEH,WAAO,MAAM;AACX,UAAI,MAAM,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAC5B;AAAA,EAEF,GAAG,CAAC,CAAC;AAEL,QAAM,qBAAiB;AAAA,IACrB,OAAO,UAAkB,OAAgC,CAAC,MAAM;AAC9D,UAAI,CAAC,OAAO,QAAS;AACrB,iBAAW,IAAI;AACf,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,QAAQ,eAAe;AAAA,UACjD,MAAM;AAAA,UACN,WAAW;AAAA,QACb,CAAC;AACD,cAAM,SAAS,wBAAwB,MAAM;AAC7C,YAAI,OAAQ,SAAQ,MAAM;AAAA,MAC5B,UAAE;AACA,mBAAW,KAAK;AAAA,MAClB;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA,YAAY,CAAC,aAAa,CAAC;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,IACA,KAAK,OAAO;AAAA,IACZ;AAAA,EACF;AACF;;;AC7FO,SAAS,aAAa,SAAsC;AACjE,QAAM,EAAE,QAAQ,eAAe,MAAM,IAAI,IAAI,OAAO,GAAG,IAAI;AAE3D,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA,WAKE,WAAW,KAAK,CAAC;AAAA,IACxB,IAAI;AAAA,WACG,GAAG;AAAA;AAAA;AAAA;AAAA,0BAIY,EAAE;AAAA;AAAA;AAG5B;AAEA,SAAS,WAAW,KAAqB;AACvC,SAAO,IACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ;AAC3B;","names":[]}
package/dist/app.mjs ADDED
@@ -0,0 +1,99 @@
1
+ // src/use-json-render-app.ts
2
+ import { useState, useEffect, useCallback, useRef } from "react";
3
+ import { App } from "@modelcontextprotocol/ext-apps";
4
+ function parseSpecFromToolResult(result) {
5
+ const textContent = result.content?.find(
6
+ (c) => c.type === "text"
7
+ );
8
+ if (!textContent?.text) return null;
9
+ try {
10
+ const parsed = JSON.parse(textContent.text);
11
+ if (parsed && typeof parsed === "object" && "spec" in parsed) {
12
+ return parsed.spec;
13
+ }
14
+ return parsed;
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+ function useJsonRenderApp(options = {}) {
20
+ const { name = "json-render", version = "1.0.0" } = options;
21
+ const [spec, setSpec] = useState(null);
22
+ const [loading, setLoading] = useState(true);
23
+ const [connected, setConnected] = useState(false);
24
+ const [error, setError] = useState(null);
25
+ const appRef = useRef(null);
26
+ useEffect(() => {
27
+ const app = new App({ name, version });
28
+ appRef.current = app;
29
+ app.ontoolresult = (result) => {
30
+ const parsed = parseSpecFromToolResult(result);
31
+ if (parsed) {
32
+ setSpec(parsed);
33
+ setLoading(false);
34
+ }
35
+ };
36
+ app.connect().then(() => {
37
+ setConnected(true);
38
+ }).catch((err) => {
39
+ setError(err instanceof Error ? err : new Error(String(err)));
40
+ });
41
+ return () => {
42
+ app.close().catch(() => {
43
+ });
44
+ };
45
+ }, []);
46
+ const callServerTool = useCallback(
47
+ async (toolName, args = {}) => {
48
+ if (!appRef.current) return;
49
+ setLoading(true);
50
+ try {
51
+ const result = await appRef.current.callServerTool({
52
+ name: toolName,
53
+ arguments: args
54
+ });
55
+ const parsed = parseSpecFromToolResult(result);
56
+ if (parsed) setSpec(parsed);
57
+ } finally {
58
+ setLoading(false);
59
+ }
60
+ },
61
+ []
62
+ );
63
+ return {
64
+ spec,
65
+ connecting: !connected && !error,
66
+ connected,
67
+ error,
68
+ loading,
69
+ app: appRef.current,
70
+ callServerTool
71
+ };
72
+ }
73
+
74
+ // src/build-app-html.ts
75
+ function buildAppHtml(options) {
76
+ const { title = "json-render", css = "", js, head = "" } = options;
77
+ return `<!DOCTYPE html>
78
+ <html lang="en">
79
+ <head>
80
+ <meta charset="UTF-8" />
81
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
82
+ <title>${escapeHtml(title)}</title>
83
+ ${head}
84
+ <style>${css}</style>
85
+ </head>
86
+ <body>
87
+ <div id="root"></div>
88
+ <script type="module">${js}</script>
89
+ </body>
90
+ </html>`;
91
+ }
92
+ function escapeHtml(str) {
93
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
94
+ }
95
+ export {
96
+ buildAppHtml,
97
+ useJsonRenderApp
98
+ };
99
+ //# sourceMappingURL=app.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/use-json-render-app.ts","../src/build-app-html.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from \"react\";\nimport type { Spec } from \"@json-render/core\";\nimport { App } from \"@modelcontextprotocol/ext-apps\";\n\n/**\n * Options for the `useJsonRenderApp` hook.\n */\nexport interface UseJsonRenderAppOptions {\n /** App name shown during initialization. Defaults to `\"json-render\"`. */\n name?: string;\n /** App version. Defaults to `\"1.0.0\"`. */\n version?: string;\n}\n\n/**\n * Return value of `useJsonRenderApp`.\n */\nexport interface UseJsonRenderAppReturn {\n /** The current json-render spec (null until the first tool result). */\n spec: Spec | null;\n /** Whether the app is still connecting to the host. */\n connecting: boolean;\n /** Whether the app is connected to the host. */\n connected: boolean;\n /** Connection error, if any. */\n error: Error | null;\n /** Whether the spec is still being received / parsed. */\n loading: boolean;\n /** The underlying MCP App instance. */\n app: App | null;\n /**\n * Call a tool on the MCP server and update the spec from the result.\n * Useful for refresh / drill-down interactions.\n */\n callServerTool: (\n name: string,\n args?: Record<string, unknown>,\n ) => Promise<void>;\n}\n\ninterface ToolResultContent {\n type: string;\n text?: string;\n}\n\nfunction parseSpecFromToolResult(result: {\n content?: ToolResultContent[];\n}): Spec | null {\n const textContent = result.content?.find(\n (c: ToolResultContent) => c.type === \"text\",\n );\n if (!textContent?.text) return null;\n try {\n const parsed = JSON.parse(textContent.text);\n if (parsed && typeof parsed === \"object\" && \"spec\" in parsed) {\n return parsed.spec as Spec;\n }\n return parsed as Spec;\n } catch {\n return null;\n }\n}\n\n/**\n * React hook that connects to the MCP host, listens for tool results,\n * and maintains the current json-render spec.\n *\n * Follows the official MCP Apps pattern: create an `App` instance,\n * register the `ontoolresult` handler, then call `app.connect()`\n * which internally creates a PostMessageTransport to the host.\n */\nexport function useJsonRenderApp(\n options: UseJsonRenderAppOptions = {},\n): UseJsonRenderAppReturn {\n const { name = \"json-render\", version = \"1.0.0\" } = options;\n\n const [spec, setSpec] = useState<Spec | null>(null);\n const [loading, setLoading] = useState(true);\n const [connected, setConnected] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const appRef = useRef<App | null>(null);\n\n useEffect(() => {\n const app = new App({ name, version });\n appRef.current = app;\n\n app.ontoolresult = (result: { content?: ToolResultContent[] }) => {\n const parsed = parseSpecFromToolResult(result);\n if (parsed) {\n setSpec(parsed);\n setLoading(false);\n }\n };\n\n // Let the App class handle transport creation internally,\n // matching the official MCP Apps quickstart pattern.\n app\n .connect()\n .then(() => {\n setConnected(true);\n })\n .catch((err: unknown) => {\n setError(err instanceof Error ? err : new Error(String(err)));\n });\n\n return () => {\n app.close().catch(() => {});\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const callServerTool = useCallback(\n async (toolName: string, args: Record<string, unknown> = {}) => {\n if (!appRef.current) return;\n setLoading(true);\n try {\n const result = await appRef.current.callServerTool({\n name: toolName,\n arguments: args,\n });\n const parsed = parseSpecFromToolResult(result);\n if (parsed) setSpec(parsed);\n } finally {\n setLoading(false);\n }\n },\n [],\n );\n\n return {\n spec,\n connecting: !connected && !error,\n connected,\n error,\n loading,\n app: appRef.current,\n callServerTool,\n };\n}\n","/**\n * Options for `buildAppHtml`.\n */\nexport interface BuildAppHtmlOptions {\n /** Title for the HTML page. Defaults to `\"json-render\"`. */\n title?: string;\n /**\n * Inline CSS to inject into the page `<style>` tag.\n * Use this to include Tailwind output or custom styles.\n */\n css?: string;\n /**\n * Bundled JavaScript for the app entry point.\n * This should be the output of a bundler (Vite, esbuild, etc.)\n * that bundles your React app, registry, and the\n * `useJsonRenderApp` hook into a single script.\n */\n js: string;\n /**\n * Additional `<head>` content (meta tags, font links, etc.).\n */\n head?: string;\n}\n\n/**\n * Build a self-contained HTML string for an MCP App UI resource.\n *\n * The resulting HTML is designed to be served as a `ui://` resource\n * via `registerJsonRenderResource` or `createMcpApp`.\n *\n * Typically you'd use a bundler (Vite + `vite-plugin-singlefile`, or\n * esbuild) to produce the `js` and `css` strings, then pass them here.\n *\n * @example\n * ```ts\n * import { buildAppHtml } from \"@json-render/mcp/app\";\n * import { readFileSync } from \"node:fs\";\n *\n * const html = buildAppHtml({\n * title: \"Dashboard\",\n * js: readFileSync(\"dist/app.js\", \"utf-8\"),\n * css: readFileSync(\"dist/app.css\", \"utf-8\"),\n * });\n * ```\n */\nexport function buildAppHtml(options: BuildAppHtmlOptions): string {\n const { title = \"json-render\", css = \"\", js, head = \"\" } = options;\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${escapeHtml(title)}</title>\n ${head}\n <style>${css}</style>\n</head>\n<body>\n <div id=\"root\"></div>\n <script type=\"module\">${js}</script>\n</body>\n</html>`;\n}\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n"],"mappings":";AAAA,SAAS,UAAU,WAAW,aAAa,cAAc;AAEzD,SAAS,WAAW;AA2CpB,SAAS,wBAAwB,QAEjB;AACd,QAAM,cAAc,OAAO,SAAS;AAAA,IAClC,CAAC,MAAyB,EAAE,SAAS;AAAA,EACvC;AACA,MAAI,CAAC,aAAa,KAAM,QAAO;AAC/B,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,YAAY,IAAI;AAC1C,QAAI,UAAU,OAAO,WAAW,YAAY,UAAU,QAAQ;AAC5D,aAAO,OAAO;AAAA,IAChB;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAUO,SAAS,iBACd,UAAmC,CAAC,GACZ;AACxB,QAAM,EAAE,OAAO,eAAe,UAAU,QAAQ,IAAI;AAEpD,QAAM,CAAC,MAAM,OAAO,IAAI,SAAsB,IAAI;AAClD,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,IAAI;AAC3C,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAuB,IAAI;AACrD,QAAM,SAAS,OAAmB,IAAI;AAEtC,YAAU,MAAM;AACd,UAAM,MAAM,IAAI,IAAI,EAAE,MAAM,QAAQ,CAAC;AACrC,WAAO,UAAU;AAEjB,QAAI,eAAe,CAAC,WAA8C;AAChE,YAAM,SAAS,wBAAwB,MAAM;AAC7C,UAAI,QAAQ;AACV,gBAAQ,MAAM;AACd,mBAAW,KAAK;AAAA,MAClB;AAAA,IACF;AAIA,QACG,QAAQ,EACR,KAAK,MAAM;AACV,mBAAa,IAAI;AAAA,IACnB,CAAC,EACA,MAAM,CAAC,QAAiB;AACvB,eAAS,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;AAAA,IAC9D,CAAC;AAEH,WAAO,MAAM;AACX,UAAI,MAAM,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAC5B;AAAA,EAEF,GAAG,CAAC,CAAC;AAEL,QAAM,iBAAiB;AAAA,IACrB,OAAO,UAAkB,OAAgC,CAAC,MAAM;AAC9D,UAAI,CAAC,OAAO,QAAS;AACrB,iBAAW,IAAI;AACf,UAAI;AACF,cAAM,SAAS,MAAM,OAAO,QAAQ,eAAe;AAAA,UACjD,MAAM;AAAA,UACN,WAAW;AAAA,QACb,CAAC;AACD,cAAM,SAAS,wBAAwB,MAAM;AAC7C,YAAI,OAAQ,SAAQ,MAAM;AAAA,MAC5B,UAAE;AACA,mBAAW,KAAK;AAAA,MAClB;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA,YAAY,CAAC,aAAa,CAAC;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,IACA,KAAK,OAAO;AAAA,IACZ;AAAA,EACF;AACF;;;AC7FO,SAAS,aAAa,SAAsC;AACjE,QAAM,EAAE,QAAQ,eAAe,MAAM,IAAI,IAAI,OAAO,GAAG,IAAI;AAE3D,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA,WAKE,WAAW,KAAK,CAAC;AAAA,IACxB,IAAI;AAAA,WACG,GAAG;AAAA;AAAA;AAAA;AAAA,0BAIY,EAAE;AAAA;AAAA;AAG5B;AAEA,SAAS,WAAW,KAAqB;AACvC,SAAO,IACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ;AAC3B;","names":[]}
@@ -0,0 +1,107 @@
1
+ import { Catalog } from '@json-render/core';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+
4
+ /**
5
+ * Options for creating an MCP App server backed by a json-render catalog.
6
+ */
7
+ interface CreateMcpAppOptions {
8
+ /** Display name for the MCP server shown in client UIs. */
9
+ name: string;
10
+ /** Semantic version of the MCP server. */
11
+ version: string;
12
+ /** The json-render catalog defining available components and actions. */
13
+ catalog: Catalog;
14
+ /**
15
+ * Pre-built HTML string for the UI resource.
16
+ * Generate this with `buildAppHtml` from `@json-render/mcp/app` or
17
+ * provide your own self-contained HTML page.
18
+ */
19
+ html: string;
20
+ /**
21
+ * Optional tool configuration overrides.
22
+ */
23
+ tool?: McpToolOptions;
24
+ }
25
+ /**
26
+ * Options for configuring the MCP tool that renders json-render specs.
27
+ */
28
+ interface McpToolOptions {
29
+ /** Tool name exposed to the LLM. Defaults to `"render-ui"`. */
30
+ name?: string;
31
+ /** Human-readable title. Defaults to `"Render UI"`. */
32
+ title?: string;
33
+ /** Tool description shown to the LLM. When omitted, a description is
34
+ * auto-generated from the catalog prompt. */
35
+ description?: string;
36
+ }
37
+ /**
38
+ * Options for registering the MCP App tool.
39
+ */
40
+ interface RegisterToolOptions {
41
+ /** The json-render catalog. */
42
+ catalog: Catalog;
43
+ /** Tool name. */
44
+ name: string;
45
+ /** Tool title. */
46
+ title: string;
47
+ /** Tool description. */
48
+ description: string;
49
+ /** The `ui://` resource URI this tool's view is served from. */
50
+ resourceUri: string;
51
+ }
52
+ /**
53
+ * Options for registering the MCP App UI resource.
54
+ */
55
+ interface RegisterResourceOptions {
56
+ /** The `ui://` resource URI. */
57
+ resourceUri: string;
58
+ /** Self-contained HTML string for the view. */
59
+ html: string;
60
+ }
61
+
62
+ /**
63
+ * Register a json-render tool on an existing MCP server.
64
+ *
65
+ * Uses `registerAppTool` from `@modelcontextprotocol/ext-apps/server`
66
+ * so that MCP Apps-capable hosts (Claude, VS Code, Cursor, ChatGPT)
67
+ * see the `_meta.ui.resourceUri` in the tool listing and know to
68
+ * fetch and render the `ui://` resource as an interactive iframe.
69
+ *
70
+ * The tool accepts a json-render spec as input and returns it as text
71
+ * content, which the iframe receives via `ontoolresult`.
72
+ */
73
+ declare function registerJsonRenderTool(server: McpServer, options: RegisterToolOptions): Promise<void>;
74
+ /**
75
+ * Register a json-render UI resource on an existing MCP server.
76
+ *
77
+ * The resource serves the self-contained HTML page that renders
78
+ * json-render specs received from tool results.
79
+ */
80
+ declare function registerJsonRenderResource(server: McpServer, options: RegisterResourceOptions): Promise<void>;
81
+ /**
82
+ * Create a fully-configured MCP server that serves a json-render catalog
83
+ * as an MCP App.
84
+ *
85
+ * This is the main entry point for most users. It creates an `McpServer`,
86
+ * registers the render tool and UI resource, and returns the server
87
+ * ready for transport connection.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { createMcpApp } from "@json-render/mcp";
92
+ *
93
+ * const server = createMcpApp({
94
+ * name: "My Dashboard",
95
+ * version: "1.0.0",
96
+ * catalog: myCatalog,
97
+ * html: myBundledHtml,
98
+ * });
99
+ *
100
+ * // Connect via stdio
101
+ * import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
102
+ * await server.connect(new StdioServerTransport());
103
+ * ```
104
+ */
105
+ declare function createMcpApp(options: CreateMcpAppOptions): Promise<McpServer>;
106
+
107
+ export { type CreateMcpAppOptions, type McpToolOptions, type RegisterResourceOptions, type RegisterToolOptions, createMcpApp, registerJsonRenderResource, registerJsonRenderTool };
@@ -0,0 +1,107 @@
1
+ import { Catalog } from '@json-render/core';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+
4
+ /**
5
+ * Options for creating an MCP App server backed by a json-render catalog.
6
+ */
7
+ interface CreateMcpAppOptions {
8
+ /** Display name for the MCP server shown in client UIs. */
9
+ name: string;
10
+ /** Semantic version of the MCP server. */
11
+ version: string;
12
+ /** The json-render catalog defining available components and actions. */
13
+ catalog: Catalog;
14
+ /**
15
+ * Pre-built HTML string for the UI resource.
16
+ * Generate this with `buildAppHtml` from `@json-render/mcp/app` or
17
+ * provide your own self-contained HTML page.
18
+ */
19
+ html: string;
20
+ /**
21
+ * Optional tool configuration overrides.
22
+ */
23
+ tool?: McpToolOptions;
24
+ }
25
+ /**
26
+ * Options for configuring the MCP tool that renders json-render specs.
27
+ */
28
+ interface McpToolOptions {
29
+ /** Tool name exposed to the LLM. Defaults to `"render-ui"`. */
30
+ name?: string;
31
+ /** Human-readable title. Defaults to `"Render UI"`. */
32
+ title?: string;
33
+ /** Tool description shown to the LLM. When omitted, a description is
34
+ * auto-generated from the catalog prompt. */
35
+ description?: string;
36
+ }
37
+ /**
38
+ * Options for registering the MCP App tool.
39
+ */
40
+ interface RegisterToolOptions {
41
+ /** The json-render catalog. */
42
+ catalog: Catalog;
43
+ /** Tool name. */
44
+ name: string;
45
+ /** Tool title. */
46
+ title: string;
47
+ /** Tool description. */
48
+ description: string;
49
+ /** The `ui://` resource URI this tool's view is served from. */
50
+ resourceUri: string;
51
+ }
52
+ /**
53
+ * Options for registering the MCP App UI resource.
54
+ */
55
+ interface RegisterResourceOptions {
56
+ /** The `ui://` resource URI. */
57
+ resourceUri: string;
58
+ /** Self-contained HTML string for the view. */
59
+ html: string;
60
+ }
61
+
62
+ /**
63
+ * Register a json-render tool on an existing MCP server.
64
+ *
65
+ * Uses `registerAppTool` from `@modelcontextprotocol/ext-apps/server`
66
+ * so that MCP Apps-capable hosts (Claude, VS Code, Cursor, ChatGPT)
67
+ * see the `_meta.ui.resourceUri` in the tool listing and know to
68
+ * fetch and render the `ui://` resource as an interactive iframe.
69
+ *
70
+ * The tool accepts a json-render spec as input and returns it as text
71
+ * content, which the iframe receives via `ontoolresult`.
72
+ */
73
+ declare function registerJsonRenderTool(server: McpServer, options: RegisterToolOptions): Promise<void>;
74
+ /**
75
+ * Register a json-render UI resource on an existing MCP server.
76
+ *
77
+ * The resource serves the self-contained HTML page that renders
78
+ * json-render specs received from tool results.
79
+ */
80
+ declare function registerJsonRenderResource(server: McpServer, options: RegisterResourceOptions): Promise<void>;
81
+ /**
82
+ * Create a fully-configured MCP server that serves a json-render catalog
83
+ * as an MCP App.
84
+ *
85
+ * This is the main entry point for most users. It creates an `McpServer`,
86
+ * registers the render tool and UI resource, and returns the server
87
+ * ready for transport connection.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { createMcpApp } from "@json-render/mcp";
92
+ *
93
+ * const server = createMcpApp({
94
+ * name: "My Dashboard",
95
+ * version: "1.0.0",
96
+ * catalog: myCatalog,
97
+ * html: myBundledHtml,
98
+ * });
99
+ *
100
+ * // Connect via stdio
101
+ * import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
102
+ * await server.connect(new StdioServerTransport());
103
+ * ```
104
+ */
105
+ declare function createMcpApp(options: CreateMcpAppOptions): Promise<McpServer>;
106
+
107
+ export { type CreateMcpAppOptions, type McpToolOptions, type RegisterResourceOptions, type RegisterToolOptions, createMcpApp, registerJsonRenderResource, registerJsonRenderTool };
package/dist/index.js ADDED
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ createMcpApp: () => createMcpApp,
34
+ registerJsonRenderResource: () => registerJsonRenderResource,
35
+ registerJsonRenderTool: () => registerJsonRenderTool
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/server.ts
40
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
41
+ async function getExtApps() {
42
+ const mod = await import("@modelcontextprotocol/ext-apps/server");
43
+ return mod;
44
+ }
45
+ async function registerJsonRenderTool(server, options) {
46
+ const { catalog, name, title, description, resourceUri } = options;
47
+ const { registerAppTool } = await getExtApps();
48
+ const specZodSchema = catalog.zodSchema();
49
+ registerAppTool(
50
+ server,
51
+ name,
52
+ {
53
+ title,
54
+ description,
55
+ inputSchema: { spec: specZodSchema },
56
+ _meta: { ui: { resourceUri } }
57
+ },
58
+ async (args) => {
59
+ const spec = args.spec;
60
+ const validation = catalog.validate(spec);
61
+ const validSpec = validation.success ? validation.data : spec;
62
+ return {
63
+ content: [
64
+ {
65
+ type: "text",
66
+ text: JSON.stringify(validSpec)
67
+ }
68
+ ]
69
+ };
70
+ }
71
+ );
72
+ }
73
+ async function registerJsonRenderResource(server, options) {
74
+ const { resourceUri, html } = options;
75
+ const { registerAppResource, RESOURCE_MIME_TYPE: mimeType } = await getExtApps();
76
+ registerAppResource(
77
+ server,
78
+ resourceUri,
79
+ resourceUri,
80
+ { mimeType },
81
+ async () => ({
82
+ contents: [
83
+ {
84
+ uri: resourceUri,
85
+ mimeType,
86
+ text: html,
87
+ _meta: {
88
+ ui: {
89
+ csp: {
90
+ resourceDomains: ["https:"],
91
+ connectDomains: ["https:"]
92
+ }
93
+ }
94
+ }
95
+ }
96
+ ]
97
+ })
98
+ );
99
+ }
100
+ async function createMcpApp(options) {
101
+ const { name, version, catalog, html, tool } = options;
102
+ const toolName = tool?.name ?? "render-ui";
103
+ const toolTitle = tool?.title ?? "Render UI";
104
+ const resourceUri = `ui://${toolName}/view.html`;
105
+ const catalogPrompt = catalog.prompt();
106
+ const toolDescription = tool?.description ?? `Render an interactive UI. The spec argument must be a json-render spec conforming to the catalog.
107
+
108
+ ${catalogPrompt}`;
109
+ const server = new import_mcp.McpServer({ name, version });
110
+ await registerJsonRenderTool(server, {
111
+ catalog,
112
+ name: toolName,
113
+ title: toolTitle,
114
+ description: toolDescription,
115
+ resourceUri
116
+ });
117
+ await registerJsonRenderResource(server, { resourceUri, html });
118
+ return server;
119
+ }
120
+ // Annotate the CommonJS export names for ESM import in node:
121
+ 0 && (module.exports = {
122
+ createMcpApp,
123
+ registerJsonRenderResource,
124
+ registerJsonRenderTool
125
+ });
126
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/server.ts"],"sourcesContent":["export type {\n CreateMcpAppOptions,\n McpToolOptions,\n RegisterToolOptions,\n RegisterResourceOptions,\n} from \"./types.js\";\n\nexport {\n createMcpApp,\n registerJsonRenderTool,\n registerJsonRenderResource,\n} from \"./server.js\";\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n CreateMcpAppOptions,\n RegisterToolOptions,\n RegisterResourceOptions,\n} from \"./types.js\";\n\nconst RESOURCE_MIME_TYPE = \"text/html;profile=mcp-app\";\n\n/**\n * Dynamically import the ext-apps server helpers to avoid CJS/ESM type\n * mismatches at compile time while still getting the proper runtime\n * `_meta.ui` normalization that hosts require.\n */\nasync function getExtApps() {\n const mod = await import(\"@modelcontextprotocol/ext-apps/server\");\n return mod;\n}\n\n/**\n * Register a json-render tool on an existing MCP server.\n *\n * Uses `registerAppTool` from `@modelcontextprotocol/ext-apps/server`\n * so that MCP Apps-capable hosts (Claude, VS Code, Cursor, ChatGPT)\n * see the `_meta.ui.resourceUri` in the tool listing and know to\n * fetch and render the `ui://` resource as an interactive iframe.\n *\n * The tool accepts a json-render spec as input and returns it as text\n * content, which the iframe receives via `ontoolresult`.\n */\nexport async function registerJsonRenderTool(\n server: McpServer,\n options: RegisterToolOptions,\n): Promise<void> {\n const { catalog, name, title, description, resourceUri } = options;\n const { registerAppTool } = await getExtApps();\n\n const specZodSchema = catalog.zodSchema();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (registerAppTool as any)(\n server,\n name,\n {\n title,\n description,\n inputSchema: { spec: specZodSchema },\n _meta: { ui: { resourceUri } },\n },\n async (args: { spec?: unknown }) => {\n const spec = args.spec;\n const validation = catalog.validate(spec);\n const validSpec = validation.success ? validation.data : spec;\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(validSpec),\n },\n ],\n };\n },\n );\n}\n\n/**\n * Register a json-render UI resource on an existing MCP server.\n *\n * The resource serves the self-contained HTML page that renders\n * json-render specs received from tool results.\n */\nexport async function registerJsonRenderResource(\n server: McpServer,\n options: RegisterResourceOptions,\n): Promise<void> {\n const { resourceUri, html } = options;\n const { registerAppResource, RESOURCE_MIME_TYPE: mimeType } =\n await getExtApps();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (registerAppResource as any)(\n server,\n resourceUri,\n resourceUri,\n { mimeType },\n async () => ({\n contents: [\n {\n uri: resourceUri,\n mimeType,\n text: html,\n _meta: {\n ui: {\n csp: {\n resourceDomains: [\"https:\"],\n connectDomains: [\"https:\"],\n },\n },\n },\n },\n ],\n }),\n );\n}\n\n/**\n * Create a fully-configured MCP server that serves a json-render catalog\n * as an MCP App.\n *\n * This is the main entry point for most users. It creates an `McpServer`,\n * registers the render tool and UI resource, and returns the server\n * ready for transport connection.\n *\n * @example\n * ```ts\n * import { createMcpApp } from \"@json-render/mcp\";\n *\n * const server = createMcpApp({\n * name: \"My Dashboard\",\n * version: \"1.0.0\",\n * catalog: myCatalog,\n * html: myBundledHtml,\n * });\n *\n * // Connect via stdio\n * import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n * await server.connect(new StdioServerTransport());\n * ```\n */\nexport async function createMcpApp(\n options: CreateMcpAppOptions,\n): Promise<McpServer> {\n const { name, version, catalog, html, tool } = options;\n\n const toolName = tool?.name ?? \"render-ui\";\n const toolTitle = tool?.title ?? \"Render UI\";\n const resourceUri = `ui://${toolName}/view.html`;\n\n const catalogPrompt = catalog.prompt();\n const toolDescription =\n tool?.description ??\n `Render an interactive UI. The spec argument must be a json-render spec conforming to the catalog.\\n\\n${catalogPrompt}`;\n\n const server = new McpServer({ name, version });\n\n await registerJsonRenderTool(server, {\n catalog,\n name: toolName,\n title: toolTitle,\n description: toolDescription,\n resourceUri,\n });\n\n await registerJsonRenderResource(server, { resourceUri, html });\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAA0B;AAc1B,eAAe,aAAa;AAC1B,QAAM,MAAM,MAAM,OAAO,uCAAuC;AAChE,SAAO;AACT;AAaA,eAAsB,uBACpB,QACA,SACe;AACf,QAAM,EAAE,SAAS,MAAM,OAAO,aAAa,YAAY,IAAI;AAC3D,QAAM,EAAE,gBAAgB,IAAI,MAAM,WAAW;AAE7C,QAAM,gBAAgB,QAAQ,UAAU;AAGxC,EAAC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA,aAAa,EAAE,MAAM,cAAc;AAAA,MACnC,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE;AAAA,IAC/B;AAAA,IACA,OAAO,SAA6B;AAClC,YAAM,OAAO,KAAK;AAClB,YAAM,aAAa,QAAQ,SAAS,IAAI;AACxC,YAAM,YAAY,WAAW,UAAU,WAAW,OAAO;AAEzD,aAAO;AAAA,QACL,SAAS;AAAA,UACP;AAAA,YACE,MAAM;AAAA,YACN,MAAM,KAAK,UAAU,SAAS;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAQA,eAAsB,2BACpB,QACA,SACe;AACf,QAAM,EAAE,aAAa,KAAK,IAAI;AAC9B,QAAM,EAAE,qBAAqB,oBAAoB,SAAS,IACxD,MAAM,WAAW;AAGnB,EAAC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,IACA,EAAE,SAAS;AAAA,IACX,aAAa;AAAA,MACX,UAAU;AAAA,QACR;AAAA,UACE,KAAK;AAAA,UACL;AAAA,UACA,MAAM;AAAA,UACN,OAAO;AAAA,YACL,IAAI;AAAA,cACF,KAAK;AAAA,gBACH,iBAAiB,CAAC,QAAQ;AAAA,gBAC1B,gBAAgB,CAAC,QAAQ;AAAA,cAC3B;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AA0BA,eAAsB,aACpB,SACoB;AACpB,QAAM,EAAE,MAAM,SAAS,SAAS,MAAM,KAAK,IAAI;AAE/C,QAAM,WAAW,MAAM,QAAQ;AAC/B,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,cAAc,QAAQ,QAAQ;AAEpC,QAAM,gBAAgB,QAAQ,OAAO;AACrC,QAAM,kBACJ,MAAM,eACN;AAAA;AAAA,EAAwG,aAAa;AAEvH,QAAM,SAAS,IAAI,qBAAU,EAAE,MAAM,QAAQ,CAAC;AAE9C,QAAM,uBAAuB,QAAQ;AAAA,IACnC;AAAA,IACA,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,IACb;AAAA,EACF,CAAC;AAED,QAAM,2BAA2B,QAAQ,EAAE,aAAa,KAAK,CAAC;AAE9D,SAAO;AACT;","names":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1,87 @@
1
+ // src/server.ts
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ async function getExtApps() {
4
+ const mod = await import("@modelcontextprotocol/ext-apps/server");
5
+ return mod;
6
+ }
7
+ async function registerJsonRenderTool(server, options) {
8
+ const { catalog, name, title, description, resourceUri } = options;
9
+ const { registerAppTool } = await getExtApps();
10
+ const specZodSchema = catalog.zodSchema();
11
+ registerAppTool(
12
+ server,
13
+ name,
14
+ {
15
+ title,
16
+ description,
17
+ inputSchema: { spec: specZodSchema },
18
+ _meta: { ui: { resourceUri } }
19
+ },
20
+ async (args) => {
21
+ const spec = args.spec;
22
+ const validation = catalog.validate(spec);
23
+ const validSpec = validation.success ? validation.data : spec;
24
+ return {
25
+ content: [
26
+ {
27
+ type: "text",
28
+ text: JSON.stringify(validSpec)
29
+ }
30
+ ]
31
+ };
32
+ }
33
+ );
34
+ }
35
+ async function registerJsonRenderResource(server, options) {
36
+ const { resourceUri, html } = options;
37
+ const { registerAppResource, RESOURCE_MIME_TYPE: mimeType } = await getExtApps();
38
+ registerAppResource(
39
+ server,
40
+ resourceUri,
41
+ resourceUri,
42
+ { mimeType },
43
+ async () => ({
44
+ contents: [
45
+ {
46
+ uri: resourceUri,
47
+ mimeType,
48
+ text: html,
49
+ _meta: {
50
+ ui: {
51
+ csp: {
52
+ resourceDomains: ["https:"],
53
+ connectDomains: ["https:"]
54
+ }
55
+ }
56
+ }
57
+ }
58
+ ]
59
+ })
60
+ );
61
+ }
62
+ async function createMcpApp(options) {
63
+ const { name, version, catalog, html, tool } = options;
64
+ const toolName = tool?.name ?? "render-ui";
65
+ const toolTitle = tool?.title ?? "Render UI";
66
+ const resourceUri = `ui://${toolName}/view.html`;
67
+ const catalogPrompt = catalog.prompt();
68
+ const toolDescription = tool?.description ?? `Render an interactive UI. The spec argument must be a json-render spec conforming to the catalog.
69
+
70
+ ${catalogPrompt}`;
71
+ const server = new McpServer({ name, version });
72
+ await registerJsonRenderTool(server, {
73
+ catalog,
74
+ name: toolName,
75
+ title: toolTitle,
76
+ description: toolDescription,
77
+ resourceUri
78
+ });
79
+ await registerJsonRenderResource(server, { resourceUri, html });
80
+ return server;
81
+ }
82
+ export {
83
+ createMcpApp,
84
+ registerJsonRenderResource,
85
+ registerJsonRenderTool
86
+ };
87
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n CreateMcpAppOptions,\n RegisterToolOptions,\n RegisterResourceOptions,\n} from \"./types.js\";\n\nconst RESOURCE_MIME_TYPE = \"text/html;profile=mcp-app\";\n\n/**\n * Dynamically import the ext-apps server helpers to avoid CJS/ESM type\n * mismatches at compile time while still getting the proper runtime\n * `_meta.ui` normalization that hosts require.\n */\nasync function getExtApps() {\n const mod = await import(\"@modelcontextprotocol/ext-apps/server\");\n return mod;\n}\n\n/**\n * Register a json-render tool on an existing MCP server.\n *\n * Uses `registerAppTool` from `@modelcontextprotocol/ext-apps/server`\n * so that MCP Apps-capable hosts (Claude, VS Code, Cursor, ChatGPT)\n * see the `_meta.ui.resourceUri` in the tool listing and know to\n * fetch and render the `ui://` resource as an interactive iframe.\n *\n * The tool accepts a json-render spec as input and returns it as text\n * content, which the iframe receives via `ontoolresult`.\n */\nexport async function registerJsonRenderTool(\n server: McpServer,\n options: RegisterToolOptions,\n): Promise<void> {\n const { catalog, name, title, description, resourceUri } = options;\n const { registerAppTool } = await getExtApps();\n\n const specZodSchema = catalog.zodSchema();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (registerAppTool as any)(\n server,\n name,\n {\n title,\n description,\n inputSchema: { spec: specZodSchema },\n _meta: { ui: { resourceUri } },\n },\n async (args: { spec?: unknown }) => {\n const spec = args.spec;\n const validation = catalog.validate(spec);\n const validSpec = validation.success ? validation.data : spec;\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(validSpec),\n },\n ],\n };\n },\n );\n}\n\n/**\n * Register a json-render UI resource on an existing MCP server.\n *\n * The resource serves the self-contained HTML page that renders\n * json-render specs received from tool results.\n */\nexport async function registerJsonRenderResource(\n server: McpServer,\n options: RegisterResourceOptions,\n): Promise<void> {\n const { resourceUri, html } = options;\n const { registerAppResource, RESOURCE_MIME_TYPE: mimeType } =\n await getExtApps();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (registerAppResource as any)(\n server,\n resourceUri,\n resourceUri,\n { mimeType },\n async () => ({\n contents: [\n {\n uri: resourceUri,\n mimeType,\n text: html,\n _meta: {\n ui: {\n csp: {\n resourceDomains: [\"https:\"],\n connectDomains: [\"https:\"],\n },\n },\n },\n },\n ],\n }),\n );\n}\n\n/**\n * Create a fully-configured MCP server that serves a json-render catalog\n * as an MCP App.\n *\n * This is the main entry point for most users. It creates an `McpServer`,\n * registers the render tool and UI resource, and returns the server\n * ready for transport connection.\n *\n * @example\n * ```ts\n * import { createMcpApp } from \"@json-render/mcp\";\n *\n * const server = createMcpApp({\n * name: \"My Dashboard\",\n * version: \"1.0.0\",\n * catalog: myCatalog,\n * html: myBundledHtml,\n * });\n *\n * // Connect via stdio\n * import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n * await server.connect(new StdioServerTransport());\n * ```\n */\nexport async function createMcpApp(\n options: CreateMcpAppOptions,\n): Promise<McpServer> {\n const { name, version, catalog, html, tool } = options;\n\n const toolName = tool?.name ?? \"render-ui\";\n const toolTitle = tool?.title ?? \"Render UI\";\n const resourceUri = `ui://${toolName}/view.html`;\n\n const catalogPrompt = catalog.prompt();\n const toolDescription =\n tool?.description ??\n `Render an interactive UI. The spec argument must be a json-render spec conforming to the catalog.\\n\\n${catalogPrompt}`;\n\n const server = new McpServer({ name, version });\n\n await registerJsonRenderTool(server, {\n catalog,\n name: toolName,\n title: toolTitle,\n description: toolDescription,\n resourceUri,\n });\n\n await registerJsonRenderResource(server, { resourceUri, html });\n\n return server;\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAc1B,eAAe,aAAa;AAC1B,QAAM,MAAM,MAAM,OAAO,uCAAuC;AAChE,SAAO;AACT;AAaA,eAAsB,uBACpB,QACA,SACe;AACf,QAAM,EAAE,SAAS,MAAM,OAAO,aAAa,YAAY,IAAI;AAC3D,QAAM,EAAE,gBAAgB,IAAI,MAAM,WAAW;AAE7C,QAAM,gBAAgB,QAAQ,UAAU;AAGxC,EAAC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA,aAAa,EAAE,MAAM,cAAc;AAAA,MACnC,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE;AAAA,IAC/B;AAAA,IACA,OAAO,SAA6B;AAClC,YAAM,OAAO,KAAK;AAClB,YAAM,aAAa,QAAQ,SAAS,IAAI;AACxC,YAAM,YAAY,WAAW,UAAU,WAAW,OAAO;AAEzD,aAAO;AAAA,QACL,SAAS;AAAA,UACP;AAAA,YACE,MAAM;AAAA,YACN,MAAM,KAAK,UAAU,SAAS;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAQA,eAAsB,2BACpB,QACA,SACe;AACf,QAAM,EAAE,aAAa,KAAK,IAAI;AAC9B,QAAM,EAAE,qBAAqB,oBAAoB,SAAS,IACxD,MAAM,WAAW;AAGnB,EAAC;AAAA,IACC;AAAA,IACA;AAAA,IACA;AAAA,IACA,EAAE,SAAS;AAAA,IACX,aAAa;AAAA,MACX,UAAU;AAAA,QACR;AAAA,UACE,KAAK;AAAA,UACL;AAAA,UACA,MAAM;AAAA,UACN,OAAO;AAAA,YACL,IAAI;AAAA,cACF,KAAK;AAAA,gBACH,iBAAiB,CAAC,QAAQ;AAAA,gBAC1B,gBAAgB,CAAC,QAAQ;AAAA,cAC3B;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AA0BA,eAAsB,aACpB,SACoB;AACpB,QAAM,EAAE,MAAM,SAAS,SAAS,MAAM,KAAK,IAAI;AAE/C,QAAM,WAAW,MAAM,QAAQ;AAC/B,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,cAAc,QAAQ,QAAQ;AAEpC,QAAM,gBAAgB,QAAQ,OAAO;AACrC,QAAM,kBACJ,MAAM,eACN;AAAA;AAAA,EAAwG,aAAa;AAEvH,QAAM,SAAS,IAAI,UAAU,EAAE,MAAM,QAAQ,CAAC;AAE9C,QAAM,uBAAuB,QAAQ;AAAA,IACnC;AAAA,IACA,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,IACb;AAAA,EACF,CAAC;AAED,QAAM,2BAA2B,QAAQ,EAAE,aAAa,KAAK,CAAC;AAE9D,SAAO;AACT;","names":[]}
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "@json-render/mcp",
3
+ "version": "0.11.0",
4
+ "license": "Apache-2.0",
5
+ "description": "MCP Apps integration for @json-render/core. Serve json-render UIs as interactive MCP Apps in Claude, ChatGPT, Cursor, and VS Code.",
6
+ "keywords": [
7
+ "json",
8
+ "ui",
9
+ "mcp",
10
+ "model-context-protocol",
11
+ "mcp-apps",
12
+ "ai",
13
+ "generative-ui",
14
+ "llm",
15
+ "renderer",
16
+ "claude",
17
+ "chatgpt",
18
+ "cursor"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/vercel-labs/json-render.git",
23
+ "directory": "packages/mcp"
24
+ },
25
+ "homepage": "https://github.com/vercel-labs/json-render#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/vercel-labs/json-render/issues"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "main": "./dist/index.js",
33
+ "module": "./dist/index.mjs",
34
+ "types": "./dist/index.d.ts",
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "import": "./dist/index.mjs",
39
+ "require": "./dist/index.js"
40
+ },
41
+ "./app": {
42
+ "types": "./dist/app.d.ts",
43
+ "import": "./dist/app.mjs",
44
+ "require": "./dist/app.js"
45
+ }
46
+ },
47
+ "files": [
48
+ "dist"
49
+ ],
50
+ "dependencies": {
51
+ "@modelcontextprotocol/ext-apps": "^1.2.0",
52
+ "@modelcontextprotocol/sdk": "^1.27.1",
53
+ "@json-render/core": "0.11.0"
54
+ },
55
+ "devDependencies": {
56
+ "@types/react": "19.2.3",
57
+ "tsup": "^8.0.2",
58
+ "typescript": "^5.4.5",
59
+ "@internal/typescript-config": "0.0.0"
60
+ },
61
+ "peerDependencies": {
62
+ "react": "^19.0.0",
63
+ "react-dom": "^19.0.0"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "react": {
67
+ "optional": true
68
+ },
69
+ "react-dom": {
70
+ "optional": true
71
+ }
72
+ },
73
+ "scripts": {
74
+ "build": "tsup",
75
+ "dev": "tsup --watch",
76
+ "typecheck": "tsc --noEmit"
77
+ }
78
+ }