MCP Web UI-通用JavaScript框架
   
MCP服务器的超轻量级、一次性Web UI框架
为MCP(模型上下文协议)服务器从头开始构建的革命性香草JavaScript框架。零依赖性、完美的安全性和超轻量级——旨在为任何用例进行复制、粘贴和定制。
______________________________________________________________________
🚀 为什么选择香草JS?
经过Alpine.js和其他框架的广泛开发,我们用vanilla JavaScript从头开始重建,以实现:
- 🪶 超轻:总捆绑包大小为2-3KB(与8KB+框架相比)
- 🔒 完美的安全性:CSP兼容内置XSS保护
- ⚡ 零依赖:没有外部图书馆,没有供应链风险
- 🤖 AI友好:广泛记录了AI代理的实施
- 🗂️ 一次性:易于复制、粘贴和修改,适用于任何用例
- ⚙️ 无构建过程:编写JavaScript,提供JavaScript,完成
______________________________________________________________________
🎯 快速开始
复制和粘贴集成
无需安装!只需复制框架文件并开始构建:
// 1. Include the framework
// 2. Initialize a todo list
const todoList = MCP.TodoList('#todo-container', [
{ id: 1, text: "Learn vanilla JS", completed: false, priority: "high" },
{ id: 2, text: "Build awesome UI", completed: false, priority: "medium" }
], {
sessionToken: 'your-session-token',
pollInterval: 2000
});
模式驱动初始化
非常适合需要动态生成UI的AI代理:
// AI generates this schema based on data structure
const schema = {
title: "User Management Dashboard",
components: [
{
type: "stats",
id: "user-stats",
config: {
metrics: [
{ key: "total_users", label: "Total Users", icon: "👥" },
{ key: "active_today", label: "Active Today", icon: "🟢" }
]
}
},
{
type: "table",
id: "user-table",
config: {
fields: [
{ key: "name", label: "Name", type: "text", sortable: true },
{ key: "email", label: "Email", type: "text" },
{ key: "status", label: "Status", type: "badge" }
],
sortable: true,
filterable: true
}
}
]
};
// Initialize from schema with port configuration
const components = MCP.initFromSchema(schema, initialData, {
...config,
portRange: [11000, 12000], // Custom port range
blockedPorts: [11434] // Block specific ports (e.g., Ollama)
});______________________________________________________________________
🏗️ 框架架构
核心层
- BaseComponent.js:具有安全性、模板和事件的基础
- 通过自动消毒内置XSS保护
- 速率限制和输入验证
- 智能DOM差异化,实现高效更新
元件层
- TodoListComponent.js:具有撤消功能的高级待办事项列表
- TableComponent.js:具有排序、过滤和分页功能的功能丰富的数据表
- StatsComponent.js:带有动画和趋势的统计显示
框架层
- MCPFramework.js:组件工厂和初始化系统
- 模式驱动的UI生成
- 全球公用事业和会议管理
服务器层
- UIServer.ts:具有完美CSP合规性的增强服务器
- 安全模板渲染
- 具有全面验证的API端点
______________________________________________________________________
🔒 内置安全功能
完美的CSP合规性
该框架生成零违规的完美CSP标头:
Content-Security-Policy: default-src 'self';
script-src 'self' 'nonce-{nonce}';
style-src 'self' 'unsafe-inline';
connect-src 'self';- 不
eval()或Function()构造函数用法 - 没有nonce的内联脚本
- 无外部依赖关系
- 无运行时编译
自动XSS保护
所有用户内容都会自动净化:
// Automatic sanitization in templates
this.html`
${userInput}
` // userInput is automatically escaped
// Advanced LLM content sanitization
sanitizeLLMContent(content, 'todo-text') // Context-aware cleaning
sanitizeLLMContent(content, 'category') // Different rules per context速率限制和输入验证
// Intelligent rate limiting - protects APIs without blocking UI
isRateLimited() // Applied to API calls only (10 calls per 5 seconds)
sanitizeActionData(data) // Cleans all user input
validateEvents() // Ensures event authenticity
// Rate limiting configuration
const config = {
rateLimitWindow: 5000, // 5 second window
maxActionsPerWindow: 10, // 10 API calls per window
security: {
enableRateLimit: true // Enable for production
}
};改进的速率限制(v1.0.5):
- ✅ 用户界面交互(按钮点击、打字)从不受费率限制
- ✅ 只有API调用受到速率限制,以防止服务器滥用
- ✅ 合理限制:每5秒10次API调用
- ✅ 正常使用期间不再出现“动作速率受限”错误
______________________________________________________________________
🎨 可用组件
待办事项列表组件
const todoList = MCP.TodoList('#todo-container', todoData, {
sessionToken: 'session-token',
todo: {
enableUndo: true,
maxTodoLength: 500,
allowCategories: true
}
});数据表组件
const table = MCP.Table('#data-table', tableData, {
sessionToken: 'session-token',
table: {
columns: [
{ key: 'name', label: 'Name', type: 'text', sortable: true },
{ key: 'email', label: 'Email', type: 'text', sortable: true },
{ key: 'status', label: 'Status', type: 'badge',
badgeConfig: { colorMap: { active: 'green', inactive: 'red' } } },
{ key: 'actions', label: 'Actions', type: 'actions',
actions: [
{ type: 'edit', label: 'Edit', icon: '✏️' },
{ type: 'delete', label: 'Delete', icon: '🗑️' }
]
}
],
sortable: true,
filterable: true,
exportable: true
}
});计划任务组件
完成任务管理仪表板,创建模态表单:
// Schema-driven scheduled tasks interface
const taskSchema = {
title: "Scheduled Tasks Dashboard",
components: [
{
type: "stats",
id: "task-overview",
config: {
metrics: [
{ key: "total_tasks", label: "Total Tasks", icon: "📋" },
{ key: "active_tasks", label: "Active", icon: "🟢" },
{ key: "completed_today", label: "Completed Today", icon: "✅" }
]
}
},
{
type: "table",
id: "tasks-list",
config: {
fields: [
{ key: "name", label: "Task Name", type: "text", sortable: true },
{ key: "schedule", label: "Schedule", type: "text" },
{ key: "status", label: "Status", type: "badge" },
{ key: "nextRun", label: "Next Run", type: "datetime" },
{ key: "actions", label: "Actions", type: "actions" }
]
}
}
],
actions: [
{ id: "create-task", type: "button", label: "Create New Task", icon: "➕" },
{ id: "toggle-enabled", type: "inline", handler: "toggle" },
{ id: "run-now", type: "inline", handler: "run-now" },
{ id: "delete", type: "inline", handler: "delete" }
]
};
// Initialize the dashboard
const components = MCP.initFromSchema(taskSchema, taskData, {
sessionToken: 'session-token',
pollInterval: 5000
});统计组件
const stats = MCP.Stats('#stats-container', statsData, {
sessionToken: 'session-token',
stats: {
metrics: [
{ key: 'total', label: 'Total Items', icon: '📊', color: 'blue' },
{ key: 'completed', label: 'Completed', icon: '✅', color: 'green' },
{ key: 'revenue', label: 'Revenue', icon: '💰', color: 'yellow',
type: 'currency', currency: 'USD' }
],
showTrends: true,
animate: true
}
});模态形式系统
内置模态接口,用于数据输入和验证:
// TableComponent automatically handles modal forms when actions are defined
const tableWithForms = MCP.Table('#data-table', data, {
sessionToken: 'session-token',
table: {
// Form fields for modal creation
formFields: [
{ key: 'name', label: 'Task Name', type: 'text', required: true },
{ key: 'description', label: 'Description', type: 'textarea' },
{ key: 'schedule_type', label: 'Schedule Type', type: 'select',
options: ['once', 'daily', 'weekly', 'monthly'] },
{ key: 'schedule_date', label: 'Date', type: 'date', required: true }
],
// Modal configuration
modal: {
title: 'Create New Task',
submitText: 'Create Task',
cancelText: 'Cancel',
validation: true,
backdrop: true
}
}
});特征:
- 现场验证:带有错误消息的实时验证
- 多种字段类型:文本、文本区域、选择、日期、数字
- 键盘导航:ESC关闭,选项卡导航
- 后退单击:单击外部关闭模式
- 加载状态:提交过程中的视觉反馈
- 错误处理:优雅的错误显示和恢复
______________________________________________________________________
🛠️ 服务器集成
使用UIServer
import { UIServer } from './server/UIServer.js';
// The server now uses vanilla JS instead of Alpine.js
const uiServer = new UIServer(
session,
schema,
dataSource,
onUpdate,
pollInterval,
bindAddress
);端口配置
该框架支持灵活的端口配置,以避免冲突:
import { MCPWebUI } from 'mcp-web-ui';
const webUI = new MCPWebUI({
dataSource: myDataSource,
schema: mySchema,
onUpdate: myUpdateHandler,
portRange: [11000, 12000], // Custom port range
blockedPorts: [11434, 3000], // Block specific ports (e.g., Ollama, default apps)
baseUrl: 'https://dev.sizzek.dungeonmind.net'
});环境变量:
# Set port range
MCP_WEB_UI_PORT_MIN=11000
MCP_WEB_UI_PORT_MAX=12000
# Block specific ports (comma-separated)
MCP_WEB_UI_BLOCKED_PORTS=11434,3000,8080API终点
服务器提供以下安全端点:
GET /-使用vanilla JS框架的主UI页面GET /api/data-获取当前数据(使用轮询)POST /api/update-处理用户操作POST /api/extend-session-延长会话持续时间GET /api/health-健康检查GET /static/mcp-framework.js-组合框架包
______________________________________________________________________
🎯 非常适合AI代理
模式驱动的UI生成
AI代理可以轻松生成动态UI:
// AI generates schema based on data structure
const schema = {
title: "Dynamic Dashboard",
components: [
{
type: "stats",
id: "metrics",
config: { /* AI-generated config */ }
},
{
type: "table",
id: "data-grid",
config: { /* AI-generated table config */ }
}
]
};
// Framework handles the rest
MCP.initFromSchema(schema, data, config);构件组装
// Create multiple components that work together
const statsComponent = MCP.Stats('#dashboard-stats', statsData, config);
const tableComponent = MCP.Table('#user-table', userData, config);
const todoComponent = MCP.TodoList('#task-list', taskData, config);
// They automatically sync via the polling system事件驱动交互
// Components communicate through global event bus
MCP.events.emit('user-selected', { userId: 123 });
MCP.events.on('user-selected', (data) => {
// Other components can react to events
console.log('User selected:', data.userId);
});______________________________________________________________________
🔧 定制
创建自定义组件
扩展BaseComponent以实现自定义功能:
class CustomComponent extends BaseComponent {
constructor(element, data, config) {
super(element, data, config);
}
render() {
this.element.innerHTML = this.html`
${this.config.title}
${this.data.map(item => this.html`
${item.name}
`)}
`;
}
bindEvents() {
this.on('click', '.item', (e) => {
this.handleItemClick(e.target.textContent);
});
}
}
// Register with framework
MCP.CustomComponent = function(selector, data, config) {
const element = document.querySelector(selector);
return new CustomComponent(element, data, config);
};______________________________________________________________________
🚀 性能特点
智能投票
组件仅在页面可见时进行轮询:
// Built into BaseComponent
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
this.fetchData(); // Immediate refresh when page becomes visible
}
});高效的DOM更新
仅在数据实际发生变化时更新:
// Smart diffing in BaseComponent.update()
const newDataHash = this.hashData(newData);
if (newDataHash !== this.lastDataHash) {
this.data = newData;
this.render(); // Only render if data changed
}超小捆绑包
服务器将所有框架文件组合成一个2-3KB的请求,并自动进行压缩和缩小。
______________________________________________________________________
📖 api参考
MCP全局对象
MCP.TodoList(selector, data, config) // Create todo list
MCP.Table(selector, data, config) // Create data table with modal support
MCP.Stats(selector, data, config) // Create stats display
MCP.initFromHTML(data, config) // Auto-init from HTML
MCP.initFromSchema(schema, data, config) // Init from schema (recommended)
MCP.getComponent(id) // Get component by ID
MCP.destroyComponent(id) // Destroy component
MCP.destroyAll() // Destroy all components
MCP.events.emit(event, data) // Global event system
MCP.events.on(event, handler) // Listen to global events基础组件方法
// Core methods (implement in subclasses)
render() // Render component HTML
bindEvents() // Bind event listeners
// Built-in methods (available in all components)
html`template${var}` // Secure template rendering
sanitize(string) // XSS protection
update(newData) // Smart data updates
on(event, selector, handler) // Secure event binding
handleAction(action, data) // API actions
fetchData() // Refresh from server
destroy() // Cleanup component
// Modal & Form methods (TableComponent)
showModal() // Display modal form
hideModal() // Close modal form
validateForm(formData) // Validate form input
submitForm(formData) // Submit form to server
resetForm() // Clear form fields______________________________________________________________________
🔄 从Alpine.js迁移
如果从以前的Alpine.js版本迁移:
- 更新服务器:使用
UIServer而不是UIServer - 更新模板:删除Alpine.js指令
- 更新初始化:使用
MCP.initFromSchema()而不是Alpine - 更新CSS:添加vanilla JS框架样式
vanilla JS版本与现有的UI模式完全兼容,只需更改初始化方法即可。
______________________________________________________________________
🎨 造型和主题
CSS架构
/* Component-specific styles */
.component-stats { /* Stats component styles */ }
.component-table { /* Table component styles */ }
.component-list { /* Todo list styles */ }
/* State classes */
.loading { /* Loading states */ }
.error { /* Error states */ }
.empty { /* Empty states */ }
/* Responsive design */
@media (max-width: 768px) { /* Mobile styles */ }暗模式支持
内置暗模式支持:
@media (prefers-color-scheme: dark) {
.component { background: #1e293b; }
.stat-card { background: #334155; }
}______________________________________________________________________
🔮 未来的增强功能
该框架旨在实现可扩展性:
计划组件
- 表单组件:高级表单处理
- 图表组件:数据可视化
- 时间线组件:时间线显示
- 日历组件:日历界面
性能改进
- WebSocket支持:无轮询的实时更新
- 虚拟滚动:高效处理大型数据集
- 服务工作者:离线功能
______________________________________________________________________
🎯 用例
任务与项目管理
- 调度任务:使用类似cron的调度进行自动化任务管理
- 个人所有列表:按优先级和类别跟踪单个任务
- 团队项目跟踪:具有状态更新的协作项目管理
- 目标和习惯跟踪:用进展指标监测长期目标
- 工作流管理:具有条件逻辑的复杂工作流自动化
数据管理
- 用户管理仪表板
- 内容管理系统
- 库存跟踪
- 客户数据管理
监控和分析
- 系统监控仪表板
- 性能指标显示
- 商业智能接口
- 实时状态板
内容和文件
- 记笔记界面
- 文档管理
- 媒体库
- 知识库
______________________________________________________________________
🔍 故障排除
调试模式
启用详细日志记录:
const config = {
enableLogging: true, // Logs all component actions
security: {
enableRateLimit: false // Disable for testing
}
};常见问题
“动作速率受限”错误:此问题已在v1.0.5中修复-更新到最新版本
// Old issue: UI events were rate limited (fixed)
// New behavior: Only API calls are rate limited
const config = {
security: {
enableRateLimit: true // Safe to enable - won't block UI
}
};数据未更新:验证您的数据源是否返回新数据
const dataSource = async (userId?: string) => {
// Don't cache if data changes frequently
return await database.getLatestData(userId);
};CSP违规:确保所有脚本都使用正确的nonce
// Your JavaScript code
模态未显示:确保您的表在架构中定义了操作
const schema = {
actions: [
{ id: "create-task", type: "button", label: "Create New Task" }
]
};______________________________________________________________________
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
______________________________________________________________________
🙏 致谢
- 为 模型上下文协议(MCP) 生态系统
- 灵感来自对超轻量、安全、一次性web界面的需求
- 专为AI代理集成和快速原型设计
______________________________________________________________________
📞 支持
- 问题:
- 讨论:
- 电子邮件: alan.meigs@gmail.com
______________________________________________________________________
由以下材料制成❤️ Alan Meigs\ *最后更新时间:2025年6月26日*
