@open-pencil/mcp 0.3.2

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/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@open-pencil/mcp",
3
+ "version": "0.3.2",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "main": "./src/server.ts",
7
+ "bin": {
8
+ "openpencil-mcp": "./src/index.ts",
9
+ "openpencil-mcp-http": "./src/http.ts"
10
+ },
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/open-pencil/open-pencil.git",
17
+ "directory": "packages/mcp"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public",
21
+ "provenance": true
22
+ },
23
+ "dependencies": {
24
+ "@modelcontextprotocol/sdk": "^1.25.2",
25
+ "@open-pencil/core": "workspace:*",
26
+ "canvaskit-wasm": "^0.40.0",
27
+ "hono": "^4.11.4",
28
+ "zod": "^3.25.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^22.0.0"
32
+ }
33
+ }
package/src/http.ts ADDED
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import { randomUUID } from 'node:crypto'
3
+ import { readFile } from 'node:fs/promises'
4
+
5
+ import { Hono } from 'hono'
6
+ import { cors } from 'hono/cors'
7
+ import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'
8
+
9
+ import { createServer } from './server.js'
10
+
11
+ const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf-8'))
12
+
13
+ const sessions = new Map<string, { server: ReturnType<typeof createServer>; transport: WebStandardStreamableHTTPServerTransport }>()
14
+
15
+ async function getOrCreateSession(sessionId?: string) {
16
+ if (sessionId && sessions.has(sessionId)) {
17
+ return sessions.get(sessionId)!
18
+ }
19
+
20
+ const id = sessionId ?? randomUUID()
21
+ const server = createServer(pkg.version)
22
+ const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: () => id })
23
+ await server.connect(transport)
24
+ sessions.set(id, { server, transport })
25
+ return { server, transport }
26
+ }
27
+
28
+ const app = new Hono()
29
+
30
+ app.use('*', cors({
31
+ origin: '*',
32
+ allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
33
+ allowHeaders: ['Content-Type', 'mcp-session-id', 'Last-Event-ID', 'mcp-protocol-version'],
34
+ exposeHeaders: ['mcp-session-id', 'mcp-protocol-version']
35
+ }))
36
+
37
+ app.get('/health', (c) => c.json({ status: 'ok', version: pkg.version, tools: 29 }))
38
+
39
+ app.all('/mcp', async (c) => {
40
+ const sessionId = c.req.header('mcp-session-id') ?? undefined
41
+ const { transport } = await getOrCreateSession(sessionId)
42
+ return transport.handleRequest(c.req.raw)
43
+ })
44
+
45
+ const port = parseInt(process.env.PORT ?? '3100', 10)
46
+
47
+ const isBun = typeof globalThis.Bun !== 'undefined'
48
+
49
+ if (isBun) {
50
+ Bun.serve({ fetch: app.fetch, port })
51
+ } else {
52
+ const { serve } = await import('@hono/node-server')
53
+ serve({ fetch: app.fetch, port })
54
+ }
55
+
56
+ console.log(`OpenPencil MCP server v${pkg.version}`)
57
+ console.log(` Health: http://localhost:${port}/health`)
58
+ console.log(` MCP: http://localhost:${port}/mcp`)
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises'
3
+
4
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
5
+
6
+ import { createServer } from './server.js'
7
+
8
+ const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf-8'))
9
+ const server = createServer(pkg.version)
10
+
11
+ const transport = new StdioServerTransport()
12
+ await server.connect(transport)
package/src/server.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { readFile, writeFile } from 'node:fs/promises'
2
+
3
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
4
+ import { z } from 'zod'
5
+
6
+ import { ALL_TOOLS, FigmaAPI, parseFigFile, computeAllLayouts, SceneGraph } from '@open-pencil/core'
7
+
8
+ import type { ToolDef, ParamDef, ParamType } from '@open-pencil/core'
9
+
10
+ type McpResult = { content: { type: 'text'; text: string }[]; isError?: boolean }
11
+
12
+ function ok(data: unknown): McpResult {
13
+ return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }
14
+ }
15
+
16
+ function fail(e: unknown): McpResult {
17
+ const msg = e instanceof Error ? e.message : String(e)
18
+ return { content: [{ type: 'text', text: JSON.stringify({ error: msg }) }], isError: true }
19
+ }
20
+
21
+ function paramToZod(param: ParamDef): z.ZodTypeAny {
22
+ const typeMap: Record<ParamType, () => z.ZodTypeAny> = {
23
+ string: () =>
24
+ param.enum
25
+ ? z.enum(param.enum as [string, ...string[]]).describe(param.description)
26
+ : z.string().describe(param.description),
27
+ number: () => {
28
+ let s = z.number()
29
+ if (param.min !== undefined) s = s.min(param.min)
30
+ if (param.max !== undefined) s = s.max(param.max)
31
+ return s.describe(param.description)
32
+ },
33
+ boolean: () => z.boolean().describe(param.description),
34
+ color: () => z.string().describe(param.description),
35
+ 'string[]': () => z.array(z.string()).min(1).describe(param.description)
36
+ }
37
+
38
+ const schema = typeMap[param.type]()
39
+ return param.required ? schema : schema.optional()
40
+ }
41
+
42
+ export function createServer(version: string): McpServer {
43
+ const server = new McpServer({ name: 'open-pencil', version })
44
+
45
+ let graph: SceneGraph | null = null
46
+ let currentPageId: string | null = null
47
+
48
+ function makeFigma(): FigmaAPI {
49
+ if (!graph) throw new Error('No document loaded. Use open_file or new_document first.')
50
+ const api = new FigmaAPI(graph)
51
+ if (currentPageId) api.currentPage = api.wrapNode(currentPageId)
52
+ return api
53
+ }
54
+
55
+ function registerTool(def: ToolDef) {
56
+ const shape: Record<string, z.ZodTypeAny> = {}
57
+ for (const [key, param] of Object.entries(def.params)) {
58
+ shape[key] = paramToZod(param)
59
+ }
60
+
61
+ server.registerTool(def.name, { description: def.description, inputSchema: z.object(shape) }, async (args) => {
62
+ try {
63
+ const result = await def.execute(makeFigma(), args as Record<string, unknown>)
64
+ return ok(result)
65
+ } catch (e) {
66
+ return fail(e)
67
+ }
68
+ })
69
+ }
70
+
71
+ server.registerTool(
72
+ 'open_file',
73
+ {
74
+ description: 'Open a .fig file for editing. Must be called before using other tools.',
75
+ inputSchema: z.object({ path: z.string().describe('Absolute path to a .fig file') })
76
+ },
77
+ async ({ path: filePath }) => {
78
+ try {
79
+ const buf = await readFile(filePath)
80
+ graph = await parseFigFile(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))
81
+ computeAllLayouts(graph)
82
+ const pages = graph.getPages()
83
+ currentPageId = pages[0]?.id ?? null
84
+ return ok({ pages: pages.map((p) => ({ id: p.id, name: p.name })), currentPage: pages[0]?.name })
85
+ } catch (e) {
86
+ return fail(e)
87
+ }
88
+ }
89
+ )
90
+
91
+ server.registerTool(
92
+ 'save_file',
93
+ {
94
+ description: 'Save the current document to a .fig file.',
95
+ inputSchema: z.object({ path: z.string().describe('Absolute path to save the .fig file') })
96
+ },
97
+ async ({ path: filePath }) => {
98
+ try {
99
+ if (!graph) throw new Error('No document loaded')
100
+ const { exportFigFile } = await import('@open-pencil/core')
101
+ const data = await exportFigFile(graph)
102
+ await writeFile(filePath, new Uint8Array(data))
103
+ return ok({ saved: filePath, bytes: data.byteLength })
104
+ } catch (e) {
105
+ return fail(e)
106
+ }
107
+ }
108
+ )
109
+
110
+ server.registerTool(
111
+ 'new_document',
112
+ {
113
+ description: 'Create a new empty document with a blank page.',
114
+ inputSchema: z.object({})
115
+ },
116
+ async () => {
117
+ try {
118
+ graph = new SceneGraph()
119
+ const pages = graph.getPages()
120
+ currentPageId = pages[0]?.id ?? null
121
+ return ok({ page: pages[0]?.name, id: currentPageId })
122
+ } catch (e) {
123
+ return fail(e)
124
+ }
125
+ }
126
+ )
127
+
128
+ for (const tool of ALL_TOOLS) {
129
+ registerTool(tool)
130
+ }
131
+
132
+ return server
133
+ }