@modern-js/create 3.10.3 → 3.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/dist/index.js CHANGED
@@ -128,8 +128,8 @@ const lodash_es_isArray = isArray;
128
128
  var freeGlobal = 'object' == typeof global && global && global.Object === Object && global;
129
129
  const _freeGlobal = freeGlobal;
130
130
  var freeSelf = 'object' == typeof self && self && self.Object === Object && self;
131
- var root = _freeGlobal || freeSelf || Function('return this')();
132
- const _root = root;
131
+ var _root_root = _freeGlobal || freeSelf || Function('return this')();
132
+ const _root = _root_root;
133
133
  var Symbol = _root.Symbol;
134
134
  const _Symbol = Symbol;
135
135
  var objectProto = Object.prototype;
@@ -576,6 +576,7 @@ const EN_LOCALE = {
576
576
  optionHelp: ' -h, --help Display this help message',
577
577
  optionVersion: ' -v, --version Display version information',
578
578
  optionLang: ' -l, --lang Set the language (zh or en)',
579
+ optionTemplate: ' --template <name> app (default) or mcp-apps (MCP Apps with UI)',
579
580
  optionSub: ' -s, --sub Mark as a subproject (package in monorepo)',
580
581
  optionNoAgentsMd: ' --no-agents-md Skip generating AGENTS.md for AI coding agents',
581
582
  optionAgentsMdOnly: ' --agents-md-only Only add/refresh AGENTS.md in the current project (no scaffolding)',
@@ -620,6 +621,7 @@ const ZH_LOCALE = {
620
621
  unsupportedVersion: '• 当前 @modern-js/app-tools@{version} 不支持随包文档,未修改任何文件。可在 AGENTS.md 中补充 https://modernjs.dev/llms.txt 供 AI 工具获取框架知识,或升级到 {since} 及以上后重新执行本命令'
621
622
  },
622
623
  help: {
624
+ optionTemplate: ' --template <name> app(默认)或 mcp-apps(带卡片的 MCP Apps)',
623
625
  title: '🚀 Modern.js 项目创建工具',
624
626
  description: '快速创建一个新的 Modern.js 项目',
625
627
  usage: '📖 用法:',
@@ -684,23 +686,38 @@ function runAgentsMd(_templateDir, targetDir) {
684
686
  location: DOCS_PATH
685
687
  }));
686
688
  }
687
- const src_dirname = node_path.dirname(fileURLToPath(import.meta.url));
688
- const templateDir = node_path.resolve(src_dirname, '..', 'template');
689
- const detectLanguage = ()=>{
690
- const langIndex = process.argv.findIndex((arg)=>'--lang' === arg || '-l' === arg);
691
- if (-1 !== langIndex && process.argv[langIndex + 1]) {
692
- const lang = process.argv[langIndex + 1];
693
- return 'zh' === lang ? 'zh' : 'en';
694
- }
695
- const detectedLang = getLocaleLanguage();
696
- if ('zh' === detectedLang) return 'zh';
697
- return 'en';
689
+ var package_namespaceObject = {
690
+ rE: "3.11.0"
698
691
  };
699
- i18n.changeLanguage({
700
- locale: detectLanguage()
701
- });
692
+ function parseTemplate(args) {
693
+ const values = [];
694
+ for(let index = 0; index < args.length; index++)if ('--template' === args[index]) values.push(args[++index] ?? '');
695
+ else if (args[index].startsWith('--template=')) values.push(args[index].slice(11));
696
+ if (values.length > 1 || values.length && ![
697
+ 'app',
698
+ 'mcp-apps'
699
+ ].includes(values[0])) throw new Error('--template must be one of: app, mcp-apps');
700
+ return values[0] ?? 'app';
701
+ }
702
+ function createProject(targetDir, options) {
703
+ const { template, mf } = options;
704
+ const isMcp = 'mcp-apps' === template;
705
+ const data = {
706
+ ...options,
707
+ isMcp,
708
+ mcpAppsVersion: package_namespaceObject.rE
709
+ };
710
+ const root = node_path.resolve(node_path.dirname(fileURLToPath(import.meta.url)), '..');
711
+ copyTemplate(node_path.join(root, 'template'), targetDir, data);
712
+ if (isMcp) {
713
+ const directory = mf ? 'mcp-apps-mf' : template;
714
+ copyTemplate(node_path.join(root, 'templates', directory), targetDir, data);
715
+ }
716
+ }
702
717
  function renderTemplate(template, data) {
703
718
  let result = template;
719
+ const ifRegex = /\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g;
720
+ result = result.replace(ifRegex, (_match, condition, content)=>data[condition] ? content : '');
704
721
  const unlessRegex = /\{\{#unless\s+(\w+)\}\}([\s\S]*?)\{\{\/unless\}\}/g;
705
722
  result = result.replace(unlessRegex, (match, condition, content)=>{
706
723
  const value = data[condition];
@@ -714,6 +731,77 @@ function renderTemplate(template, data) {
714
731
  });
715
732
  return result;
716
733
  }
734
+ function copyTemplate(src, dest, data) {
735
+ node_fs.mkdirSync(dest, {
736
+ recursive: true
737
+ });
738
+ const excludeInSubproject = [
739
+ '.rstack',
740
+ '.vscode',
741
+ '.gitignore.handlebars',
742
+ 'rstack.config.mts',
743
+ '.npmrc',
744
+ '.nvmrc',
745
+ 'AGENTS.md'
746
+ ];
747
+ function copyRecursive(srcDir, destDir) {
748
+ const entries = node_fs.readdirSync(srcDir, {
749
+ withFileTypes: true
750
+ });
751
+ for (const entry of entries){
752
+ if ('.DS_Store' === entry.name) continue;
753
+ if (data.isSubproject && excludeInSubproject.includes(entry.name)) continue;
754
+ if (data.noAgentsMd && 'AGENTS.md' === entry.name) continue;
755
+ const relative = node_path.relative(src, node_path.join(srcDir, entry.name)).split(node_path.sep).join('/');
756
+ if (data.isMcp && 'template' === node_path.basename(src)) {
757
+ if ([
758
+ 'README.md',
759
+ 'modern.config.ts',
760
+ 'src/routes/page.tsx'
761
+ ].includes(relative)) continue;
762
+ }
763
+ const srcPath = node_path.join(srcDir, entry.name);
764
+ let destPath = node_path.join(destDir, entry.name);
765
+ if (entry.isDirectory()) {
766
+ node_fs.mkdirSync(destPath, {
767
+ recursive: true
768
+ });
769
+ copyRecursive(srcPath, destPath);
770
+ } else if (entry.name.endsWith('.handlebars') || 'tsconfig.json' === entry.name) {
771
+ const templateContent = node_fs.readFileSync(srcPath, 'utf-8');
772
+ let rendered = renderTemplate(templateContent, data);
773
+ if ('tsconfig.json' === entry.name && data.isMcp) {
774
+ const config = JSON.parse(rendered);
775
+ config.include.push('api');
776
+ config.compilerOptions.module = 'NodeNext';
777
+ config.compilerOptions.moduleResolution = 'NodeNext';
778
+ if (data.mf) config.include.push('module-federation.config.ts');
779
+ rendered = `${JSON.stringify(config, null, 2)}\n`;
780
+ }
781
+ destPath = destPath.replace(/\.handlebars$/, '');
782
+ node_fs.writeFileSync(destPath, rendered, {
783
+ encoding: 'utf-8',
784
+ flag: 'wx'
785
+ });
786
+ } else node_fs.copyFileSync(srcPath, destPath, node_fs.constants.COPYFILE_EXCL);
787
+ }
788
+ }
789
+ copyRecursive(src, dest);
790
+ }
791
+ const src_dirname = node_path.dirname(fileURLToPath(import.meta.url));
792
+ const detectLanguage = ()=>{
793
+ const langIndex = process.argv.findIndex((arg)=>'--lang' === arg || '-l' === arg);
794
+ if (-1 !== langIndex && process.argv[langIndex + 1]) {
795
+ const lang = process.argv[langIndex + 1];
796
+ return 'zh' === lang ? 'zh' : 'en';
797
+ }
798
+ const detectedLang = getLocaleLanguage();
799
+ if ('zh' === detectedLang) return 'zh';
800
+ return 'en';
801
+ };
802
+ i18n.changeLanguage({
803
+ locale: detectLanguage()
804
+ });
717
805
  function showVersion() {
718
806
  const createPackageJson = node_path.resolve(src_dirname, '..', 'package.json');
719
807
  const createPackage = JSON.parse(node_fs.readFileSync(createPackageJson, 'utf-8'));
@@ -737,6 +825,8 @@ function showHelp() {
737
825
  console.log(i18n.t(localeKeys.help.optionSub));
738
826
  console.log(i18n.t(localeKeys.help.optionNoAgentsMd));
739
827
  console.log(i18n.t(localeKeys.help.optionAgentsMdOnly));
828
+ console.log(i18n.t(localeKeys.help.optionTemplate));
829
+ console.log(' --mf Enable Module Federation for --template mcp-apps');
740
830
  console.log('');
741
831
  console.log(i18n.t(localeKeys.help.examples));
742
832
  console.log(i18n.t(localeKeys.help.example1));
@@ -762,7 +852,8 @@ function promptInput(question) {
762
852
  }
763
853
  const VALUE_FLAGS = [
764
854
  '--lang',
765
- '-l'
855
+ '-l',
856
+ '--template'
766
857
  ];
767
858
  const BOOLEAN_FLAGS = [
768
859
  '--help',
@@ -772,6 +863,7 @@ const BOOLEAN_FLAGS = [
772
863
  '--sub',
773
864
  '-s',
774
865
  '--no-sub',
866
+ '--mf',
775
867
  '--no-agents-md',
776
868
  '--agents-md-only'
777
869
  ];
@@ -795,7 +887,7 @@ function isDirectoryEmpty(dirPath) {
795
887
  }
796
888
  async function getProjectName() {
797
889
  const args = process.argv.slice(2);
798
- const projectNameArg = args.find((arg, index)=>!VALUE_FLAGS.includes(arg) && !BOOLEAN_FLAGS.includes(arg) && !(index > 0 && VALUE_FLAGS.includes(args[index - 1])));
890
+ const projectNameArg = args.find((arg, index)=>!VALUE_FLAGS.includes(arg) && !BOOLEAN_FLAGS.includes(arg) && !arg.startsWith('--template=') && !(index > 0 && VALUE_FLAGS.includes(args[index - 1])));
799
891
  if (projectNameArg) return {
800
892
  name: projectNameArg,
801
893
  useCurrentDir: false
@@ -819,13 +911,16 @@ async function main() {
819
911
  const args = process.argv.slice(2);
820
912
  if (args.includes('--help') || args.includes('-h')) return void showHelp();
821
913
  if (args.includes('--version') || args.includes('-v')) return void showVersion();
914
+ const template = parseTemplate(args);
915
+ const mf = args.includes('--mf');
916
+ if (mf && 'mcp-apps' !== template) throw new Error('--mf requires --template mcp-apps');
822
917
  if (args.includes('--agents-md-only')) {
823
918
  const hasProjectName = args.some((arg, index)=>!arg.startsWith('-') && !VALUE_FLAGS.includes(args[index - 1]));
824
- if (hasProjectName || args.includes('--no-agents-md')) {
919
+ if (hasProjectName || args.includes('--no-agents-md') || 'app' !== template) {
825
920
  console.error(i18n.t(localeKeys.error.agentsMdOnlyConflict));
826
921
  process.exit(1);
827
922
  }
828
- runAgentsMd(templateDir, process.cwd());
923
+ runAgentsMd(node_path.resolve(src_dirname, '../template'), process.cwd());
829
924
  return;
830
925
  }
831
926
  console.log(`\n${i18n.t(localeKeys.message.welcome)}\n`);
@@ -846,16 +941,14 @@ async function main() {
846
941
  const subprojectFlag = detectSubprojectFlag();
847
942
  const isSubproject = true === subprojectFlag;
848
943
  const noAgentsMd = detectNoAgentsMdFlag();
849
- copyTemplate(templateDir, targetDir, {
944
+ createProject(targetDir, {
850
945
  packageName: projectName,
851
946
  version,
852
947
  isSubproject,
853
- noAgentsMd
948
+ noAgentsMd,
949
+ template,
950
+ mf
854
951
  });
855
- const targetPackageJson = node_path.join(targetDir, 'package.json');
856
- const packageJson = JSON.parse(node_fs.readFileSync(targetPackageJson, 'utf-8'));
857
- packageJson.name = projectName;
858
- node_fs.writeFileSync(targetPackageJson, `${JSON.stringify(packageJson, null, 2)}\n`);
859
952
  const dim = '\x1b[2m\x1b[3m';
860
953
  const reset = '\x1b[0m';
861
954
  console.log(`${i18n.t(localeKeys.message.success)}\n`);
@@ -867,47 +960,6 @@ async function main() {
867
960
  console.log(`${dim} ${i18n.t(localeKeys.message.step2)}${reset}`);
868
961
  console.log(`${dim} ${i18n.t(localeKeys.message.step3)}${reset}\n`);
869
962
  }
870
- function copyTemplate(src, dest, options) {
871
- node_fs.mkdirSync(dest, {
872
- recursive: true
873
- });
874
- const excludeInSubproject = [
875
- '.rstack',
876
- '.vscode',
877
- '.gitignore.handlebars',
878
- 'rstack.config.mts',
879
- '.npmrc',
880
- '.nvmrc',
881
- 'AGENTS.md'
882
- ];
883
- function copyRecursive(srcDir, destDir) {
884
- const entries = node_fs.readdirSync(srcDir, {
885
- withFileTypes: true
886
- });
887
- for (const entry of entries){
888
- if (options.isSubproject && excludeInSubproject.includes(entry.name)) continue;
889
- if (options.noAgentsMd && 'AGENTS.md' === entry.name) continue;
890
- const srcPath = node_path.join(srcDir, entry.name);
891
- let destPath = node_path.join(destDir, entry.name);
892
- if (entry.isDirectory()) {
893
- node_fs.mkdirSync(destPath, {
894
- recursive: true
895
- });
896
- copyRecursive(srcPath, destPath);
897
- } else if (entry.name.endsWith('.handlebars')) {
898
- const templateContent = node_fs.readFileSync(srcPath, 'utf-8');
899
- const rendered = renderTemplate(templateContent, {
900
- packageName: options.packageName,
901
- version: options.version,
902
- isSubproject: options.isSubproject
903
- });
904
- destPath = destPath.replace(/\.handlebars$/, '');
905
- node_fs.writeFileSync(destPath, rendered, 'utf-8');
906
- } else node_fs.copyFileSync(srcPath, destPath);
907
- }
908
- }
909
- copyRecursive(src, dest);
910
- }
911
963
  main().catch((error)=>{
912
964
  console.error(i18n.t(localeKeys.error.createFailed), error);
913
965
  process.exit(1);
package/package.json CHANGED
@@ -19,7 +19,7 @@
19
19
  "engines": {
20
20
  "node": ">=20"
21
21
  },
22
- "version": "3.10.3",
22
+ "version": "3.11.0",
23
23
  "main": "./dist/index.js",
24
24
  "bin": {
25
25
  "create": "./bin/run.js"
@@ -30,15 +30,16 @@
30
30
  "files": [
31
31
  "template",
32
32
  "dist",
33
- "bin.js"
33
+ "bin.js",
34
+ "templates"
34
35
  ],
35
36
  "devDependencies": {
36
37
  "@types/node": "^20",
37
38
  "tsx": "^4.23.15",
38
39
  "typescript": "^5",
39
- "@modern-js/rslib": "3.10.3",
40
- "@modern-js/i18n-utils": "3.10.3",
41
- "@scripts/rstest-config": "2.66.2"
40
+ "@modern-js/rslib": "3.11.0",
41
+ "@modern-js/i18n-utils": "3.11.0",
42
+ "@scripts/rstest-config": "2.66.4"
42
43
  },
43
44
  "publishConfig": {
44
45
  "registry": "https://registry.npmjs.org/",
@@ -4,7 +4,8 @@
4
4
  "scripts": {
5
5
  "dev": "modern dev",
6
6
  "build": "modern build",
7
- "serve": "modern serve"{{#unless isSubproject}},
7
+ "serve": "modern serve"{{#if isMcp}},
8
+ "deploy": "modern deploy"{{/if}}{{#unless isSubproject}},
8
9
  "prepare": "rs hooks",
9
10
  "check": "rs check",
10
11
  "lint": "rs lint",
@@ -16,15 +17,24 @@
16
17
  "dependencies": {
17
18
  "@modern-js/runtime": "{{version}}",
18
19
  "react": "^19.2.3",
19
- "react-dom": "^19.2.0"
20
+ "react-dom": "^19.2.0"{{#if isMcp}},
21
+ "@modern-js/mcp-apps": "{{mcpAppsVersion}}",
22
+ "@modern-js/plugin-bff": "{{version}}",
23
+ "@modelcontextprotocol/server": "2.3.1",
24
+ "@modelcontextprotocol/ext-apps": "2.0.3",
25
+ "@modern-js/server-runtime": "{{version}}",
26
+ "zod": "^4.2.0"{{/if}}{{#if mf}},
27
+ "@module-federation/enhanced": "2.0.0"{{/if}}
20
28
  },
21
29
  "devDependencies": {
22
30
  "@modern-js/app-tools": "{{version}}",
23
- "@modern-js/tsconfig": "{{version}}"{{#unless isSubproject}},
31
+ "@modern-js/tsconfig": "{{version}}",
32
+ "typescript": "{{#if isMcp}}~5.9.3{{/if}}{{#unless isMcp}}~5.7.3{{/unless}}",
33
+ "@types/node": "^20"{{#unless isSubproject}},
24
34
  "rstack": "0.8.2"{{/unless}},
25
- "typescript": "~5.7.3",
26
- "@types/node": "^20",
27
35
  "@types/react": "^19.1.8",
28
- "@types/react-dom": "^19.1.6"
36
+ "@types/react-dom": "^19.1.6"{{#if isMcp}},
37
+ "ts-node": "^10.9.2"{{/if}}{{#if mf}},
38
+ "@module-federation/modern-js-v3": "2.0.0"{{/if}}
29
39
  }
30
40
  }
@@ -0,0 +1,10 @@
1
+ # Modern.js MCP Apps
2
+
3
+ Run `pnpm install`, then `pnpm dev`. The MCP endpoint is `/api/mcp`.
4
+
5
+ The server is an ordinary BFF route in `api/lambda/mcp.ts` using the official MCP SDK.
6
+
7
+ Declare cards in `mcp-views.json`. Connect an MCP Apps compatible host to `/api/mcp` to call tools and display cards.
8
+
9
+ Run `pnpm build` and `pnpm serve` for production. Deploy `dist/mcp-apps` together with the generated static assets.
10
+ The UI build never loads the server route or business store. Card props come from `structuredContent`.
@@ -0,0 +1,39 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import { registerAppTool } from '@modelcontextprotocol/ext-apps/server';
3
+ import {
4
+ createBffHandlers,
5
+ registerUiResources,
6
+ } from '@modern-js/mcp-apps/server';
7
+ import { z } from 'zod';
8
+ import { listTodos, addTodo } from '../server/store';
9
+
10
+ async function createServer(request: Request) {
11
+ const server = new McpServer({ name: 'todo-mcp', version: '1.0.0' });
12
+ const ui = await registerUiResources(server, { request });
13
+ registerAppTool(
14
+ server,
15
+ 'list_todos',
16
+ {
17
+ description: 'List todos and open the todo card.',
18
+ inputSchema: z.object({}),
19
+ _meta: { ui: { resourceUri: ui.todos } },
20
+ },
21
+ async () => ({
22
+ content: [{ type: 'text', text: 'Todo list opened.' }],
23
+ structuredContent: { todos: listTodos() },
24
+ }),
25
+ );
26
+ server.registerTool(
27
+ 'add_todo',
28
+ {
29
+ description: 'Add a todo.',
30
+ inputSchema: z.object({ title: z.string().min(1) }),
31
+ },
32
+ async ({ title }) => ({
33
+ content: [{ type: 'text', text: `Added: ${title}` }],
34
+ structuredContent: { todo: addTodo(title) },
35
+ }),
36
+ );
37
+ return server;
38
+ }
39
+ export const { POST, GET, DELETE } = createBffHandlers(createServer);
@@ -0,0 +1,12 @@
1
+ export interface Todo {
2
+ id: string;
3
+ title: string;
4
+ completed: boolean;
5
+ }
6
+ const todos: Todo[] = [];
7
+ export const listTodos = () => todos.map(todo => ({ ...todo }));
8
+ export function addTodo(title: string) {
9
+ const todo = { id: crypto.randomUUID(), title, completed: false };
10
+ todos.push(todo);
11
+ return { ...todo };
12
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "views": {
3
+ "todos": "./src/components/Todos.tsx"
4
+ },
5
+ "csp": {
6
+ "resourceDomains": [],
7
+ "connectDomains": []
8
+ },
9
+ "prefersBorder": true
10
+ }
@@ -0,0 +1,12 @@
1
+ import { appTools } from '@modern-js/app-tools';
2
+ import { bffPlugin } from '@modern-js/plugin-bff';
3
+ import { mcpAppsPlugin } from '@modern-js/mcp-apps/cli';
4
+
5
+ export default {
6
+ server: { port: Number(process.env.PORT ?? 8080) },
7
+ plugins: [
8
+ appTools(),
9
+ bffPlugin(),
10
+ mcpAppsPlugin({ views: './mcp-views.json' }),
11
+ ],
12
+ };
@@ -0,0 +1,58 @@
1
+ import { useState } from 'react';
2
+ import type { McpViewProps } from '@modern-js/mcp-apps/react';
3
+ interface Todo {
4
+ id: string;
5
+ title: string;
6
+ completed: boolean;
7
+ }
8
+ export default function Todos({
9
+ todos = [],
10
+ mcpApp,
11
+ }: McpViewProps<{ todos: Todo[] }>) {
12
+ const [items, setItems] = useState(todos);
13
+ const [title, setTitle] = useState('');
14
+ const [error, setError] = useState('');
15
+ async function add() {
16
+ if (!title.trim()) return;
17
+ const result = await mcpApp.callServerTool({
18
+ name: 'add_todo',
19
+ arguments: { title },
20
+ });
21
+ if (result.isError) {
22
+ setError('Could not add todo');
23
+ return;
24
+ }
25
+ const todo = (result.structuredContent as { todo?: Todo } | undefined)
26
+ ?.todo;
27
+ if (todo) setItems(previous => [...previous, todo]);
28
+ setTitle('');
29
+ }
30
+ const submit = () => {
31
+ void add().catch(() => setError('Could not add todo'));
32
+ };
33
+ return (
34
+ <section>
35
+ <h1>Todos</h1>
36
+ <ul>
37
+ {items.map(todo => (
38
+ <li key={todo.id}>{todo.title}</li>
39
+ ))}
40
+ </ul>
41
+ {/* MCP hosts sandbox cards without allow-forms, which blocks form submission. */}
42
+ <div>
43
+ <input
44
+ aria-label="Todo title"
45
+ value={title}
46
+ onChange={event => setTitle(event.target.value)}
47
+ onKeyDown={event => {
48
+ if (event.key === 'Enter') submit();
49
+ }}
50
+ />
51
+ <button type="button" onClick={submit}>
52
+ Add todo
53
+ </button>
54
+ </div>
55
+ {error && <p role="alert">{error}</p>}
56
+ </section>
57
+ );
58
+ }
@@ -0,0 +1,8 @@
1
+ export default function Page() {
2
+ return (
3
+ <main>
4
+ <h1>Modern.js MCP Apps</h1>
5
+ <p>Connect your MCP Apps compatible host to /api/mcp.</p>
6
+ </main>
7
+ );
8
+ }
@@ -0,0 +1,10 @@
1
+ # Modern.js MCP Apps
2
+
3
+ Run `pnpm install`, then `pnpm dev`. The MCP endpoint is `/api/mcp`.
4
+
5
+ The server is an ordinary BFF route in `api/lambda/mcp.ts` using the official MCP SDK.
6
+
7
+ Declare cards in `mcp-views.json`. Connect an MCP Apps compatible host to `/api/mcp` to call tools and display cards.
8
+
9
+ Run `pnpm build` and `pnpm serve` for production. Deploy `dist/mcp-apps` together with the generated static assets.
10
+ The UI build never loads the server route or business store. Card props come from `structuredContent`.
@@ -0,0 +1,39 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import { registerAppTool } from '@modelcontextprotocol/ext-apps/server';
3
+ import {
4
+ createBffHandlers,
5
+ registerUiResources,
6
+ } from '@modern-js/mcp-apps/server';
7
+ import { z } from 'zod';
8
+ import { listTodos, addTodo } from '../server/store';
9
+
10
+ async function createServer(request: Request) {
11
+ const server = new McpServer({ name: 'todo-mcp', version: '1.0.0' });
12
+ const ui = await registerUiResources(server, { request });
13
+ registerAppTool(
14
+ server,
15
+ 'list_todos',
16
+ {
17
+ description: 'List todos and open the todo card.',
18
+ inputSchema: z.object({}),
19
+ _meta: { ui: { resourceUri: ui.todos } },
20
+ },
21
+ async () => ({
22
+ content: [{ type: 'text', text: 'Todo list opened.' }],
23
+ structuredContent: { todos: listTodos() },
24
+ }),
25
+ );
26
+ server.registerTool(
27
+ 'add_todo',
28
+ {
29
+ description: 'Add a todo.',
30
+ inputSchema: z.object({ title: z.string().min(1) }),
31
+ },
32
+ async ({ title }) => ({
33
+ content: [{ type: 'text', text: `Added: ${title}` }],
34
+ structuredContent: { todo: addTodo(title) },
35
+ }),
36
+ );
37
+ return server;
38
+ }
39
+ export const { POST, GET, DELETE } = createBffHandlers(createServer);
@@ -0,0 +1,12 @@
1
+ export interface Todo {
2
+ id: string;
3
+ title: string;
4
+ completed: boolean;
5
+ }
6
+ const todos: Todo[] = [];
7
+ export const listTodos = () => todos.map(todo => ({ ...todo }));
8
+ export function addTodo(title: string) {
9
+ const todo = { id: crypto.randomUUID(), title, completed: false };
10
+ todos.push(todo);
11
+ return { ...todo };
12
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "views": {
3
+ "todos": {
4
+ "expose": "./Todos"
5
+ }
6
+ },
7
+ "csp": {
8
+ "resourceDomains": [],
9
+ "connectDomains": []
10
+ },
11
+ "prefersBorder": true
12
+ }
@@ -0,0 +1,14 @@
1
+ import { appTools } from '@modern-js/app-tools';
2
+ import { bffPlugin } from '@modern-js/plugin-bff';
3
+ import { mcpAppsPlugin } from '@modern-js/mcp-apps/cli';
4
+ import { moduleFederationPlugin } from '@module-federation/modern-js-v3';
5
+
6
+ export default {
7
+ server: { port: Number(process.env.PORT ?? 8080) },
8
+ plugins: [
9
+ appTools(),
10
+ bffPlugin(),
11
+ moduleFederationPlugin(),
12
+ mcpAppsPlugin({ views: './mcp-views.json' }),
13
+ ],
14
+ };
@@ -0,0 +1,17 @@
1
+ import { createModuleFederationConfig } from '@module-federation/modern-js-v3';
2
+
3
+ export default createModuleFederationConfig({
4
+ name: 'mcp_ui',
5
+ manifest: { filePath: 'static' },
6
+ filename: 'static/remoteEntry.js',
7
+ dts: false,
8
+ exposes: {
9
+ './Todos': './src/components/Todos.tsx',
10
+ },
11
+ shared: {
12
+ react: { singleton: true },
13
+ 'react-dom': { singleton: true },
14
+ 'react/jsx-runtime': { singleton: true },
15
+ 'react/jsx-dev-runtime': { singleton: true },
16
+ },
17
+ });
@@ -0,0 +1,58 @@
1
+ import { useState } from 'react';
2
+ import type { McpViewProps } from '@modern-js/mcp-apps/react';
3
+ interface Todo {
4
+ id: string;
5
+ title: string;
6
+ completed: boolean;
7
+ }
8
+ export default function Todos({
9
+ todos = [],
10
+ mcpApp,
11
+ }: McpViewProps<{ todos: Todo[] }>) {
12
+ const [items, setItems] = useState(todos);
13
+ const [title, setTitle] = useState('');
14
+ const [error, setError] = useState('');
15
+ async function add() {
16
+ if (!title.trim()) return;
17
+ const result = await mcpApp.callServerTool({
18
+ name: 'add_todo',
19
+ arguments: { title },
20
+ });
21
+ if (result.isError) {
22
+ setError('Could not add todo');
23
+ return;
24
+ }
25
+ const todo = (result.structuredContent as { todo?: Todo } | undefined)
26
+ ?.todo;
27
+ if (todo) setItems(previous => [...previous, todo]);
28
+ setTitle('');
29
+ }
30
+ const submit = () => {
31
+ void add().catch(() => setError('Could not add todo'));
32
+ };
33
+ return (
34
+ <section>
35
+ <h1>Todos</h1>
36
+ <ul>
37
+ {items.map(todo => (
38
+ <li key={todo.id}>{todo.title}</li>
39
+ ))}
40
+ </ul>
41
+ {/* MCP hosts sandbox cards without allow-forms, which blocks form submission. */}
42
+ <div>
43
+ <input
44
+ aria-label="Todo title"
45
+ value={title}
46
+ onChange={event => setTitle(event.target.value)}
47
+ onKeyDown={event => {
48
+ if (event.key === 'Enter') submit();
49
+ }}
50
+ />
51
+ <button type="button" onClick={submit}>
52
+ Add todo
53
+ </button>
54
+ </div>
55
+ {error && <p role="alert">{error}</p>}
56
+ </section>
57
+ );
58
+ }
@@ -0,0 +1,8 @@
1
+ export default function Page() {
2
+ return (
3
+ <main>
4
+ <h1>Modern.js MCP Apps</h1>
5
+ <p>Connect your MCP Apps compatible host to /api/mcp.</p>
6
+ </main>
7
+ );
8
+ }