Cursor 集成 Figma MCP 实现阅读理解原型图生成方案
整体架构设计
阅读理解题目 Cursor 处理 Figma MCP 自动生成原型 交互式学习界面
在 Cursor 中配置 Figma MCP 的完整方案
1. Cursor 配置文件 (cursor.config.js
)
javascript
// cursor.config.js
module.exports = {
figma: {
// Figma MCP 配置
mcp: {
enabled: true,
apiKey: process.env.FIGMA_API_KEY,
fileId: "YOUR_FIGMA_FILE_ID",
mcpFrameId: "MCP_FRAME_ID", // MCP 主框架 ID
// MCP 组件映射
components: {
question: "COMPONENT_ID:QUESTION",
option: "COMPONENT_ID:OPTION",
feedback: "COMPONENT_ID:FEEDBACK",
progress: "COMPONENT_ID:PROGRESS"
},
// 样式配置
styles: {
primaryColor: "#4361EE",
secondaryColor: "#F1F5F9",
fontFamily: "Inter"
}
},
// 阅读理解题目处理配置
readingComprehension: {
maxQuestions: 10,
optionsPerQuestion: 4,
difficultyLevels: ["easy", "medium", "hard"]
}
},
// 其他 Cursor 配置
aiModel: "gpt-4-turbo",
maxTokens: 4096,
temperature: 0.3
}
2. Figma MCP 连接脚本 (figma-mcp-integration.js
)
javascript
// figma-mcp-integration.js
const axios = require('axios');
const config = require('./cursor.config.js').figma;
class FigmaMCPIntegrator {
constructor() {
this.api = axios.create({
baseURL: 'https://api.figma.com/v1/',
headers: {
'X-Figma-Token': config.mcp.apiKey
}
});
}
/**
* 获取 MCP 框架结构
*/
async getMCPStructure() {
try {
const response = await this.api.get(`files/${config.mcp.fileId}`);
const mcpFrame = this.findMCPFrame(response.data.document);
return {
frame: mcpFrame,
components: config.mcp.components
};
} catch (error) {
console.error('获取 Figma MCP 失败:', error);
throw error;
}
}
/**
* 在 Figma 文档树中查找 MCP 框架
*/
findMCPFrame(node) {
if (node.id === config.mcp.mcpFrameId) return node;
if (node.children) {
for (const child of node.children) {
const found = this.findMCPFrame(child);
if (found) return found;
}
}
return null;
}
/**
* 根据阅读理解数据生成原型
*/
async generateReadingComprehensionPrototype(questions) {
const operations = [];
const baseX = 100;
let currentY = 200;
// 创建主框架
const mainFrame = {
type: 'FRAME',
name: '阅读理解原型',
x: baseX,
y: currentY,
constraints: { horizontal: 'MIN', vertical: 'MIN' },
children: []
};
currentY += 50;
// 添加进度指示器
const progressBar = {
type: 'INSTANCE',
componentId: config.mcp.components.progress,
name: '进度指示器',
x: baseX,
y: currentY,
properties: {
total: questions.length,
current: 1
}
};
mainFrame.children.push(progressBar);
currentY += 80;
// 添加题目和选项
questions.forEach((question, index) => {
// 题目
const questionBlock = {
type: 'INSTANCE',
componentId: config.mcp.components.question,
name: `问题 ${index + 1}`,
x: baseX,
y: currentY,
properties: {
text: question.question,
difficulty: question.difficulty
}
};
mainFrame.children.push(questionBlock);
currentY += 120;
// 选项
question.options.forEach((option, optIndex) => {
const optionBlock = {
type: 'INSTANCE',
componentId: config.mcp.components.option,
name: `选项 ${optIndex + 1}`,
x: baseX + (optIndex * 300),
y: currentY,
properties: {
text: option.text,
isCorrect: option.isCorrect,
optionId: `q${index+1}_opt${optIndex+1}`
}
};
mainFrame.children.push(optionBlock);
});
currentY += 100;
// 反馈区域
const feedbackBlock = {
type: 'INSTANCE',
componentId: config.mcp.components.feedback,
name: `反馈 ${index + 1}`,
x: baseX,
y: currentY,
properties: {
visible: false,
text: question.explanation
}
};
mainFrame.children.push(feedbackBlock);
currentY += 150;
});
// 提交按钮
const submitButton = {
type: 'INSTANCE',
componentId: config.mcp.components.button,
name: '提交答案',
x: baseX,
y: currentY,
properties: {
text: '提交答案',
variant: 'primary'
}
};
mainFrame.children.push(submitButton);
// 添加到操作列表
operations.push({
method: 'POST',
path: `/files/${config.mcp.fileId}/nodes`,
data: {
nodes: [mainFrame]
}
});
// 应用全局样式
operations.push({
method: 'POST',
path: `/files/${config.mcp.fileId}/styles`,
data: {
styles: {
fill: config.mcp.styles.primaryColor,
text: {
fontFamily: config.mcp.styles.fontFamily,
fontSize: 16
}
}
}
});
return operations;
}
/**
* 执行 Figma 操作
*/
async executeOperations(operations) {
const results = [];
for (const operation of operations) {
try {
const response = await this.api({
method: operation.method,
url: operation.path,
data: operation.data
});
results.push(response.data);
} catch (error) {
console.error('Figma 操作失败:', operation.path, error.response?.data || error.message);
results.push({ error: error.message });
}
}
return results;
}
}
module.exports = FigmaMCPIntegrator;
3. 阅读理解题目处理模块 (reading-comprehension-processor.js
)
javascript
// reading-comprehension-processor.js
const { getCodeCompletion } = require('cursor').ai;
const config = require('./cursor.config.js').figma;
class ReadingComprehensionProcessor {
constructor() {
this.difficultyLevels = config.readingComprehension.difficultyLevels;
}
/**
* 从文本中提取阅读理解题目
*/
async extractQuestionsFromText(text) {
const prompt = `
你是一位教育专家,请从以下文本中提取阅读理解题目:
${text}
要求:
1. 生成 ${config.readingComprehension.maxQuestions} 道题目
2. 每道题有 ${config.readingComprehension.optionsPerQuestion} 个选项
3. 包含正确答案和解析
4. 随机分配难度等级:${this.difficultyLevels.join(', ')}
返回格式为 JSON 数组:
[
{
"question": "问题文本",
"options": [
{"text": "选项1", "isCorrect": true/false},
...
],
"correctAnswer": "A",
"explanation": "答案解析",
"difficulty": "easy/medium/hard"
},
...
]
`;
const response = await getCodeCompletion({
prompt,
model: config.aiModel,
maxTokens: config.maxTokens,
temperature: config.temperature
});
try {
const questions = JSON.parse(response);
return this.validateQuestions(questions);
} catch (e) {
console.error('解析题目失败:', e);
return this.fallbackQuestionGeneration(text);
}
}
/**
* 验证题目格式
*/
validateQuestions(questions) {
if (!Array.isArray(questions)) throw new Error('题目格式无效');
return questions.slice(0, config.readingComprehension.maxQuestions).map(q => {
// 确保选项数量正确
if (q.options.length > config.readingComprehension.optionsPerQuestion) {
q.options = q.options.slice(0, config.readingComprehension.optionsPerQuestion);
}
// 确保有正确答案
const hasCorrect = q.options.some(opt => opt.isCorrect);
if (!hasCorrect && q.options.length > 0) {
q.options[0].isCorrect = true;
}
// 验证难度等级
if (!this.difficultyLevels.includes(q.difficulty)) {
q.difficulty = this.difficultyLevels[Math.floor(Math.random() * this.difficultyLevels.length)];
}
return q;
});
}
/**
* 后备题目生成方法
*/
async fallbackQuestionGeneration(text) {
console.warn('使用后备题目生成方法');
// 简化版的题目生成逻辑
const sentences = text.split(/[.!?]/).filter(s => s.trim().length > 10);
return sentences.slice(0, config.readingComprehension.maxQuestions).map((sentence, i) => {
const baseQuestion = `关于这句话的理解正确的是? "${sentence.trim()}"`;
return {
question: baseQuestion,
options: [
{ text: "正确理解1", isCorrect: i === 0 },
{ text: "正确理解2", isCorrect: i === 1 },
{ text: "错误理解1", isCorrect: false },
{ text: "错误理解2", isCorrect: false }
],
correctAnswer: i < 2 ? "A" : "B",
explanation: "这是自动生成的题目解析",
difficulty: this.difficultyLevels[i % this.difficultyLevels.length]
};
});
}
}
module.exports = ReadingComprehensionProcessor;
4. 主执行脚本 (main.js
)
javascript
// main.js
const FigmaMCPIntegrator = require('./figma-mcp-integration');
const ReadingComprehensionProcessor = require('./reading-comprehension-processor');
const config = require('./cursor.config.js').figma;
async function main() {
// 1. 获取阅读理解文本
const readingText = `
人工智能(AI)是计算机科学的一个分支,旨在创建能够执行通常需要人类智能的任务的系统。
这些任务包括学习、推理、问题解决、感知和语言理解。AI可以分为两类:弱人工智能和强人工智能。
弱人工智能专注于执行特定任务,而强人工智能则具有全面的认知能力。
AI的发展经历了几个阶段。1950年代是AI的诞生期,艾伦·图灵提出了著名的"图灵测试"。
1980年代见证了专家系统的兴起,这些系统模拟人类专家的决策能力。
2010年代,深度学习的突破推动了AI的快速发展,特别是在图像识别和自然语言处理领域。
当前,AI已应用于多个领域:医疗诊断、自动驾驶汽车、智能助手和金融分析等。
然而,AI也引发了伦理问题,如就业影响、隐私问题和算法偏见。
`;
// 2. 处理阅读理解题目
const processor = new ReadingComprehensionProcessor();
const questions = await processor.extractQuestionsFromText(readingText);
console.log(`成功生成 ${questions.length} 道题目`);
// 3. 连接到 Figma MCP
const figma = new FigmaMCPIntegrator();
const mcpStructure = await figma.getMCPStructure();
console.log('Figma MCP 结构:', mcpStructure);
// 4. 生成原型操作
const operations = await figma.generateReadingComprehensionPrototype(questions);
// 5. 在 Figma 中执行操作
const results = await figma.executeOperations(operations);
console.log('原型生成结果:', results);
// 6. 输出 Figma 文件链接
const figmaFileUrl = `https://www.figma.com/file/${config.mcp.fileId}`;
console.log(`\n原型已生成: ${figmaFileUrl}`);
return {
questions,
figmaUrl: figmaFileUrl
};
}
// 执行主函数
main()
.then(result => console.log('完成:', result))
.catch(err => console.error('发生错误:', err));
Figma MCP 配置指南
1. 在 Figma 中创建 MCP 组件
在 Figma 文件中创建以下主要组件:
主控制面板 题目组件 选项组件 反馈组件 进度组件 按钮组件 文本区域 难度指示器 选项文本 选择框 反馈文本 反馈图标 进度条 进度文本
2. 组件属性配置
为每个组件设置可配置属性:
组件 | 属性 | 类型 | 描述 |
---|---|---|---|
题目 | text | 文本 | 问题文本 |
difficulty | 枚举 | easy/medium/hard | |
选项 | text | 文本 | 选项文本 |
isCorrect | 布尔 | 是否为正确答案 | |
optionId | 文本 | 选项唯一标识 | |
反馈 | text | 文本 | 解释文本 |
visible | 布尔 | 是否显示 | |
进度 | total | 数字 | 总题目数 |
current | 数字 | 当前题目 | |
按钮 | text | 文本 | 按钮文本 |
variant | 枚举 | primary/secondary |
3. 在 Cursor 中配置组件 ID
在 cursor.config.js
中配置组件 ID:
javascript
components: {
question: "12345:7890", // Figma 组件 ID
option: "23456:8901",
feedback: "34567:9012",
progress: "45678:0123",
button: "56789:1234"
}
交互原型功能实现
1. 交互逻辑脚本
在 Figma 中添加原型交互逻辑:
javascript
// 选项点击交互
function onOptionClick(optionId) {
// 重置所有选项状态
resetAllOptions();
// 设置当前选中选项
setOptionSelected(optionId, true);
// 显示反馈区域
setFeedbackVisible(true);
}
// 提交按钮交互
function onSubmit() {
// 验证答案
const isCorrect = checkAnswer();
// 更新进度
updateProgress();
// 显示结果
showResult(isCorrect);
// 进入下一题
goToNextQuestion();
}
// 答案检查逻辑
function checkAnswer() {
const selectedOption = getSelectedOption();
return selectedOption && selectedOption.isCorrect;
}
2. 原型状态管理
使用 Figma 的变量功能管理状态:
javascript
// 状态变量
const state = {
currentQuestion: 1,
totalQuestions: 10,
selectedOption: null,
answers: {}
};
// 更新状态函数
function setState(newState) {
Object.assign(state, newState);
updateUI();
}
// 更新UI
function updateUI() {
// 更新进度条
progressBar.setProperties({
current: state.currentQuestion,
total: state.totalQuestions
});
// 更新题目
questionText.text = getQuestionText(state.currentQuestion);
// 更新选项
options.forEach(option => {
option.setProperties({
selected: state.selectedOption === option.id
});
});
}
部署与使用指南
1. 环境准备
- 安装 Node.js (v16+)
- 获取 Figma API Key:
- 登录 Figma → 设置 → 个人访问令牌
- 创建 Figma 文件并记录文件 ID
2. 配置步骤
bash
# 1. 克隆仓库
git clone https://github.com/your-repo/figma-reading-prototype.git
# 2. 进入项目目录
cd figma-reading-prototype
# 3. 安装依赖
npm install axios dotenv
# 4. 创建环境文件
echo "FIGMA_API_KEY=your_figma_api_key" > .env
# 5. 更新配置文件
# 修改 cursor.config.js 中的 fileId 和组件 ID
# 6. 运行程序
node main.js
3. 进阶配置选项
在 cursor.config.js
中可配置:
javascript
// 高级样式配置
styles: {
colors: {
primary: '#4361EE',
secondary: '#F1F5F9',
success: '#10B981',
error: '#EF4444',
background: '#FFFFFF'
},
typography: {
fontFamily: 'Inter, sans-serif',
fontSize: {
title: 24,
question: 18,
option: 16,
feedback: 14
}
},
spacing: {
questionMargin: 40,
optionGap: 20,
sectionPadding: 30
}
},
// 交互行为配置
interactions: {
animation: {
optionSelect: 'spring',
feedbackReveal: 'fade-in'
},
timings: {
feedbackDelay: 300,
transitionDuration: 500
}
}
故障排除
常见问题解决
问题 | 解决方案 |
---|---|
Figma API 连接失败 | 检查 API Key 和网络连接 |
组件 ID 无效 | 在 Figma 中验证组件 ID |
题目生成格式错误 | 调整 AI 提示词或使用后备生成方法 |
原型布局错位 | 检查 MCP 框架结构和坐标计算 |
交互功能不工作 | 验证 Figma 原型交互设置 |
调试建议
- 启用详细日志:
javascript
// 在 main.js 开头添加
process.env.DEBUG = 'figma-integration*';
- 使用测试模式:
javascript
// 在 cursor.config.js 中添加
testMode: true,
testQuestions: [...] // 预定义测试题目
总结
通过以上配置,Cursor 能够与 Figma MCP 深度集成,实现以下功能:
- 智能题目解析:自动从文本中提取阅读理解题目
- 动态原型生成:在 Figma 中创建交互式学习界面
- 个性化配置:通过 MCP 控制样式和布局
- 交互逻辑实现:添加答题、反馈和进度功能
此方案特别适用于教育科技产品开发,能够将文本教材快速转化为交互式学习体验,大幅提升内容制作效率。实际部署时,建议结合具体教育场景调整题目生成算法和交互设计。