openpencil/server/api/ai/mcp-install.ts
Kayshen Xu aac025f3f4 V0.3.1 (#25)
* feat(mcp): enhance document management and design tools

- Updated `openDocument` to always re-fetch the live canvas, ensuring user edits are captured.
- Introduced new tools: `get_design_prompt` for retrieving design guidelines and `batch_design` for executing multiple design operations using a DSL.
- Improved `handleInsertNode` and `handleUpdateNode` to include validation for node data and return the final node state after operations.
- Enhanced design prompt with detailed PenNode schema and layout rules for better AI-generated designs.
- Added validation functions to ensure node data integrity during CRUD operations.
- Updated `handleOpenDocument` to provide context-aware design prompts based on document content.

* feat(electron): enhance build configuration and auto-update functionality

- Updated `electron-builder.yml` to include artifact naming conventions for Windows and Linux builds.
- Enhanced NSIS installer settings to create desktop and start menu shortcuts.
- Improved path handling for GUI applications on Windows to ensure proper environment variable inheritance.
- Refactored auto-update logic in `main.ts` to streamline update checks and improve error handling.
- Added new IPC handlers for managing pending file paths and improved file handling during application startup.
- Updated `use-electron-menu` hook to handle additional menu structures and improve document loading logic.

* chore: bump version to 0.3.1 and update project description

- Updated version in package.json to 0.3.1.
- Enhanced project description to highlight OpenPencil as the world's first open-source AI-native vector design tool featuring concurrent Agent Teams and Design-as-Code capabilities.
- Refactored auto-updater to utilize constants for GitHub repository details, improving maintainability.
- Introduced a new constants file to centralize shared values for the Electron application, enhancing code clarity and reducing duplication.
- Updated various components to use new constants for port file handling and window dimensions, ensuring consistency across the application.

* feat(ai): clarify mobile design guidelines and mockup usage

- Updated design guidelines to emphasize that "mobile" requests should generate actual mobile-sized screens (375x812) instead of desktop mockups.
- Added critical notes regarding the use of phone mockups, specifying they should only be used for marketing showcases and not for functional mobile screens.
- Enhanced clarity on sizing and layout rules for mobile and web designs to ensure consistent application of design principles.

* fix(canvas): improve text centering, layout inference, and Pencil format rendering

- Resolve fit-content parent dimensions in computeLayoutPositions instead of
  using 0 (which caused negative available space and broken child positioning)
- Reduce text width estimation minimum from 20px to 1px to fix centering of
  narrow single-character text in fixed-size centered frames
- Add inferLayout() to detect padding-only frames as layout containers, so
  padding offsets are applied to children (fixes badge text ignoring padding)
- Use Fabric's fontSize * 1.13 for single-line text height in centering
  calculations instead of fontSize * lineHeight
- Add fontWeight propagation to text width/height estimation functions
- Refine defaultLineHeight() tiers for better Pencil format compatibility
- Support Pencil's singular `effect` property alongside `effects` array
- Handle plain color strings in fill/stroke resolution for Pencil format
- Add directional stroke rendering as synthetic border rectangles
- Add icon_font node type rendering via lookupIconByName
- Fix z-order reconciliation to use fresh canvas object map after text recreation
- Fix canvas initialization race: defer reference tracking until canvas is ready
- Resolve $variable references with circular reference guards

* feat(types): add icon_font node type with panel and store support

- Add IconFontNode type to pen.ts for icon_font nodes storing iconFontName
- Extend property panel and icon section to recognize icon_font nodes
- Add icon_font type icon in layer panel
- Support icon_font in document tree utilities

* feat(ai): improve design generation accuracy and validation

- Add pre-validation pass to fix text with explicit pixel height to fit_content
- Enhance validation tree dump with textGrowth and lineHeight fields
- Update orchestrator prompts with structural patterns from Pencil analysis
- Simplify role-resolver defaults to match Pencil conventions
- Only force textGrowth=fixed-width on text >15 chars in streaming insertion

* feat(ai): optimize generation pipeline and fix streaming layout

- Disable LLM validation layer (pre-validation heuristics still run)
- Remove visual-ref pipeline (3 fewer LLM calls per generation)
- Compress sub-agent prompt and design principles (~70% smaller)
- Remove width>480 guards so mobile gets root frame height expansion
- Add gap field to orchestrator rootFrame format and guidance
- Default icon_font nodes to lucide family in generation heuristics

* feat(ai): load full Lucide icon set and default icon_font to lucide

- Load all 1,729 Lucide icons as primary set (replaces 286 hand-picked)
- Keep Feather as fallback for unmatched names
- Default iconFontFamily to 'lucide' during .pen file normalization

* feat(codegen): add icon_font support to all 8 code generators

Output Lucide icon references instead of 'Unknown node' comments.
React/RN use component syntax, HTML/Vue/Svelte use data-lucide,
Flutter/SwiftUI/Compose use framework-native icon APIs.

* feat(panels): replace product card quick action with food app homepage

* feat(electron): implement preferences management and app storage abstraction

- Introduced a new preferences management system in Electron, replacing localStorage with a JSON-based preferences file.
- Added IPC handlers for getting, setting, and removing preferences, ensuring data persistence across sessions.
- Created an app storage utility to provide a consistent API for accessing preferences in both Electron and web environments.
- Updated various components and stores to utilize the new app storage system for improved data handling and synchronization.
- Enhanced the initialization process to load preferences at startup, ensuring a seamless user experience.

---------

Co-authored-by: Fini <fini.yang@gmail.com>
2026-03-09 22:02:43 +08:00

178 lines
5.3 KiB
TypeScript

import { defineEventHandler, readBody, setResponseHeaders } from 'h3'
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import { readFile, writeFile, mkdir } from 'node:fs/promises'
import { existsSync } from 'node:fs'
const MCP_DEFAULT_PORT = 3100
interface InstallBody {
tool: string
action: 'install' | 'uninstall'
transportMode?: 'stdio' | 'http' | 'both'
httpPort?: number
}
interface InstallResult {
success: boolean
error?: string
configPath?: string
}
const MCP_SERVER_NAME = 'openpencil'
/**
* Resolve the absolute path to the compiled MCP server.
* In dev: <project>/dist/mcp-server.cjs
* In production (Electron): <resources>/mcp-server.cjs
*/
function resolveMcpServerPath(): string {
// Electron production: extraResources places it in resourcesPath
const electronResources = process.env.ELECTRON_RESOURCES_PATH
if (electronResources) {
const electronPath = join(electronResources, 'mcp-server.cjs')
if (existsSync(electronPath)) return electronPath
}
// Try dist/ in the project root (dev + web build)
const projectDist = resolve(process.cwd(), 'dist', 'mcp-server.cjs')
if (existsSync(projectDist)) return projectDist
// Fallback: try relative to this file
const serverDist = resolve(__dirname, '..', '..', '..', 'dist', 'mcp-server.cjs')
if (existsSync(serverDist)) return serverDist
return projectDist // Return expected path even if not yet compiled
}
function buildMcpServerEntry(
serverPath: string,
transportMode: 'stdio' | 'http' | 'both' = 'stdio',
httpPort = MCP_DEFAULT_PORT,
): { command: string; args: string[] } {
switch (transportMode) {
case 'http':
return { command: 'node', args: [serverPath, '--http', '--port', String(httpPort)] }
case 'both':
return { command: 'node', args: [serverPath, '--http', '--port', String(httpPort), '--stdio'] }
default:
return { command: 'node', args: [serverPath] }
}
}
/** Config file locations and formats for each CLI tool. */
interface CliConfigDef {
configPath: () => string
read: (filePath: string) => Promise<Record<string, any>>
write: (filePath: string, config: Record<string, any>) => Promise<void>
}
function installMcpServer(
config: Record<string, any>,
serverPath: string,
transportMode?: 'stdio' | 'http' | 'both',
httpPort?: number,
): Record<string, any> {
return {
...config,
mcpServers: {
...(config.mcpServers ?? {}),
[MCP_SERVER_NAME]: buildMcpServerEntry(serverPath, transportMode, httpPort),
},
}
}
function uninstallMcpServer(config: Record<string, any>): Record<string, any> {
const servers = { ...(config.mcpServers ?? {}) }
delete servers[MCP_SERVER_NAME]
return { ...config, mcpServers: Object.keys(servers).length > 0 ? servers : undefined }
}
const CLI_CONFIGS: Record<string, CliConfigDef> = {
'claude-code': {
configPath: () => join(homedir(), '.claude.json'),
read: readJsonConfig,
write: writeJsonConfig,
},
'codex-cli': {
configPath: () => join(homedir(), '.codex', 'config.json'),
read: readJsonConfig,
write: writeJsonConfig,
},
'gemini-cli': {
configPath: () => join(homedir(), '.gemini', 'settings.json'),
read: readJsonConfig,
write: writeJsonConfig,
},
'opencode-cli': {
configPath: () => join(homedir(), '.opencode', 'config.json'),
read: readJsonConfig,
write: writeJsonConfig,
},
'kiro-cli': {
configPath: () => join(homedir(), '.kiro', 'settings.json'),
read: readJsonConfig,
write: writeJsonConfig,
},
'copilot-cli': {
configPath: () => join(homedir(), '.config', 'github-copilot', 'mcp.json'),
read: readJsonConfig,
write: writeJsonConfig,
},
}
async function readJsonConfig(filePath: string): Promise<Record<string, any>> {
try {
const text = await readFile(filePath, 'utf-8')
return JSON.parse(text)
} catch {
return {}
}
}
async function writeJsonConfig(
filePath: string,
config: Record<string, any>,
): Promise<void> {
const dir = join(filePath, '..')
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true })
}
await writeFile(filePath, JSON.stringify(config, null, 2) + '\n', 'utf-8')
}
/**
* POST /api/ai/mcp-install
* Install or uninstall the openpencil MCP server into a CLI tool's config.
*/
export default defineEventHandler(async (event) => {
const body = await readBody<InstallBody>(event)
setResponseHeaders(event, { 'Content-Type': 'application/json' })
if (!body?.tool || !body?.action) {
return { success: false, error: 'Missing tool or action field' } satisfies InstallResult
}
const cliConfig = CLI_CONFIGS[body.tool]
if (!cliConfig) {
return { success: false, error: `Unknown CLI tool: ${body.tool}` } satisfies InstallResult
}
try {
const configPath = cliConfig.configPath()
const config = await cliConfig.read(configPath)
const serverPath = resolveMcpServerPath()
const updated =
body.action === 'install'
? installMcpServer(config, serverPath, body.transportMode, body.httpPort)
: uninstallMcpServer(config)
await cliConfig.write(configPath, updated)
return { success: true, configPath } satisfies InstallResult
} catch (err) {
return {
success: false,
error: err instanceof Error ? err.message : String(err),
} satisfies InstallResult
}
})