figura-mcp 0.17.0 → 0.17.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.
Files changed (2) hide show
  1. package/dist/index.js +4 -4
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as LQ}from"node:module";var PQ=LQ(import.meta.url);import{promises as R,readFileSync as cQ}from"node:fs";import{homedir as xQ}from"node:os";import{dirname as dQ,join as u}from"node:path";import BQ from"axios";import{McpServer as lQ}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as gQ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as $}from"zod";function d(Q,Z,W){return Q.toUpperCase()!=="GET"&&Z==="global"&&!W}function l(Q){let Z={name:Q.name};if(Q.appDescription!==void 0)Z.appDescription=Q.appDescription;if(Q.tokensBlock!==void 0)Z.tokensBlock=Q.tokensBlock;if(Q.surfaces!==void 0)Z.surfaces=Q.surfaces;if(Q.identity!==void 0)Z.identity=Q.identity;if(Q.platforms!==void 0)Z.platforms=Q.platforms;if(Q.proseSource!==void 0)Z.proseSource=Q.proseSource;return Z}import{createHash as RQ}from"node:crypto";import{existsSync as AQ,readdirSync as w,readFileSync as k}from"node:fs";import{homedir as jQ}from"node:os";import{fileURLToPath as g}from"node:url";import{dirname as NQ,join as V,relative as OQ,sep as FQ}from"node:path";var _Q=".figura-version";var i="fig";function o(Q){let Z=[],W=(K)=>{for(let X of w(K,{withFileTypes:!0})){let Y=V(K,X.name);if(X.isDirectory())W(Y);else if(X.isFile())Z.push(Y)}};try{for(let K of w(Q,{withFileTypes:!0}))if(K.isDirectory()&&K.name===i)W(V(Q,K.name))}catch{return null}if(Z.length===0)return null;let q=RQ("sha256");for(let K of Z.sort()){let X=OQ(Q,K).split(FQ).join("/");q.update(X),q.update("\x00"),q.update(k(K)),q.update("\x00")}return q.digest("hex").slice(0,16)}function n(Q){try{return w(Q,{withFileTypes:!0}).some((Z)=>Z.isDirectory()&&AQ(V(Q,Z.name,"SKILL.md")))}catch{return!1}}function t(){let Q=[new URL("../skills/",import.meta.url),new URL("../../skills/",import.meta.url)].map((W)=>g(W));for(let W of Q)if(n(W))return W;let Z=g(new URL("./",import.meta.url));for(let W=0;W<8;W++){let q=V(Z,".claude","skills");if(n(q))return q;let K=NQ(Z);if(K===Z)break;Z=K}return null}function EQ(){let Q=t();return Q?o(Q):null}function IQ(){let Q=t();if(!Q)return null;try{return JSON.parse(k(V(Q,"skills.json"),"utf8")).skills?.[i]?.version??null}catch{return null}}function TQ(Q){try{return k(V(Q,_Q),"utf8").trim()||null}catch{return null}}function wQ(Q,Z){let W=(X)=>{let Y=/^\D*(\d+)\.(\d+)\.(\d+)/.exec(X.trim());return Y?[Number(Y[1]),Number(Y[2]),Number(Y[3])]:null},q=W(Q),K=W(Z);if(!q||!K)return!1;for(let X=0;X<3;X++){if(q[X]>K[X])return!0;if(q[X]<K[X])return!1}return!1}function kQ(Q){let{stamp:Z,installedHash:W,bundledHash:q,referenceVersion:K}=Q;if(W==null)return"absent";if(q!=null&&W===q&&Z===K)return"pristine";if(Z!=null&&K!=null&&wQ(K,Z))return"stale";return"modified"}function SQ(Q,Z=V(jQ(),".claude","skills")){try{let W=TQ(Z),q=o(Z),K=EQ(),X=kQ({stamp:W,installedHash:q,bundledHash:K,referenceVersion:IQ()});return{version:W,hash:q,status:X}}catch{return{version:null,hash:null,status:"absent"}}}function N(Q){return{channel:"mcp",mcpVersion:Q,skill:SQ(Q)}}function s(Q){if(Q==="modified")return"⚠ your fig skill is MODIFIED (differs from figura-cli's shipped version) — run `figura install` to restore it";if(Q==="stale")return"⚠ your fig skill is outdated (behind figura-cli) — run `figura install` to reinstall it";return null}import{promises as S}from"node:fs";import{homedir as b}from"node:os";import{join as f}from"node:path";var bQ=604800000,fQ=21600000;function O(Q){try{let Z=new URL(Q);return`${Z.protocol}//${Z.host}`.toLowerCase()}catch{return Q.trim().toLowerCase().replace(/\/+$/,"")}}async function y(Q,Z="latest",W){let q=await import("package-manager-detector"),K=W!==void 0?W:q.getUserAgent()??null;if(K){let X=q.resolveCommand(K,"global",[`${Q}@${Z}`]);if(X)return{command:`${X.command} ${X.args.join(" ")}`,generic:!1}}return{command:`npm i -g ${Q}@${Z}`,generic:!0}}function v(Q){return Q.generic?`Update with your package manager's global install, e.g. ${Q.command}`:`Run: ${Q.command}`}function r(Q){if(Q==="figura-cli")return{pkg:"figura-cli",cacheFile:f(b(),".figura","update-check.json"),minHeader:"x-figura-min-cli",latestHeader:"x-figura-latest-cli",label:"figura",installPkg:"figura-cli"};return{pkg:"figura-mcp",cacheFile:f(b(),".figura","update-check-mcp.json"),minHeader:"x-figura-min-mcp",latestHeader:"x-figura-latest-mcp",label:"figura-mcp",installPkg:"figura-mcp"}}function yQ(Q,Z,W){if(!Z.min&&!Z.latest)return null;let q={...Q},K=!1,X=(Y)=>typeof Y!=="number"||W-Y>=fQ;if(Z.min&&(Q.min!==Z.min||X(Q.minAt)))q.min=Z.min,q.minAt=W,K=!0;if(Z.latest&&(Q.latest!==Z.latest||X(Q.latestAt)))q.latest=Z.latest,q.latestAt=W,K=!0;return K?q:null}function a(Q,Z){return typeof Q==="number"&&Z-Q<bQ}function z(Q,Z,W){let q=Q.serverAdvice?.[Z];if(!q)return{};return{min:a(q.minAt,W)?q.min:void 0,latest:a(q.latestAt,W)?q.latest:void 0}}function P(Q,Z){let W=(X)=>{let Y=/^\D*(\d+)\.(\d+)\.(\d+)/.exec(X.trim());return Y?[Number(Y[1]),Number(Y[2]),Number(Y[3])]:null},q=W(Q),K=W(Z);if(!q||!K)return!1;for(let X=0;X<3;X++){if(q[X]>K[X])return!0;if(q[X]<K[X])return!1}return!1}function vQ(Q){if(Q.CI)return"ci";if(Q.FIGURA_NO_UPDATE_NOTIFIER==="1"||Q.NO_UPDATE_NOTIFIER==="1")return"opt-out";return null}function zQ(Q,Z,W,q){return`⚠ ${Q.label} ${Z} → ${W} available. ${q}`}function mQ(Q,Z,W,q){return`⚠ ${Q.label} ${Z} is below the minimum supported ${W} — `+`some tools may fail. ${q}`}function e(Q,Z,W){let q=Q.latest,K=z(Q,Z,W).latest;if(q&&K)return P(K,q)?K:q;return q??K}function pQ(Q,Z,W,q,K=Date.now()){let X=z(W,q,K).min;if(X&&P(X,Z))return{level:"firm",target:X};let Y=e(W,q,K);if(Y&&P(Y,Z))return{level:"stale",target:Y};return null}function hQ(Q,Z,W,q){return Z.level==="firm"?`Your ${Q.label} ${W} is below the minimum supported ${Z.target} — `+`some Figura tools may fail. Ask the user to update: ${q}`:`${Q.label} ${W} → ${Z.target} available. Ask the user to update: ${q}`}async function QQ(Q){try{let Z=Q.cache??await m(Q.stream),W=pQ(Q.stream,Q.current,Z,Q.origin,Q.now);if(!W)return null;let q=v(await y(Q.stream.installPkg,"latest",Q.agent));return hQ(Q.stream,W,Q.current,q)}catch{return null}}function ZQ(Q,Z){let W=Z(Q.minHeader)?.trim(),q=Z(Q.latestHeader)?.trim();return{min:W||void 0,latest:q||void 0}}async function $Q(Q,Z,W,q=Date.now()){try{if(!W.min&&!W.latest)return;let K=await m(Q),X={...K.serverAdvice??{}},Y=yQ(X[Z]??{},W,q);if(!Y)return;X[Z]=Y,await uQ(Q,{...K,serverAdvice:X})}catch{}}async function m(Q){try{let Z=JSON.parse(await S.readFile(Q.cacheFile,"utf8"));return Z&&typeof Z==="object"?Z:{}}catch{return{}}}async function uQ(Q,Z){await S.mkdir(f(b(),".figura"),{recursive:!0,mode:448}),await S.writeFile(Q.cacheFile,JSON.stringify(Z,null,2)+`
3
- `,{mode:384})}async function WQ(Q,Z,W,q=process.env,K=Date.now()){try{if(vQ(q))return;let X=await m(Z),Y=z(X,W,K).min;if(Y&&P(Y,Q)){let D=v(await y(Z.installPkg));process.stderr.write(mQ(Z,Q,Y,D)+`
4
- `);return}let M=e(X,W,K);if(M&&P(M,Q)){let D=v(await y(Z.installPkg));process.stderr.write(zQ(Z,Q,M,D)+`
5
- `)}}catch{}}var nQ=$.object({name:$.string(),hex:$.string().describe("3/4/6/8-digit hex, e.g. #1FB6A6 or #1FB6A6FF."),role:$.string().optional(),meaning:$.string().optional()}).passthrough(),iQ=$.object({id:$.string().optional(),rule:$.string()}).passthrough(),oQ=$.object({colors:$.array(nQ).optional(),gradient:$.string().optional(),type:$.object({families:$.record($.string()).optional(),ramp:$.array($.number()).optional(),rules:$.string().optional()}).passthrough().optional(),spacing:$.array($.number()).optional(),radius:$.array($.number()).optional(),voice:$.object({nouns:$.array($.string()).optional(),promise:$.string().optional(),lines:$.array($.string()).optional(),tone:$.string().optional()}).passthrough().optional(),forbidden:$.array(iQ).optional()}).passthrough(),p=$.object({components:$.array($.object({name:$.string(),spec:$.string()}).passthrough()).optional(),icons:$.string().optional(),layout:$.string().optional(),surfaces:$.array($.string()).optional(),bans:$.array($.string()).optional(),tokensBlock:$.string().optional()}).passthrough(),tQ=$.object({mobile:p.optional(),web:p.optional(),desktop:p.optional()}).passthrough(),sQ="https://api.figura.so",aQ="mcp",qQ=u(xQ(),".figura","config.json"),rQ=u(".figura","config.json");async function KQ(Q){try{let Z=JSON.parse(await R.readFile(Q,"utf8"));if(Z&&typeof Z==="object")return Z}catch{}return{}}async function eQ(Q=process.cwd()){let Z=xQ(),W=Q;for(;;){if(W!==Z){let K=u(W,rQ);try{return await R.access(K),K}catch{}}let q=dQ(W);if(q===W)return null;W=q}}async function E(){let Q=await eQ(),Z=Q?await KQ(Q):{},W=await KQ(qQ),q={...W,...Z},K=process.env.FIGURA_TOKEN||q.token||void 0,X=process.env.FIGURA_TOKEN?"env":Z.token?"project":W.token?"global":"none",Y=(process.env.FIGURA_API_URL||q.apiUrl||sQ).replace(/\/+$/,"");return{token:K,apiUrl:Y,team:q.team,source:X,configPath:X==="project"?Q:X==="global"?qQ:null}}async function J(Q,Z={}){let W=await E(),q=W.token;if(!q)throw Error("No Figura token. Run `figura link` in this repo (or `figura login`, or set FIGURA_TOKEN).");let K=(Z.method??"GET").toUpperCase();if(d(K,W.source,process.env.FIGURA_ALLOW_GLOBAL==="1"))throw Error(`this project isn't linked to a Figura team — the global credential${W.team?` (team '${W.team}')`:""} would receive this write. Ask the user to run \`figura link\` in this repo (or set FIGURA_ALLOW_GLOBAL=1 to use the global team deliberately).`);let X=`${W.apiUrl}${Q.startsWith("/")?"":"/"}${Q}`,Y={Accept:"application/json",Authorization:`Bearer ${q}`,"X-Figura-Source":aQ},M;if(Z.body!==void 0)Y["Content-Type"]="application/json",M=JSON.stringify(Z.body);let D=await BQ.request({url:X,method:Z.method??"GET",headers:Y,data:M,validateStatus:()=>!0,transformRequest:[(C)=>C],transformResponse:[(C)=>C]});{let C=D.headers,MQ=(UQ)=>{let c=C?.[UQ];return typeof c==="string"?c:void 0};$Q(_,O(W.apiUrl),ZQ(_,MQ))}let T=typeof D.data==="string"?D.data:"",H=void 0;if(T)try{H=JSON.parse(T)}catch{H=T}if(D.status<200||D.status>=300){let C=H&&typeof H==="object"&&H!==null&&"error"in H?String(H.error):typeof H==="string"&&H?H:D.statusText||`HTTP ${D.status}`;throw Error(`${C} (HTTP ${D.status})`)}return H}var XQ=2500,QZ=600000,ZZ=60000,YQ=(Q)=>new Promise((Z)=>setTimeout(Z,Q));async function $Z(Q){let Z=Date.now(),W=null;for(;;){let q;try{q=await J(`/v1/jobs/${encodeURIComponent(Q)}`),W=null}catch(K){if(W??=Date.now(),Date.now()-W>=ZZ){let X=K instanceof Error?K.message:String(K);throw Error(`Lost contact with the Figura API while waiting for job ${Q} (${X}). `+`The job may still complete — resume by checking GET /v1/jobs/${Q} instead of regenerating.`)}await YQ(XQ);continue}if(q.status==="done")return q;if(q.status==="error")throw Error(q.error||"The generation job failed. Please retry.");if(Date.now()-Z>QZ)throw Error(`Timed out waiting for job ${Q} — it may still complete; `+`check GET /v1/jobs/${Q} instead of regenerating.`);await YQ(XQ)}}function G(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function B(Q){return{content:[{type:"text",text:Q instanceof Error?Q.message:String(Q)}],isError:!0}}var JQ=!1;async function A(Q){try{if(JQ)return Q;if(!Q||typeof Q!=="object"||Array.isArray(Q))return Q;let{apiUrl:Z}=await E(),W=await QQ({stream:_,current:L,origin:O(Z)});if(!W)return Q;return JQ=!0,{...Q,notice:W}}catch{return Q}}function F(Q,Z){if(!Q||typeof Q!=="object"||Array.isArray(Q))return Q;let W=s(Z);if(!W)return Q;return{...Q,skillWarning:W}}var U=()=>$.string().optional().describe("Product area / surface the fig belongs to, e.g. 'dashboard', 'settings', 'onboarding'. Free text."),j=["portrait","landscape","both"],I=["single","compare","variations"],{version:L,name:WZ}=(()=>{try{let Q=JSON.parse(cQ(new URL("../package.json",import.meta.url),"utf8"));return{version:typeof Q.version==="string"?Q.version:"0.0.0",name:typeof Q.name==="string"?Q.name:void 0}}catch{return{version:"0.0.0"}}})(),_=r(WZ),x=new lQ({name:"figura",version:L});x.registerTool("figura_whoami",{title:"Figura: whoami",description:"Return the identity (team, actor, scopes) for the configured Figura token, plus `binding` — which config tier supplied it (env | project | global). A `global` binding means this project is not linked to a team and writes will be refused; ask the user to run `figura link` in the repo.",inputSchema:{}},async()=>{try{let Q=await J("/v1/whoami"),{source:Z,configPath:W}=await E();return G(await A({...Q,binding:{source:Z,configPath:W}}))}catch(Q){return B(Q)}});x.registerTool("figura_set_brand",{title:"Figura: set brand profile",description:'Set (upsert) the team brand profile that the fig generator renders against. Use this to "introduce a repo to Figura": scan the codebase for its design system, synthesize the brand, then push it here. `name` is required. PREFERRED — send a STRUCTURED brand: `identity` (shared colors/gradient/type/spacing/radius/voice/forbidden) + `platforms` (per-platform surfaces, keys mobile|web|desktop) — this makes the brand structured + addressable (is_structured=true). LEGACY/fallback — send prose: `tokensBlock` (freeform design-token reference) + `surfaces` (the product\'s own key areas). `appDescription` is a one-clause product summary. This is a partial merge — fields you omit keep their saved value; a structured write clears the dormant prose columns and a prose write downgrades to legacy. Editing the team brand — confirm with the user before calling.',inputSchema:{name:$.string().describe("Brand / app name (required)."),appDescription:$.string().optional().describe("One clause on what the product is + who it is for."),identity:oQ.optional().describe("STRUCTURED shared identity (platform-agnostic): { colors:[{name,hex,role?,meaning?}], gradient?, type?:{families?:{slot:font},ramp?:number[],rules?}, spacing?:number[], radius?:number[], voice?:{nouns?,promise?,lines?,tone?}, forbidden?:[{id?,rule}] }. hex is 3/4/6/8 digits. Sending this makes the brand STRUCTURED (is_structured=true). Validated server-side."),platforms:tQ.optional().describe("STRUCTURED per-platform surfaces — a map keyed by mobile|web|desktop; include ONLY the platforms the product targets: { <platform>: { components?:[{name,spec}], icons?, layout?, surfaces?:string[], bans?:string[], tokensBlock? } }. `tokensBlock` here is a per-platform escape hatch for guidance that does not fit a structured field."),proseSource:$.string().optional().describe(`The human-readable freeform description this structured brand was authored from — stored as the editable source shown in the web brand editor; NOT used by generation. Send it alongside a structured write so a skill/CLI/MCP-authored brand still seeds the web editor's "Author from a description" textarea (a repo scan should pass the prose it synthesized the brand from; a prose→structured upgrade should pass the original prose).`),tokensBlock:$.string().optional().describe("LEGACY prose fallback: freeform plain-text design-token reference (colors + hex + role, type scale + faces, spacing, gradient, voice/conventions). Prefer `identity`/`platforms`. Injected verbatim into the fig-generation prompt."),surfaces:$.array($.string()).optional().describe(`LEGACY prose fallback: the product's own key areas/sections (e.g. ["Feed", "Settings", "Checkout"]) — read from the repo's real navigation/routes. For a structured brand put surfaces under each platform instead. Pass [] to clear.`)}},async(Q)=>{try{return G(await J("/brand",{method:"PUT",body:l(Q)}))}catch(Z){return B(Z)}});x.registerTool("figura_brand_schema",{title:"Figura: brand schema",description:"Return the JSON Schema for the STRUCTURED brand — the ONE authority (derived server-side from the zod schema PUT /brand validates). Fetch this BEFORE synthesizing a brand for figura_set_brand's `identity`/`platforms`, and author against it so the brand validates first try (strict keys; hex 3/4/6/8 digits; platform keys mobile|web|desktop; no blank array entries). Read-only. Returns { schema }.",inputSchema:{}},async()=>{try{return G(await J("/v1/brand/schema"))}catch(Q){return B(Q)}});var qZ={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml"},h=5242880;function GQ(Q){let Z=Q.split(/[?#]/)[0].split(".").pop()?.toLowerCase()??"";return qZ[Z]}async function DQ(Q,Z){let W,q=Z;if(/^https?:\/\//i.test(Q)){let K=await BQ.get(Q,{responseType:"arraybuffer",maxContentLength:h,timeout:30000});if(W=Buffer.from(K.data).toString("base64"),!q){let X=String(K.headers["content-type"]??"").split(";")[0].trim().toLowerCase();q=X.startsWith("image/")?X:GQ(Q)}}else{let{size:K}=await R.stat(Q);if(K>h)throw Error(`'${Q}' is ${(K/1048576).toFixed(1)}MB — over the ${h/1048576}MB asset limit.`);if(W=(await R.readFile(Q)).toString("base64"),!q)q=GQ(Q)}if(!q)throw Error(`Could not determine an image content-type for '${Q}' — pass contentType (e.g. image/png).`);return{data:W,contentType:q}}async function KZ(Q,Z){let{data:W,contentType:q}=await DQ(Q,Z),K=await J("/v1/assets",{method:"POST",body:{data:W,contentType:q}});if(!K||typeof K.url!=="string")throw Error("Asset upload did not return a URL.");return K.url}var HQ=()=>$.array($.object({source:$.string().describe("The image — a local file path or an http(s) URL (e.g. a screenshot)."),match:$.string().optional().describe('Exact string in the HTML to replace with the hosted URL (defaults to `source` — i.e. write <img src="<source>"> in the HTML).')})).optional().describe("Images to attach: each is uploaded to durable figura hosting (stable non-expiring URL, allowed by the fig CSP) and substituted into the HTML in place of `match`/`source`. Use for real screenshots/photos/logos instead of base64 data-URIs (HTML size cap) or external URLs (expire/CSP-blocked).");async function CQ(Q,Z){if(!Z?.length)return{html:Q,uploaded:[]};let W=Q,q=[];for(let K of Z){let X=K.match??K.source;if(!W.includes(X))throw Error(`images: '${X}' does not occur in the html — reference it (e.g. <img src="${X}">) so it can be swapped for the hosted URL, or set 'match'.`);let Y=await KZ(K.source);W=W.split(X).join(Y),q.push({source:K.source,url:Y})}return{html:W,uploaded:q}}function VQ(Q,Z){if(!Z.length)return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q))return{...Q,assets:Z};return{result:Q,assets:Z}}x.registerTool("figura_create_fig",{title:"Figura: create fig",description:"Create a new visualization from an HTML document — this HOSTS it (the create IS the hosting; there is no separate \"land it in Figura\" step). Every create returns `viewUrl`: ALWAYS a link you can open for approval, whether or not the fig is published — the public share url once published, else a team-scoped viewer link only signed-in teammates can open. The fig lands as a workspace DRAFT (`status: 'draft'`): hosted and viewable, visible to its author, but NOT in the team library and silent for teammates — iterate freely without claiming the team's attention, then COMMIT only the session's final recommendation (`commit: true` on that final create/revise, or figura_commit_fig). Do NOT pass publish:true just to get something viewable — omit it (default false) so the fig lands team-private, open `viewUrl` for review, and only publish when the human wants a link they can share outside the team (figura_publish_fig, once approved). The response also carries `brandWarnings` — a deterministic (no-LLM) colors/fonts/radii/spacing diff against the team's brand tokens, WARN-only (never blocks the create). If it comes back non-empty, read it and consider a figura_revise_fig call that binds the missing tokens before telling the user you're done. To include REAL images (screenshots/photos/logos), pass them via `images` — they are uploaded to durable figura hosting and their stable URLs substituted into the HTML. TIP — injected components: if your HTML shows phone frames (a compare/multi-screen mock), wrap each state in <div class=\"fig-device portrait|landscape\"><div class=\"fig-screen\">…</div><div class=\"fig-di\"></div><div class=\"fig-homebar\"></div></div> — Figura injects accurate iPhone frame CSS at save, BEFORE your <style>, so you normally leave those classes alone; if you do style them your rule wins by cascade (the frame still works), but to shrink frames for an overview grid wrap each frame in the injected `.fig-mini` wrapper (e.g. <div class=\"fig-mini\" style=\"--fig-scale:.34\"> … the .fig-device block … </div>) — it scales the device with transform and reserves the scaled layout box — rather than re-declaring .fig-device width/height or adding transform: scale() yourself (which fights the injected geometry), and never CSS zoom (it leaks unzoomed width into horizontal overflow). Same injection applies to an iOS status bar (<div class=\"fig-statusbar\" data-time=\"9:41\"></div>), a compare control bar (.fig-controls/.fig-seg), and the .frame-web browser window.",inputSchema:{html:$.string().describe("The full HTML document for the visualization."),images:HQ(),title:$.string().optional().describe("Title (otherwise derived from the HTML)."),description:$.string().optional(),area:U(),tags:$.array($.string()).optional(),orientation:$.enum(j).optional(),mode:$.enum(I).optional(),model:$.string().optional().describe("Model attribution."),device:$.string().optional().describe("Catalog iPhone id the fig targets (e.g. 'iphone-16', 'iphone-17-pro', 'iphone-se-3') — keys the injected frame/safe-area geometry."),issue:$.number().optional().describe("Linked issue number."),publish:$.boolean().optional().describe("Publish to a shareable public URL on create (requires a paid plan). Default false — the response's `viewUrl` is already open-able team-privately, so only set this when the human explicitly wants a link they can share outside the team. Share link ONLY — does not commit the fig to the team library (that's `commit`)."),commit:$.boolean().optional().describe("Commit to the team library on create (sends status: 'published'). Default false — the fig lands as a workspace DRAFT: hosted + viewable via `viewUrl`, visible to its author, but not in the team library and silent for teammates. Set true ONLY when this write is the session's final recommendation (the fig the user asked for / signed off on); explorations and intermediate iterations stay drafts. Committing later: figura_commit_fig."),prompt:$.string().optional().describe("OPTIONAL: the brief that produced this HTML, if there was one — you wrote the HTML yourself, so Figura never sees a prompt unless you pass it here. Stored on the fig (DB-only, never stamped into the HTML), and returned by figura_get_fig — lets teammates see 'why' this fig exists.")}},async(Q)=>{try{let{html:Z,uploaded:W}=await CQ(Q.html,Q.images),q={html:Z};for(let X of["title","description","area","tags","orientation","mode","model","device","issue","publish","prompt"])if(Q[X]!==void 0)q[X]=Q[X];if(Q.commit)q.status="published";let K=N(L);return q.toolchain=K,G(F(await A(VQ(await J("/v1/figs",{method:"POST",body:q}),W)),K.skill.status))}catch(Z){return B(Z)}});var XZ=["single","compare","variations","overview-focus","document"];x.registerTool("figura_compose_fig",{title:"Figura: compose fig",description:"PREFERRED way to build a device fig. You write ONLY each screen's CONTENT (the markup inside the phone) + typed params; Figura owns the STRUCTURE — the iPhone frame, the Dynamic Island/notch/home bar, the exact catalog artboard geometry, the REAL safe-area insets, and the composition (grid/diptych/overview). This means the parts that used to drift every few figs — hand-rolled artboards, guessed `--fig-safe-top:59px`, a forgotten `data-device` so no safe machinery stamped — are correct-by-construction: you never write them. Pass `layout` + an ARRAY of `screens`. For every DEVICE layout (single/compare/variations/overview-focus) each screen REQUIRES `device` (a catalog id like 'iphone-16' — fetch figura_fig_devices), `orientation` ('portrait'|'landscape'), and `safeZone` ('respect' = Figura pads your content to the device's real safe insets; 'ignore' = edge-to-edge splash/hero). Each screen's `html` is CONTENT ONLY — do NOT draw a frame, a bezel, a status bar, or safe padding; do NOT set `--fig-safe-*`; do NOT wrap in `.fig-device`. Style your content with brand tokens via `sharedCss` (ONE stylesheet all screens share) + optional per-screen `css`. Layouts: `single` (one frame), `compare` (as-is → proposed diptych — pass label per screen), `variations` (responsive grid + status chips), `overview-focus` (CSS overview⇄focus toggle for arguing a redesign), `document` (NO device framing — brand/overview figs; screens need no device/orientation/safeZone). Lands EXACTLY like figura_create_fig (workspace DRAFT, returns `viewUrl` + `brandWarnings` + `warnings`; commit the session's final pick). For a `document`/exotic hand-authored fig where you need full control of the HTML, use figura_create_fig instead.",inputSchema:{layout:$.enum(XZ).describe("The composition Figura emits."),title:$.string().optional().describe("Fig title (else derived from the HTML)."),description:$.string().optional(),area:U(),tags:$.array($.string()).optional(),orientation:$.enum(j).optional().describe('Fig-level orientation for the persisted row (may be "both").'),device:$.string().optional().describe("Fig-level default catalog device (per-screen `device` still keys each frame)."),sharedCss:$.string().optional().describe("ONE stylesheet ALL screens share — put brand tokens + shared classes here."),screens:$.array($.object({html:$.string().describe("SCREEN CONTENT markup only — no frame, no bezel, no safe padding."),css:$.string().optional().describe("Optional per-screen content styles (appended unscoped)."),device:$.string().optional().describe("Catalog device id (e.g. 'iphone-16'). REQUIRED for device layouts."),orientation:$.enum(["portrait","landscape"]).optional().describe("REQUIRED for device layouts."),safeZone:$.enum(["respect","ignore"]).optional().describe("REQUIRED for device layouts. 'respect' pads to the real catalog safe insets; 'ignore' is edge-to-edge."),label:$.string().optional().describe("Chrome label (compare/variations chip, focus pill).")})).describe("The screens to compose. One for `single`; two for a `compare` diptych; N for variations/overview-focus/document."),model:$.string().optional().describe("Model attribution."),issue:$.number().optional().describe("Linked issue number."),publish:$.boolean().optional().describe("Publish to a shareable public URL on compose (requires a paid plan). Default false."),commit:$.boolean().optional().describe("Commit to the team library (sends status: 'published'). Default false — lands a workspace draft."),prompt:$.string().optional().describe("OPTIONAL brief that produced this fig (DB-only).")}},async(Q)=>{try{let Z={layout:Q.layout,screens:Q.screens};for(let q of["title","description","area","tags","orientation","device","sharedCss","model","issue","publish","prompt"])if(Q[q]!==void 0)Z[q]=Q[q];if(Q.commit)Z.status="published";let W=N(L);return Z.toolchain=W,G(F(await A(await J("/v1/figs/compose",{method:"POST",body:Z})),W.skill.status))}catch(Z){return B(Z)}});x.registerTool("figura_upload_asset",{title:"Figura: upload asset",description:"Upload a durable image asset and get back a STABLE, figura-hosted URL that never expires — use it in a fig's <img src> instead of a base64 data-URI (bloats the HTML past the publish size) or an external URL that expires (Instagram/CDN signed links). The fig CSP allows figura-hosted images. Provide `path` (a local image file), `url` (an http(s) image to fetch and re-host), or `data` (base64 bytes) + `contentType`. Accepts png/jpeg/gif/webp/avif/svg, up to 5MB. Returns `{ url }`.",inputSchema:{path:$.string().optional().describe("Local path to an image file to upload (content-type inferred from the extension)."),url:$.string().optional().describe("http(s) URL of an image to fetch and re-host (alternative to `path`) — use for expiring/signed source URLs so the fig keeps rendering after they die."),data:$.string().optional().describe("Base64-encoded image bytes (alternative to `path`/`url`). Requires `contentType`."),contentType:$.string().optional().describe("MIME type, e.g. image/png. Required with `data`; inferred from the extension/response for `path`/`url`.")}},async(Q)=>{try{let Z=Q.path??Q.url;if(Z){let{data:W,contentType:q}=await DQ(Z,Q.contentType);return G(await J("/v1/assets",{method:"POST",body:{data:W,contentType:q}}))}if(!Q.data)throw Error("Provide `path` (a local image file), `url` (an http(s) image), or `data` (base64 bytes).");if(!Q.contentType)throw Error("`contentType` is required with `data` — e.g. image/png.");return G(await J("/v1/assets",{method:"POST",body:{data:Q.data,contentType:Q.contentType}}))}catch(Z){return B(Z)}});x.registerTool("figura_generate_fig",{title:"Figura: generate fig",description:"Generate a new fig server-side from a natural-language brief, then persist it — this HOSTS it (the create IS the hosting). The engine runs Figura's on-brand generation — you do NOT write the HTML; just describe the screen. SPENDS TEAM CREDITS: only use when the user explicitly opts for a server render; otherwise default to writing the HTML yourself and landing it with figura_create_fig (free, uses the calling model). Runs as an async server job; this call polls until the fig lands (typically 30–90s). Returns the created fig (id, slug) and `viewUrl` — ALWAYS a link you can open for approval (a team-scoped viewer when unpublished, the public share url once published). Like figura_create_fig, the generated fig lands as a workspace DRAFT — not in the team library, silent for teammates — commit the session's final pick with figura_commit_fig. Requires an active paid subscription.",inputSchema:{prompt:$.string().describe("A natural-language brief describing the screen/UI to generate."),area:U(),orientation:$.enum(j).optional(),mode:$.enum(I).optional(),platform:$.enum(["mobile","web"]).optional().describe("Output platform: 'mobile' (iPhone frame) or 'web' (browser frame). When omitted, the engine INFERS it from the brief — a desktop/web/browser/landing-page/dashboard brief renders web, an iPhone/mobile/app-screen brief renders mobile — falling back to mobile only when neither is signalled. Pass this to force a platform regardless of the wording."),device:$.string().optional().describe("Catalog iPhone id to target (e.g. 'iphone-16', 'iphone-17-pro', 'iphone-se-3'). Mobile only; default iphone-16."),title:$.string().optional().describe("Title (otherwise derived from the generated HTML)."),fidelity:$.enum(["fast","high"]).optional().describe("Generation fidelity (default fast)."),publish:$.boolean().optional().describe("Publish to a shareable public URL on create (requires a paid plan). Default false — the response's `viewUrl` is already open-able team-privately, so only set this when the human explicitly wants a link they can share outside the team.")}},async(Q)=>{try{let Z={prompt:Q.prompt};for(let K of["area","orientation","mode","platform","device","title","publish"])if(Q[K]!==void 0)Z[K]=Q[K];if(Q.fidelity!==void 0)Z.model=Q.fidelity;let W=N(L);Z.toolchain=W,Z.async=!0;let q=await J("/v1/figs/generate",{method:"POST",body:Z});if(q&&typeof q==="object"&&typeof q.jobId==="string"){let K=await $Z(q.jobId),X=K.result??{};return G(F(await A(X.fig??K.result),W.skill.status))}return G(F(await A(q),W.skill.status))}catch(Z){return B(Z)}});x.registerTool("figura_fig_scaffold",{title:"Figura: fig scaffold",description:"Return the CANONICAL fig authoring scaffold — the exact system prompt Figura injects when it renders a fig server-side (design rules + exemplars + accent hints + your team's composed brand + the component/device kit context), composed for a target (platform/device/area/mode/orientation). USE THIS on the hand-build path (before writing a fig's HTML with figura_create_fig): author against this scaffold instead of a hand-maintained copy of the guidance, so your fig follows the SAME rules + brand the server would. Read-only — no fig is created, no credits are spent. Returns { scaffold, platform, mode, orientation, area, device, brand }.",inputSchema:{platform:$.enum(["mobile","web"]).optional().describe("Target platform: 'mobile' (iPhone frame, default) or 'web' (browser frame)."),device:$.string().optional().describe("Catalog iPhone id (e.g. 'iphone-16', 'iphone-17-pro', 'iphone-se-3'). Mobile only; default iphone-16."),area:U(),orientation:$.enum(j).optional(),mode:$.enum(I).optional()}},async(Q)=>{try{let Z=new URLSearchParams;for(let q of["platform","device","area","orientation","mode"])if(Q[q]!==void 0)Z.set(q,String(Q[q]));let W=Z.toString();return G(await J(`/v1/fig/scaffold${W?`?${W}`:""}`))}catch(Z){return B(Z)}});x.registerTool("figura_fig_devices",{title:"Figura: fig devices",description:"Return the CANONICAL framed-device catalog — every valid `data-device` id plus its per-device geometry (logical dims portrait/landscape, safe-area insets, cutout island|notch|none, corner radius). USE THIS when authoring a CANVAS COMPOSITION fig that frames a specific phone in-fig (a `.fig-device` element with `data-device` set): pick a real id from here instead of guessing, since an unknown data-device silently gets NO frame. Read-only — no fig is created, no credits are spent. Returns { devices, default }.",inputSchema:{}},async()=>{try{return G(await J("/v1/fig/devices"))}catch(Q){return B(Q)}});x.registerTool("figura_revise_fig",{title:"Figura: revise fig",description:"Create a new revision (version) of an existing fig from updated HTML — this HOSTS it, same as create. Returns the new fig (id, slug, version) and `viewUrl` — ALWAYS a link to open and re-review. The revision lands as a workspace DRAFT regardless of the parent's status — not in the team library, silent for teammates — so iterate freely; when a revision is the session's final agreed version, commit it (`commit: true` on that call, or figura_commit_fig). Publishing is NOT inherited from the fig being revised: the new revision defaults to unpublished (a team-scoped viewer `viewUrl`) even if the fig it revises is currently live — the existing public link keeps serving the OLD version until you pass `publish: true` on THIS call, which republishes at the SAME stable link (same publicId across the chain). The new version joins the original fig's chain — it does not replace it in place. Use list_revisions for the chain (rootFig + every version). The response also carries `brandWarnings` — a deterministic (no-LLM) colors/fonts/radii/spacing diff against the team's brand tokens, WARN-only. If it comes back non-empty, consider one more revision that binds the missing tokens. To include REAL images (screenshots/photos/logos), pass them via `images` — uploaded to durable figura hosting, stable URLs substituted into the HTML.",inputSchema:{id:$.string().describe("The fig to revise — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),html:$.string().describe("The full updated HTML document."),images:HQ(),title:$.string().optional().describe("Title (otherwise derived from the HTML)."),description:$.string().optional(),area:$.string().optional().describe("Product area / surface; free text. Inherited from the parent if omitted."),tags:$.array($.string()).optional(),orientation:$.enum(j).optional().describe("Inherited from the parent if omitted."),mode:$.enum(I).optional(),model:$.string().optional().describe("Model attribution."),issue:$.number().optional().describe("Linked issue number."),publish:$.boolean().optional().describe("Publish the new revision to a shareable public URL (requires a paid plan). Default false — the response's `viewUrl` is already open-able team-privately. If the fig being revised is ALREADY published, pass true here too or its public link keeps serving the prior version. Share link ONLY — does not commit the revision to the team library (that's `commit`)."),commit:$.boolean().optional().describe("Commit this revision to the team library (sends status: 'published'). Default false — the revision lands as a workspace DRAFT even when the fig it revises is committed. Set true ONLY when this revision is the session's final agreed version; intermediate iterations stay drafts. Committing later: figura_commit_fig."),prompt:$.string().optional().describe("OPTIONAL: the brief/ask that produced this revision, if there was one. Stored on the fig (DB-only, never stamped into the HTML), and returned by figura_get_fig.")}},async(Q)=>{try{let{html:Z,uploaded:W}=await CQ(Q.html,Q.images),q={html:Z};for(let K of["title","description","area","tags","orientation","mode","model","issue","publish","prompt"])if(Q[K]!==void 0)q[K]=Q[K];if(Q.commit)q.status="published";return G(VQ(await J(`/v1/figs/${encodeURIComponent(Q.id)}/revise`,{method:"POST",body:q}),W))}catch(Z){return B(Z)}});x.registerTool("figura_list_revisions",{title:"Figura: list revisions",description:"List the full revision chain for a fig (all versions sharing a root), oldest to newest.",inputSchema:{id:$.string().describe("Any fig in the chain — its id (`fig_…`), a UUID, share link/URL, or publicId.")}},async(Q)=>{try{return G(await J(`/v1/figs/${encodeURIComponent(Q.id)}/revisions`))}catch(Z){return B(Z)}});x.registerTool("figura_commit_fig",{title:"Figura: commit fig",description:"Commit a fig to the team library (status draft → published). Machine-created figs land as workspace DRAFTS — hosted, viewable via `viewUrl`, visible to their author, but NOT in the team library and silent for teammates. Committing is the explicit act that puts one in the team library and notifies the team (digest-batched) — so commit ONLY the session's final recommendation (the fig the user asked for / signed off on), never every exploration or intermediate iteration. If the final fig is one you're about to create/revise anyway, prefer `commit: true` on that call over a separate commit here. Orthogonal to figura_publish_fig (the public share link): a shared draft's URL resolves fine, and committing creates no link. Idempotent. Pass `uncommit: true` to reverse it (published → draft; the share link is untouched). Returns { id, status, committed, alreadyCommitted, viewUrl }.",inputSchema:{id:$.string().describe("The fig to commit — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),uncommit:$.boolean().optional().describe("Set true to uncommit: the fig leaves the team library back to an author-visible workspace draft. Defaults to false (commit).")}},async(Q)=>{try{return G(await J(`/v1/figs/${encodeURIComponent(Q.id)}/${Q.uncommit?"uncommit":"commit"}`,{method:"POST",body:{}}))}catch(Z){return B(Z)}});x.registerTool("figura_publish_fig",{title:"Figura: publish fig",description:"Publish (or unpublish) an existing fig to its shareable public URL. The fig is ALREADY hosted and viewable team-privately without this (figura_create_fig/figura_revise_fig's `viewUrl`) — only call this once the human wants a link they can share outside the team. Share link ONLY — it does not put the fig in the team library (that's figura_commit_fig; a shared draft's URL resolves fine). Requires a paid plan. Returns { isPublic, url, publicId, viewUrl }.",inputSchema:{id:$.string().describe("The fig to publish — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),isPublic:$.boolean().optional().describe("Set false to unpublish (make private). Defaults to true (publish).")}},async(Q)=>{try{let Z={};if(Q.isPublic!==void 0)Z.isPublic=Q.isPublic;return G(await J(`/v1/figs/${encodeURIComponent(Q.id)}/publish`,{method:"POST",body:Z}))}catch(Z){return B(Z)}});x.registerTool("figura_list_figs",{title:"Figura: list figs",description:"List visualizations for the team, optionally filtered by area or tag.",inputSchema:{area:U(),tag:$.string().optional(),limit:$.number().optional(),cursor:$.string().optional()}},async(Q)=>{try{let Z=new URLSearchParams;if(Q.area)Z.set("area",Q.area);if(Q.tag)Z.set("tag",Q.tag);if(Q.limit!==void 0)Z.set("limit",String(Q.limit));if(Q.cursor)Z.set("cursor",Q.cursor);let W=Z.toString();return G(await J(`/v1/figs${W?`?${W}`:""}`))}catch(Z){return B(Z)}});x.registerTool("figura_get_fig",{title:"Figura: get fig",description:"Fetch a single visualization by id. The response carries `viewUrl` — ALWAYS a link you can open for approval (a team-scoped viewer when unpublished, the public share url once published).",inputSchema:{id:$.string().describe("The fig — its id (`fig_…`), a UUID, a share link/URL, or its publicId.")}},async(Q)=>{try{return G(await J(`/v1/figs/${encodeURIComponent(Q.id)}`))}catch(Z){return B(Z)}});x.registerTool("figura_comment",{title:"Figura: comment",description:"Add a comment to a visualization.",inputSchema:{fig_id:$.string().describe("The fig to comment on — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),body:$.string().describe("Comment text.")}},async(Q)=>{try{return G(await J(`/v1/figs/${encodeURIComponent(Q.fig_id)}/comments`,{method:"POST",body:{body:Q.body}}))}catch(Z){return B(Z)}});x.registerTool("figura_request_feedback",{title:"Figura: request feedback",description:"Ask a teammate to review a fig. Resolve `from` to a team member (by name or email); they get a notification (in-app, push, email) and the discussion happens in the fig's comment thread. Use this when the user says they want a specific person's feedback/eyes/review on a fig. Returns { ok, request: { to, status }, figUrl }.",inputSchema:{id:$.string().describe("The fig to request feedback on — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),from:$.string().describe("The teammate to ask, by name or email (resolved within the team)."),note:$.string().optional().describe("Optional message for them (e.g. what to look at).")}},async(Q)=>{try{let Z={from:Q.from};if(Q.note!==void 0)Z.note=Q.note;return G(await J(`/v1/figs/${encodeURIComponent(Q.id)}/request-feedback`,{method:"POST",body:Z}))}catch(Z){return B(Z)}});x.registerTool("figura_list_sources",{title:"Figura: list sources",description:"List the company-brain source-spine connectors for the team, with event counts and last-synced times.",inputSchema:{}},async()=>{try{return G(await J("/v1/sources"))}catch(Q){return B(Q)}});x.registerTool("figura_sync_source",{title:"Figura: sync source",description:"Ingest new events from a connected source into the spine. Returns { ingested, fetched, nextCursor }.",inputSchema:{id:$.string().describe("The source id to sync (from figura_list_sources).")}},async(Q)=>{try{return G(await J(`/v1/sources/${encodeURIComponent(Q.id)}/sync`,{method:"POST"}))}catch(Z){return B(Z)}});x.registerTool("figura_mine_screens",{title:"Figura: mine screens",description:"Build the app's screen catalog from a connected git source's CURRENT file tree (framework-aware, convention-based — no file bodies, no fig generation, no credits). Returns { screens: [{slug,name,path,framework}], framework, count, commitSha, truncated }.",inputSchema:{id:$.string().describe("The git source id to mine (from figura_list_sources).")}},async(Q)=>{try{return G(await J(`/v1/sources/${encodeURIComponent(Q.id)}/mine-screens`,{method:"POST"}))}catch(Z){return B(Z)}});x.registerTool("figura_list_screens",{title:"Figura: list screens",description:"Read the team's mined screen catalog — the app's current screens ({slug,name,path,framework}) plus when it was last mined. Free, read-only. Run figura_mine_screens first to populate it.",inputSchema:{}},async()=>{try{return G(await J("/v1/sources/screens"))}catch(Q){return B(Q)}});x.registerTool("figura_update_fig",{title:"Figura: update fig",description:"Update a fig's METADATA only (title/description/area/tags/status). Set status='archived' to soft-delete. For library membership (draft ⇄ published) prefer figura_commit_fig — a status PATCH here is a silent metadata setter that never notifies the team. To change the fig's HTML, use figura_revise_fig — it saves a new version and never destroys the old one. update cannot touch the HTML.",inputSchema:{id:$.string().describe("The fig to update — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),title:$.string().optional(),description:$.string().optional(),area:U(),tags:$.array($.string()).optional().describe("Replaces the existing tags."),status:$.enum(["draft","published","archived"]).optional()}},async(Q)=>{try{let Z={};if(Q.title!==void 0)Z.title=Q.title;if(Q.description!==void 0)Z.description=Q.description;if(Q.area!==void 0)Z.area=Q.area;if(Q.tags!==void 0)Z.tags=Q.tags;if(Q.status!==void 0)Z.status=Q.status;return G(await J(`/v1/figs/${encodeURIComponent(Q.id)}`,{method:"PATCH",body:Z}))}catch(Z){return B(Z)}});x.registerTool("figura_delete_fig",{title:"Figura: delete fig",description:"Archive a fig (soft-delete; leaves the library, public link stops resolving) or permanently delete it with hard=true.",inputSchema:{id:$.string().describe("The fig to delete — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),hard:$.boolean().optional().describe("Permanently delete instead of archive.")}},async(Q)=>{try{return G(await J(`/v1/figs/${encodeURIComponent(Q.id)}${Q.hard?"?hard=true":""}`,{method:"DELETE"}))}catch(Z){return B(Z)}});(async()=>{let{apiUrl:Q}=await E();await WQ(L,_,O(Q))})();await x.connect(new gQ);
2
+ import{createRequire as VQ}from"node:module";var LQ=VQ(import.meta.url);import{promises as z,readFileSync as hQ}from"node:fs";import GQ from"axios";import{McpServer as pQ}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as uQ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as $}from"zod";import{CONFIG_PATH as WQ,findProjectConfigPath as dQ,readJsonConfig as qQ}from"@panofm/figura-core/net/client-config";import{pollUntilTerminal as lQ}from"@panofm/figura-core/net/jobs";import{shouldRefuseGlobalMutate as d,bindingGuardAction as YZ}from"@panofm/figura-core/net/client-config";function l(Q){let Z={name:Q.name};if(Q.appDescription!==void 0)Z.appDescription=Q.appDescription;if(Q.tokensBlock!==void 0)Z.tokensBlock=Q.tokensBlock;if(Q.surfaces!==void 0)Z.surfaces=Q.surfaces;if(Q.identity!==void 0)Z.identity=Q.identity;if(Q.platforms!==void 0)Z.platforms=Q.platforms;if(Q.proseSource!==void 0)Z.proseSource=Q.proseSource;return Z}import{createHash as MQ}from"node:crypto";import{existsSync as PQ,readdirSync as I,readFileSync as T}from"node:fs";import{homedir as RQ}from"node:os";import{fileURLToPath as c}from"node:url";import{dirname as UQ,join as V,relative as jQ,sep as AQ}from"node:path";var _Q=".figura-version";var n="fig";function i(Q){let Z=[],W=(K)=>{for(let X of I(K,{withFileTypes:!0})){let Y=V(K,X.name);if(X.isDirectory())W(Y);else if(X.isFile())Z.push(Y)}};try{for(let K of I(Q,{withFileTypes:!0}))if(K.isDirectory()&&K.name===n)W(V(Q,K.name))}catch{return null}if(Z.length===0)return null;let q=MQ("sha256");for(let K of Z.sort()){let X=jQ(Q,K).split(AQ).join("/");q.update(X),q.update("\x00"),q.update(T(K)),q.update("\x00")}return q.digest("hex").slice(0,16)}function g(Q){try{return I(Q,{withFileTypes:!0}).some((Z)=>Z.isDirectory()&&PQ(V(Q,Z.name,"SKILL.md")))}catch{return!1}}function o(){let Q=[new URL("../skills/",import.meta.url),new URL("../../skills/",import.meta.url)].map((W)=>c(W));for(let W of Q)if(g(W))return W;let Z=c(new URL("./",import.meta.url));for(let W=0;W<8;W++){let q=V(Z,".claude","skills");if(g(q))return q;let K=UQ(Z);if(K===Z)break;Z=K}return null}function NQ(){let Q=o();return Q?i(Q):null}function OQ(){let Q=o();if(!Q)return null;try{return JSON.parse(T(V(Q,"skills.json"),"utf8")).skills?.[n]?.version??null}catch{return null}}function FQ(Q){try{return T(V(Q,_Q),"utf8").trim()||null}catch{return null}}function EQ(Q,Z){let W=(X)=>{let Y=/^\D*(\d+)\.(\d+)\.(\d+)/.exec(X.trim());return Y?[Number(Y[1]),Number(Y[2]),Number(Y[3])]:null},q=W(Q),K=W(Z);if(!q||!K)return!1;for(let X=0;X<3;X++){if(q[X]>K[X])return!0;if(q[X]<K[X])return!1}return!1}function wQ(Q){let{stamp:Z,installedHash:W,bundledHash:q,referenceVersion:K}=Q;if(W==null)return"absent";if(q!=null&&W===q&&Z===K)return"pristine";if(Z!=null&&K!=null&&EQ(K,Z))return"stale";return"modified"}function IQ(Q,Z=V(RQ(),".claude","skills")){try{let W=FQ(Z),q=i(Z),K=NQ(),X=wQ({stamp:W,installedHash:q,bundledHash:K,referenceVersion:OQ()});return{version:W,hash:q,status:X}}catch{return{version:null,hash:null,status:"absent"}}}function A(Q){return{channel:"mcp",mcpVersion:Q,skill:IQ(Q)}}function t(Q){if(Q==="modified")return"⚠ your fig skill is MODIFIED (differs from figura-cli's shipped version) — run `figura install` to restore it";if(Q==="stale")return"⚠ your fig skill is outdated (behind figura-cli) — run `figura install` to reinstall it";return null}import{promises as k}from"node:fs";import{homedir as b}from"node:os";import{join as S}from"node:path";var TQ=604800000,kQ=21600000;function _(Q){try{let Z=new URL(Q);return`${Z.protocol}//${Z.host}`.toLowerCase()}catch{return Q.trim().toLowerCase().replace(/\/+$/,"")}}async function f(Q,Z="latest",W){let q=await import("package-manager-detector"),K=W!==void 0?W:q.getUserAgent()??null;if(K){let X=q.resolveCommand(K,"global",[`${Q}@${Z}`]);if(X)return{command:`${X.command} ${X.args.join(" ")}`,generic:!1}}return{command:`npm i -g ${Q}@${Z}`,generic:!0}}function y(Q){return Q.generic?`Update with your package manager's global install, e.g. ${Q.command}`:`Run: ${Q.command}`}function a(Q){if(Q==="figura-cli")return{pkg:"figura-cli",cacheFile:S(b(),".figura","update-check.json"),minHeader:"x-figura-min-cli",latestHeader:"x-figura-latest-cli",label:"figura",installPkg:"figura-cli"};return{pkg:"figura-mcp",cacheFile:S(b(),".figura","update-check-mcp.json"),minHeader:"x-figura-min-mcp",latestHeader:"x-figura-latest-mcp",label:"figura-mcp",installPkg:"figura-mcp"}}function bQ(Q,Z,W){if(!Z.min&&!Z.latest)return null;let q={...Q},K=!1,X=(Y)=>typeof Y!=="number"||W-Y>=kQ;if(Z.min&&(Q.min!==Z.min||X(Q.minAt)))q.min=Z.min,q.minAt=W,K=!0;if(Z.latest&&(Q.latest!==Z.latest||X(Q.latestAt)))q.latest=Z.latest,q.latestAt=W,K=!0;return K?q:null}function s(Q,Z){return typeof Q==="number"&&Z-Q<TQ}function v(Q,Z,W){let q=Q.serverAdvice?.[Z];if(!q)return{};return{min:s(q.minAt,W)?q.min:void 0,latest:s(q.latestAt,W)?q.latest:void 0}}function R(Q,Z){let W=(X)=>{let Y=/^\D*(\d+)\.(\d+)\.(\d+)/.exec(X.trim());return Y?[Number(Y[1]),Number(Y[2]),Number(Y[3])]:null},q=W(Q),K=W(Z);if(!q||!K)return!1;for(let X=0;X<3;X++){if(q[X]>K[X])return!0;if(q[X]<K[X])return!1}return!1}function SQ(Q){if(Q.CI)return"ci";if(Q.FIGURA_NO_UPDATE_NOTIFIER==="1"||Q.NO_UPDATE_NOTIFIER==="1")return"opt-out";return null}function fQ(Q,Z,W,q){return`⚠ ${Q.label} ${Z} → ${W} available. ${q}`}function yQ(Q,Z,W,q){return`⚠ ${Q.label} ${Z} is below the minimum supported ${W} — `+`some tools may fail. ${q}`}function r(Q,Z,W){let q=Q.latest,K=v(Q,Z,W).latest;if(q&&K)return R(K,q)?K:q;return q??K}function vQ(Q,Z,W,q,K=Date.now()){let X=v(W,q,K).min;if(X&&R(X,Z))return{level:"firm",target:X};let Y=r(W,q,K);if(Y&&R(Y,Z))return{level:"stale",target:Y};return null}function mQ(Q,Z,W,q){return Z.level==="firm"?`Your ${Q.label} ${W} is below the minimum supported ${Z.target} — `+`some Figura tools may fail. Ask the user to update: ${q}`:`${Q.label} ${W} → ${Z.target} available. Ask the user to update: ${q}`}async function e(Q){try{let Z=Q.cache??await m(Q.stream),W=vQ(Q.stream,Q.current,Z,Q.origin,Q.now);if(!W)return null;let q=y(await f(Q.stream.installPkg,"latest",Q.agent));return mQ(Q.stream,W,Q.current,q)}catch{return null}}function QQ(Q,Z){let W=Z(Q.minHeader)?.trim(),q=Z(Q.latestHeader)?.trim();return{min:W||void 0,latest:q||void 0}}async function ZQ(Q,Z,W,q=Date.now()){try{if(!W.min&&!W.latest)return;let K=await m(Q),X={...K.serverAdvice??{}},Y=bQ(X[Z]??{},W,q);if(!Y)return;X[Z]=Y,await zQ(Q,{...K,serverAdvice:X})}catch{}}async function m(Q){try{let Z=JSON.parse(await k.readFile(Q.cacheFile,"utf8"));return Z&&typeof Z==="object"?Z:{}}catch{return{}}}async function zQ(Q,Z){await k.mkdir(S(b(),".figura"),{recursive:!0,mode:448}),await k.writeFile(Q.cacheFile,JSON.stringify(Z,null,2)+`
3
+ `,{mode:384})}async function $Q(Q,Z,W,q=process.env,K=Date.now()){try{if(SQ(q))return;let X=await m(Z),Y=v(X,W,K).min;if(Y&&R(Y,Q)){let D=y(await f(Z.installPkg));process.stderr.write(yQ(Z,Q,Y,D)+`
4
+ `);return}let L=r(X,W,K);if(L&&R(L,Q)){let D=y(await f(Z.installPkg));process.stderr.write(fQ(Z,Q,L,D)+`
5
+ `)}}catch{}}var cQ=$.object({name:$.string(),hex:$.string().describe("3/4/6/8-digit hex, e.g. #1FB6A6 or #1FB6A6FF."),role:$.string().optional(),meaning:$.string().optional()}).passthrough(),gQ=$.object({id:$.string().optional(),rule:$.string()}).passthrough(),nQ=$.object({colors:$.array(cQ).optional(),gradient:$.string().optional(),type:$.object({families:$.record($.string()).optional(),ramp:$.array($.number()).optional(),rules:$.string().optional()}).passthrough().optional(),spacing:$.array($.number()).optional(),radius:$.array($.number()).optional(),voice:$.object({nouns:$.array($.string()).optional(),promise:$.string().optional(),lines:$.array($.string()).optional(),tone:$.string().optional()}).passthrough().optional(),forbidden:$.array(gQ).optional()}).passthrough(),h=$.object({components:$.array($.object({name:$.string(),spec:$.string()}).passthrough()).optional(),icons:$.string().optional(),layout:$.string().optional(),surfaces:$.array($.string()).optional(),bans:$.array($.string()).optional(),tokensBlock:$.string().optional()}).passthrough(),iQ=$.object({mobile:h.optional(),web:h.optional(),desktop:h.optional()}).passthrough(),oQ="https://api.figura.so",tQ="mcp";async function F(){let Q=await dQ(),Z=Q?await qQ(Q):{},W=await qQ(WQ),q={...W,...Z},K=process.env.FIGURA_TOKEN||q.token||void 0,X=process.env.FIGURA_TOKEN?"env":Z.token?"project":W.token?"global":"none",Y=(process.env.FIGURA_API_URL||q.apiUrl||oQ).replace(/\/+$/,"");return{token:K,apiUrl:Y,team:q.team,source:X,configPath:X==="project"?Q:X==="global"?WQ:null}}async function G(Q,Z={}){let W=await F(),q=W.token;if(!q)throw Error("No Figura token. Run `figura link` in this repo (or `figura login`, or set FIGURA_TOKEN).");let K=(Z.method??"GET").toUpperCase();if(d(K,W.source,process.env.FIGURA_ALLOW_GLOBAL==="1"))throw Error(`this project isn't linked to a Figura team — the global credential${W.team?` (team '${W.team}')`:""} would receive this write. Ask the user to run \`figura link\` in this repo (or set FIGURA_ALLOW_GLOBAL=1 to use the global team deliberately).`);let X=`${W.apiUrl}${Q.startsWith("/")?"":"/"}${Q}`,Y={Accept:"application/json",Authorization:`Bearer ${q}`,"X-Figura-Source":tQ},L;if(Z.body!==void 0)Y["Content-Type"]="application/json",L=JSON.stringify(Z.body);let D=await GQ.request({url:X,method:Z.method??"GET",headers:Y,data:L,validateStatus:()=>!0,transformRequest:[(C)=>C],transformResponse:[(C)=>C]});{let C=D.headers,HQ=(CQ)=>{let u=C?.[CQ];return typeof u==="string"?u:void 0};ZQ(O,_(W.apiUrl),QQ(O,HQ))}let w=typeof D.data==="string"?D.data:"",H=void 0;if(w)try{H=JSON.parse(w)}catch{H=w}if(D.status<200||D.status>=300){let C=H&&typeof H==="object"&&H!==null&&"error"in H?String(H.error):typeof H==="string"&&H?H:D.statusText||`HTTP ${D.status}`;throw Error(`${C} (HTTP ${D.status})`)}return H}var KQ=2500,sQ=600000,aQ=60000;async function rQ(Q){let Z=Math.ceil(sQ/KQ);try{return await lQ({intervalMs:KQ,maxPolls:Z,errorToleranceMs:aQ,fetchJob:()=>G(`/v1/jobs/${encodeURIComponent(Q)}`)})}catch(W){let q=W instanceof Error?W.message:String(W);if(q.startsWith("Job poll failed:"))throw Error(`Lost contact with the Figura API while waiting for job ${Q} (${q.slice(17)}). `+`The job may still complete — resume by checking GET /v1/jobs/${Q} instead of regenerating.`);if(q.startsWith("Timed out"))throw Error(`Timed out waiting for job ${Q} — it may still complete; `+`check GET /v1/jobs/${Q} instead of regenerating.`);throw W}}function J(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function B(Q){return{content:[{type:"text",text:Q instanceof Error?Q.message:String(Q)}],isError:!0}}var XQ=!1;async function U(Q){try{if(XQ)return Q;if(!Q||typeof Q!=="object"||Array.isArray(Q))return Q;let{apiUrl:Z}=await F(),W=await e({stream:O,current:P,origin:_(Z)});if(!W)return Q;return XQ=!0,{...Q,notice:W}}catch{return Q}}function N(Q,Z){if(!Q||typeof Q!=="object"||Array.isArray(Q))return Q;let W=t(Z);if(!W)return Q;return{...Q,skillWarning:W}}var M=()=>$.string().optional().describe("Product area / surface the fig belongs to, e.g. 'dashboard', 'settings', 'onboarding'. Free text."),j=["portrait","landscape","both"],E=["single","compare","variations"],{version:P,name:eQ}=(()=>{try{let Q=JSON.parse(hQ(new URL("../package.json",import.meta.url),"utf8"));return{version:typeof Q.version==="string"?Q.version:"0.0.0",name:typeof Q.name==="string"?Q.name:void 0}}catch{return{version:"0.0.0"}}})(),O=a(eQ),x=new pQ({name:"figura",version:P});x.registerTool("figura_whoami",{title:"Figura: whoami",description:"Return the identity (team, actor, scopes) for the configured Figura token, plus `binding` — which config tier supplied it (env | project | global). A `global` binding means this project is not linked to a team and writes will be refused; ask the user to run `figura link` in the repo.",inputSchema:{}},async()=>{try{let Q=await G("/v1/whoami"),{source:Z,configPath:W}=await F();return J(await U({...Q,binding:{source:Z,configPath:W}}))}catch(Q){return B(Q)}});x.registerTool("figura_set_brand",{title:"Figura: set brand profile",description:'Set (upsert) the team brand profile that the fig generator renders against. Use this to "introduce a repo to Figura": scan the codebase for its design system, synthesize the brand, then push it here. `name` is required. PREFERRED — send a STRUCTURED brand: `identity` (shared colors/gradient/type/spacing/radius/voice/forbidden) + `platforms` (per-platform surfaces, keys mobile|web|desktop) — this makes the brand structured + addressable (is_structured=true). LEGACY/fallback — send prose: `tokensBlock` (freeform design-token reference) + `surfaces` (the product\'s own key areas). `appDescription` is a one-clause product summary. This is a partial merge — fields you omit keep their saved value; a structured write clears the dormant prose columns and a prose write downgrades to legacy. Editing the team brand — confirm with the user before calling.',inputSchema:{name:$.string().describe("Brand / app name (required)."),appDescription:$.string().optional().describe("One clause on what the product is + who it is for."),identity:nQ.optional().describe("STRUCTURED shared identity (platform-agnostic): { colors:[{name,hex,role?,meaning?}], gradient?, type?:{families?:{slot:font},ramp?:number[],rules?}, spacing?:number[], radius?:number[], voice?:{nouns?,promise?,lines?,tone?}, forbidden?:[{id?,rule}] }. hex is 3/4/6/8 digits. Sending this makes the brand STRUCTURED (is_structured=true). Validated server-side."),platforms:iQ.optional().describe("STRUCTURED per-platform surfaces — a map keyed by mobile|web|desktop; include ONLY the platforms the product targets: { <platform>: { components?:[{name,spec}], icons?, layout?, surfaces?:string[], bans?:string[], tokensBlock? } }. `tokensBlock` here is a per-platform escape hatch for guidance that does not fit a structured field."),proseSource:$.string().optional().describe(`The human-readable freeform description this structured brand was authored from — stored as the editable source shown in the web brand editor; NOT used by generation. Send it alongside a structured write so a skill/CLI/MCP-authored brand still seeds the web editor's "Author from a description" textarea (a repo scan should pass the prose it synthesized the brand from; a prose→structured upgrade should pass the original prose).`),tokensBlock:$.string().optional().describe("LEGACY prose fallback: freeform plain-text design-token reference (colors + hex + role, type scale + faces, spacing, gradient, voice/conventions). Prefer `identity`/`platforms`. Injected verbatim into the fig-generation prompt."),surfaces:$.array($.string()).optional().describe(`LEGACY prose fallback: the product's own key areas/sections (e.g. ["Feed", "Settings", "Checkout"]) — read from the repo's real navigation/routes. For a structured brand put surfaces under each platform instead. Pass [] to clear.`)}},async(Q)=>{try{return J(await G("/brand",{method:"PUT",body:l(Q)}))}catch(Z){return B(Z)}});x.registerTool("figura_brand_schema",{title:"Figura: brand schema",description:"Return the JSON Schema for the STRUCTURED brand — the ONE authority (derived server-side from the zod schema PUT /brand validates). Fetch this BEFORE synthesizing a brand for figura_set_brand's `identity`/`platforms`, and author against it so the brand validates first try (strict keys; hex 3/4/6/8 digits; platform keys mobile|web|desktop; no blank array entries). Read-only. Returns { schema }.",inputSchema:{}},async()=>{try{return J(await G("/v1/brand/schema"))}catch(Q){return B(Q)}});var QZ={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml"},p=5242880;function YQ(Q){let Z=Q.split(/[?#]/)[0].split(".").pop()?.toLowerCase()??"";return QZ[Z]}async function JQ(Q,Z){let W,q=Z;if(/^https?:\/\//i.test(Q)){let K=await GQ.get(Q,{responseType:"arraybuffer",maxContentLength:p,timeout:30000});if(W=Buffer.from(K.data).toString("base64"),!q){let X=String(K.headers["content-type"]??"").split(";")[0].trim().toLowerCase();q=X.startsWith("image/")?X:YQ(Q)}}else{let{size:K}=await z.stat(Q);if(K>p)throw Error(`'${Q}' is ${(K/1048576).toFixed(1)}MB — over the ${p/1048576}MB asset limit.`);if(W=(await z.readFile(Q)).toString("base64"),!q)q=YQ(Q)}if(!q)throw Error(`Could not determine an image content-type for '${Q}' — pass contentType (e.g. image/png).`);return{data:W,contentType:q}}async function ZZ(Q,Z){let{data:W,contentType:q}=await JQ(Q,Z),K=await G("/v1/assets",{method:"POST",body:{data:W,contentType:q}});if(!K||typeof K.url!=="string")throw Error("Asset upload did not return a URL.");return K.url}var xQ=()=>$.array($.object({source:$.string().describe("The image — a local file path or an http(s) URL (e.g. a screenshot)."),match:$.string().optional().describe('Exact string in the HTML to replace with the hosted URL (defaults to `source` — i.e. write <img src="<source>"> in the HTML).')})).optional().describe("Images to attach: each is uploaded to durable figura hosting (stable non-expiring URL, allowed by the fig CSP) and substituted into the HTML in place of `match`/`source`. Use for real screenshots/photos/logos instead of base64 data-URIs (HTML size cap) or external URLs (expire/CSP-blocked).");async function BQ(Q,Z){if(!Z?.length)return{html:Q,uploaded:[]};let W=Q,q=[];for(let K of Z){let X=K.match??K.source;if(!W.includes(X))throw Error(`images: '${X}' does not occur in the html — reference it (e.g. <img src="${X}">) so it can be swapped for the hosted URL, or set 'match'.`);let Y=await ZZ(K.source);W=W.split(X).join(Y),q.push({source:K.source,url:Y})}return{html:W,uploaded:q}}function DQ(Q,Z){if(!Z.length)return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q))return{...Q,assets:Z};return{result:Q,assets:Z}}x.registerTool("figura_create_fig",{title:"Figura: create fig",description:"Create a new visualization from an HTML document — this HOSTS it (the create IS the hosting; there is no separate \"land it in Figura\" step). Every create returns `viewUrl`: ALWAYS a link you can open for approval, whether or not the fig is published — the public share url once published, else a team-scoped viewer link only signed-in teammates can open. The fig lands as a workspace DRAFT (`status: 'draft'`): hosted and viewable, visible to its author, but NOT in the team library and silent for teammates — iterate freely without claiming the team's attention, then COMMIT only the session's final recommendation (`commit: true` on that final create/revise, or figura_commit_fig). Do NOT pass publish:true just to get something viewable — omit it (default false) so the fig lands team-private, open `viewUrl` for review, and only publish when the human wants a link they can share outside the team (figura_publish_fig, once approved). The response also carries `brandWarnings` — a deterministic (no-LLM) colors/fonts/radii/spacing diff against the team's brand tokens, WARN-only (never blocks the create). If it comes back non-empty, read it and consider a figura_revise_fig call that binds the missing tokens before telling the user you're done. To include REAL images (screenshots/photos/logos), pass them via `images` — they are uploaded to durable figura hosting and their stable URLs substituted into the HTML. TIP — injected components: if your HTML shows phone frames (a compare/multi-screen mock), wrap each state in <div class=\"fig-device portrait|landscape\"><div class=\"fig-screen\">…</div><div class=\"fig-di\"></div><div class=\"fig-homebar\"></div></div> — Figura injects accurate iPhone frame CSS at save, BEFORE your <style>, so you normally leave those classes alone; if you do style them your rule wins by cascade (the frame still works), but to shrink frames for an overview grid wrap each frame in the injected `.fig-mini` wrapper (e.g. <div class=\"fig-mini\" style=\"--fig-scale:.34\"> … the .fig-device block … </div>) — it scales the device with transform and reserves the scaled layout box — rather than re-declaring .fig-device width/height or adding transform: scale() yourself (which fights the injected geometry), and never CSS zoom (it leaks unzoomed width into horizontal overflow). Same injection applies to an iOS status bar (<div class=\"fig-statusbar\" data-time=\"9:41\"></div>), a compare control bar (.fig-controls/.fig-seg), and the .frame-web browser window.",inputSchema:{html:$.string().describe("The full HTML document for the visualization."),images:xQ(),title:$.string().optional().describe("Title (otherwise derived from the HTML)."),description:$.string().optional(),area:M(),tags:$.array($.string()).optional(),orientation:$.enum(j).optional(),mode:$.enum(E).optional(),model:$.string().optional().describe("Model attribution."),device:$.string().optional().describe("Catalog iPhone id the fig targets (e.g. 'iphone-16', 'iphone-17-pro', 'iphone-se-3') — keys the injected frame/safe-area geometry."),issue:$.number().optional().describe("Linked issue number."),publish:$.boolean().optional().describe("Publish to a shareable public URL on create (requires a paid plan). Default false — the response's `viewUrl` is already open-able team-privately, so only set this when the human explicitly wants a link they can share outside the team. Share link ONLY — does not commit the fig to the team library (that's `commit`)."),commit:$.boolean().optional().describe("Commit to the team library on create (sends status: 'published'). Default false — the fig lands as a workspace DRAFT: hosted + viewable via `viewUrl`, visible to its author, but not in the team library and silent for teammates. Set true ONLY when this write is the session's final recommendation (the fig the user asked for / signed off on); explorations and intermediate iterations stay drafts. Committing later: figura_commit_fig."),prompt:$.string().optional().describe("OPTIONAL: the brief that produced this HTML, if there was one — you wrote the HTML yourself, so Figura never sees a prompt unless you pass it here. Stored on the fig (DB-only, never stamped into the HTML), and returned by figura_get_fig — lets teammates see 'why' this fig exists.")}},async(Q)=>{try{let{html:Z,uploaded:W}=await BQ(Q.html,Q.images),q={html:Z};for(let X of["title","description","area","tags","orientation","mode","model","device","issue","publish","prompt"])if(Q[X]!==void 0)q[X]=Q[X];if(Q.commit)q.status="published";let K=A(P);return q.toolchain=K,J(N(await U(DQ(await G("/v1/figs",{method:"POST",body:q}),W)),K.skill.status))}catch(Z){return B(Z)}});var $Z=["single","compare","variations","overview-focus","document"];x.registerTool("figura_compose_fig",{title:"Figura: compose fig",description:"PREFERRED way to build a device fig. You write ONLY each screen's CONTENT (the markup inside the phone) + typed params; Figura owns the STRUCTURE — the iPhone frame, the Dynamic Island/notch/home bar, the exact catalog artboard geometry, the REAL safe-area insets, and the composition (grid/diptych/overview). This means the parts that used to drift every few figs — hand-rolled artboards, guessed `--fig-safe-top:59px`, a forgotten `data-device` so no safe machinery stamped — are correct-by-construction: you never write them. Pass `layout` + an ARRAY of `screens`. For every DEVICE layout (single/compare/variations/overview-focus) each screen REQUIRES `device` (a catalog id like 'iphone-16' — fetch figura_fig_devices), `orientation` ('portrait'|'landscape'), and `safeZone` ('respect' = Figura pads your content to the device's real safe insets; 'ignore' = edge-to-edge splash/hero). Each screen's `html` is CONTENT ONLY — do NOT draw a frame, a bezel, a status bar, or safe padding; do NOT set `--fig-safe-*`; do NOT wrap in `.fig-device`. Style your content with brand tokens via `sharedCss` (ONE stylesheet all screens share) + optional per-screen `css`. Layouts: `single` (one frame), `compare` (as-is → proposed diptych — pass label per screen), `overview-focus` (**use for ANY redesign argument or set of candidate directions** — a CSS toggle that OPENS on the full-frame Focus view with state pills; the Overview grid is the alternative behind the second tab), `variations` (a scan-only grid at the kit's ~0.34 device scale with NO toggle — every frame renders ~134px wide, so body copy and annotations are unreadable; use ONLY for a pure catalogue, NEVER to argue a change), `document` (NO device framing — brand/overview figs; screens need no device/orientation/safeZone). Lands EXACTLY like figura_create_fig (workspace DRAFT, returns `viewUrl` + `brandWarnings` + `warnings`; commit the session's final pick). For a `document`/exotic hand-authored fig where you need full control of the HTML, use figura_create_fig instead.",inputSchema:{layout:$.enum($Z).describe("The composition Figura emits."),title:$.string().optional().describe("Fig title (else derived from the HTML)."),description:$.string().optional(),area:M(),tags:$.array($.string()).optional(),orientation:$.enum(j).optional().describe('Fig-level orientation for the persisted row (may be "both").'),device:$.string().optional().describe("Fig-level default catalog device (per-screen `device` still keys each frame)."),sharedCss:$.string().optional().describe("ONE stylesheet ALL screens share — put brand tokens + shared classes here."),screens:$.array($.object({html:$.string().describe("SCREEN CONTENT markup only — no frame, no bezel, no safe padding."),css:$.string().optional().describe("Optional per-screen content styles (appended unscoped)."),device:$.string().optional().describe("Catalog device id (e.g. 'iphone-16'). REQUIRED for device layouts."),orientation:$.enum(["portrait","landscape"]).optional().describe("REQUIRED for device layouts."),safeZone:$.enum(["respect","ignore"]).optional().describe("REQUIRED for device layouts. 'respect' pads to the real catalog safe insets; 'ignore' is edge-to-edge."),label:$.string().optional().describe("Chrome label (compare/variations chip, focus pill).")})).describe("The screens to compose. One for `single`; two for a `compare` diptych; N for variations/overview-focus/document."),model:$.string().optional().describe("Model attribution."),issue:$.number().optional().describe("Linked issue number."),publish:$.boolean().optional().describe("Publish to a shareable public URL on compose (requires a paid plan). Default false."),commit:$.boolean().optional().describe("Commit to the team library (sends status: 'published'). Default false — lands a workspace draft."),prompt:$.string().optional().describe("OPTIONAL brief that produced this fig (DB-only).")}},async(Q)=>{try{let Z={layout:Q.layout,screens:Q.screens};for(let q of["title","description","area","tags","orientation","device","sharedCss","model","issue","publish","prompt"])if(Q[q]!==void 0)Z[q]=Q[q];if(Q.commit)Z.status="published";let W=A(P);return Z.toolchain=W,J(N(await U(await G("/v1/figs/compose",{method:"POST",body:Z})),W.skill.status))}catch(Z){return B(Z)}});x.registerTool("figura_upload_asset",{title:"Figura: upload asset",description:"Upload a durable image asset and get back a STABLE, figura-hosted URL that never expires — use it in a fig's <img src> instead of a base64 data-URI (bloats the HTML past the publish size) or an external URL that expires (Instagram/CDN signed links). The fig CSP allows figura-hosted images. Provide `path` (a local image file), `url` (an http(s) image to fetch and re-host), or `data` (base64 bytes) + `contentType`. Accepts png/jpeg/gif/webp/avif/svg, up to 5MB. Returns `{ url }`.",inputSchema:{path:$.string().optional().describe("Local path to an image file to upload (content-type inferred from the extension)."),url:$.string().optional().describe("http(s) URL of an image to fetch and re-host (alternative to `path`) — use for expiring/signed source URLs so the fig keeps rendering after they die."),data:$.string().optional().describe("Base64-encoded image bytes (alternative to `path`/`url`). Requires `contentType`."),contentType:$.string().optional().describe("MIME type, e.g. image/png. Required with `data`; inferred from the extension/response for `path`/`url`.")}},async(Q)=>{try{let Z=Q.path??Q.url;if(Z){let{data:W,contentType:q}=await JQ(Z,Q.contentType);return J(await G("/v1/assets",{method:"POST",body:{data:W,contentType:q}}))}if(!Q.data)throw Error("Provide `path` (a local image file), `url` (an http(s) image), or `data` (base64 bytes).");if(!Q.contentType)throw Error("`contentType` is required with `data` — e.g. image/png.");return J(await G("/v1/assets",{method:"POST",body:{data:Q.data,contentType:Q.contentType}}))}catch(Z){return B(Z)}});x.registerTool("figura_generate_fig",{title:"Figura: generate fig",description:"Generate a new fig server-side from a natural-language brief, then persist it — this HOSTS it (the create IS the hosting). The engine runs Figura's on-brand generation — you do NOT write the HTML; just describe the screen. SPENDS TEAM CREDITS: only use when the user explicitly opts for a server render; otherwise default to writing the HTML yourself and landing it with figura_create_fig (free, uses the calling model). Runs as an async server job; this call polls until the fig lands (typically 30–90s). Returns the created fig (id, slug) and `viewUrl` — ALWAYS a link you can open for approval (a team-scoped viewer when unpublished, the public share url once published). Like figura_create_fig, the generated fig lands as a workspace DRAFT — not in the team library, silent for teammates — commit the session's final pick with figura_commit_fig. Requires an active paid subscription.",inputSchema:{prompt:$.string().describe("A natural-language brief describing the screen/UI to generate."),area:M(),orientation:$.enum(j).optional(),mode:$.enum(E).optional(),platform:$.enum(["mobile","web"]).optional().describe("Output platform: 'mobile' (iPhone frame) or 'web' (browser frame). When omitted, the engine INFERS it from the brief — a desktop/web/browser/landing-page/dashboard brief renders web, an iPhone/mobile/app-screen brief renders mobile — falling back to mobile only when neither is signalled. Pass this to force a platform regardless of the wording."),device:$.string().optional().describe("Catalog iPhone id to target (e.g. 'iphone-16', 'iphone-17-pro', 'iphone-se-3'). Mobile only; default iphone-16."),title:$.string().optional().describe("Title (otherwise derived from the generated HTML)."),fidelity:$.enum(["fast","high"]).optional().describe("Generation fidelity (default fast)."),publish:$.boolean().optional().describe("Publish to a shareable public URL on create (requires a paid plan). Default false — the response's `viewUrl` is already open-able team-privately, so only set this when the human explicitly wants a link they can share outside the team.")}},async(Q)=>{try{let Z={prompt:Q.prompt};for(let K of["area","orientation","mode","platform","device","title","publish"])if(Q[K]!==void 0)Z[K]=Q[K];if(Q.fidelity!==void 0)Z.model=Q.fidelity;let W=A(P);Z.toolchain=W,Z.async=!0;let q=await G("/v1/figs/generate",{method:"POST",body:Z});if(q&&typeof q==="object"&&typeof q.jobId==="string"){let K=await rQ(q.jobId),X=K.result??{};return J(N(await U(X.fig??K.result),W.skill.status))}return J(N(await U(q),W.skill.status))}catch(Z){return B(Z)}});x.registerTool("figura_fig_scaffold",{title:"Figura: fig scaffold",description:"Return the CANONICAL fig authoring scaffold — the exact system prompt Figura injects when it renders a fig server-side (design rules + exemplars + accent hints + your team's composed brand + the component/device kit context), composed for a target (platform/device/area/mode/orientation). USE THIS on the hand-build path (before writing a fig's HTML with figura_create_fig): author against this scaffold instead of a hand-maintained copy of the guidance, so your fig follows the SAME rules + brand the server would. Read-only — no fig is created, no credits are spent. Returns { scaffold, platform, mode, orientation, area, device, brand }.",inputSchema:{platform:$.enum(["mobile","web"]).optional().describe("Target platform: 'mobile' (iPhone frame, default) or 'web' (browser frame)."),device:$.string().optional().describe("Catalog iPhone id (e.g. 'iphone-16', 'iphone-17-pro', 'iphone-se-3'). Mobile only; default iphone-16."),area:M(),orientation:$.enum(j).optional(),mode:$.enum(E).optional()}},async(Q)=>{try{let Z=new URLSearchParams;for(let q of["platform","device","area","orientation","mode"])if(Q[q]!==void 0)Z.set(q,String(Q[q]));let W=Z.toString();return J(await G(`/v1/fig/scaffold${W?`?${W}`:""}`))}catch(Z){return B(Z)}});x.registerTool("figura_fig_devices",{title:"Figura: fig devices",description:"Return the CANONICAL framed-device catalog — every valid `data-device` id plus its per-device geometry (logical dims portrait/landscape, safe-area insets, cutout island|notch|none, corner radius). USE THIS when authoring a CANVAS COMPOSITION fig that frames a specific phone in-fig (a `.fig-device` element with `data-device` set): pick a real id from here instead of guessing, since an unknown data-device silently gets NO frame. Read-only — no fig is created, no credits are spent. Returns { devices, default }.",inputSchema:{}},async()=>{try{return J(await G("/v1/fig/devices"))}catch(Q){return B(Q)}});x.registerTool("figura_revise_fig",{title:"Figura: revise fig",description:"Create a new revision (version) of an existing fig from updated HTML — this HOSTS it, same as create. Returns the new fig (id, slug, version) and `viewUrl` — ALWAYS a link to open and re-review. The revision lands as a workspace DRAFT regardless of the parent's status — not in the team library, silent for teammates — so iterate freely; when a revision is the session's final agreed version, commit it (`commit: true` on that call, or figura_commit_fig). Publishing is NOT inherited from the fig being revised: the new revision defaults to unpublished (a team-scoped viewer `viewUrl`) even if the fig it revises is currently live — the existing public link keeps serving the OLD version until you pass `publish: true` on THIS call, which republishes at the SAME stable link (same publicId across the chain). The new version joins the original fig's chain — it does not replace it in place. Use list_revisions for the chain (rootFig + every version). The response also carries `brandWarnings` — a deterministic (no-LLM) colors/fonts/radii/spacing diff against the team's brand tokens, WARN-only. If it comes back non-empty, consider one more revision that binds the missing tokens. To include REAL images (screenshots/photos/logos), pass them via `images` — uploaded to durable figura hosting, stable URLs substituted into the HTML.",inputSchema:{id:$.string().describe("The fig to revise — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),html:$.string().describe("The full updated HTML document."),images:xQ(),title:$.string().optional().describe("Title (otherwise derived from the HTML)."),description:$.string().optional(),area:$.string().optional().describe("Product area / surface; free text. Inherited from the parent if omitted."),tags:$.array($.string()).optional(),orientation:$.enum(j).optional().describe("Inherited from the parent if omitted."),mode:$.enum(E).optional(),model:$.string().optional().describe("Model attribution."),issue:$.number().optional().describe("Linked issue number."),publish:$.boolean().optional().describe("Publish the new revision to a shareable public URL (requires a paid plan). Default false — the response's `viewUrl` is already open-able team-privately. If the fig being revised is ALREADY published, pass true here too or its public link keeps serving the prior version. Share link ONLY — does not commit the revision to the team library (that's `commit`)."),commit:$.boolean().optional().describe("Commit this revision to the team library (sends status: 'published'). Default false — the revision lands as a workspace DRAFT even when the fig it revises is committed. Set true ONLY when this revision is the session's final agreed version; intermediate iterations stay drafts. Committing later: figura_commit_fig."),prompt:$.string().optional().describe("OPTIONAL: the brief/ask that produced this revision, if there was one. Stored on the fig (DB-only, never stamped into the HTML), and returned by figura_get_fig.")}},async(Q)=>{try{let{html:Z,uploaded:W}=await BQ(Q.html,Q.images),q={html:Z};for(let K of["title","description","area","tags","orientation","mode","model","issue","publish","prompt"])if(Q[K]!==void 0)q[K]=Q[K];if(Q.commit)q.status="published";return J(DQ(await G(`/v1/figs/${encodeURIComponent(Q.id)}/revise`,{method:"POST",body:q}),W))}catch(Z){return B(Z)}});x.registerTool("figura_list_revisions",{title:"Figura: list revisions",description:"List the full revision chain for a fig (all versions sharing a root), oldest to newest.",inputSchema:{id:$.string().describe("Any fig in the chain — its id (`fig_…`), a UUID, share link/URL, or publicId.")}},async(Q)=>{try{return J(await G(`/v1/figs/${encodeURIComponent(Q.id)}/revisions`))}catch(Z){return B(Z)}});x.registerTool("figura_commit_fig",{title:"Figura: commit fig",description:"Commit a fig to the team library (status draft → published). Machine-created figs land as workspace DRAFTS — hosted, viewable via `viewUrl`, visible to their author, but NOT in the team library and silent for teammates. Committing is the explicit act that puts one in the team library and notifies the team (digest-batched) — so commit ONLY the session's final recommendation (the fig the user asked for / signed off on), never every exploration or intermediate iteration. If the final fig is one you're about to create/revise anyway, prefer `commit: true` on that call over a separate commit here. Orthogonal to figura_publish_fig (the public share link): a shared draft's URL resolves fine, and committing creates no link. Idempotent. Pass `uncommit: true` to reverse it (published → draft; the share link is untouched). Returns { id, status, committed, alreadyCommitted, viewUrl }.",inputSchema:{id:$.string().describe("The fig to commit — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),uncommit:$.boolean().optional().describe("Set true to uncommit: the fig leaves the team library back to an author-visible workspace draft. Defaults to false (commit).")}},async(Q)=>{try{return J(await G(`/v1/figs/${encodeURIComponent(Q.id)}/${Q.uncommit?"uncommit":"commit"}`,{method:"POST",body:{}}))}catch(Z){return B(Z)}});x.registerTool("figura_publish_fig",{title:"Figura: publish fig",description:"Publish (or unpublish) an existing fig to its shareable public URL. The fig is ALREADY hosted and viewable team-privately without this (figura_create_fig/figura_revise_fig's `viewUrl`) — only call this once the human wants a link they can share outside the team. Share link ONLY — it does not put the fig in the team library (that's figura_commit_fig; a shared draft's URL resolves fine). Requires a paid plan. Returns { isPublic, url, publicId, viewUrl }.",inputSchema:{id:$.string().describe("The fig to publish — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),isPublic:$.boolean().optional().describe("Set false to unpublish (make private). Defaults to true (publish).")}},async(Q)=>{try{let Z={};if(Q.isPublic!==void 0)Z.isPublic=Q.isPublic;return J(await G(`/v1/figs/${encodeURIComponent(Q.id)}/publish`,{method:"POST",body:Z}))}catch(Z){return B(Z)}});x.registerTool("figura_list_figs",{title:"Figura: list figs",description:"List visualizations for the team, optionally filtered by area or tag.",inputSchema:{area:M(),tag:$.string().optional(),limit:$.number().optional(),cursor:$.string().optional()}},async(Q)=>{try{let Z=new URLSearchParams;if(Q.area)Z.set("area",Q.area);if(Q.tag)Z.set("tag",Q.tag);if(Q.limit!==void 0)Z.set("limit",String(Q.limit));if(Q.cursor)Z.set("cursor",Q.cursor);let W=Z.toString();return J(await G(`/v1/figs${W?`?${W}`:""}`))}catch(Z){return B(Z)}});x.registerTool("figura_get_fig",{title:"Figura: get fig",description:"Fetch a single visualization by id. The response carries `viewUrl` — ALWAYS a link you can open for approval (a team-scoped viewer when unpublished, the public share url once published).",inputSchema:{id:$.string().describe("The fig — its id (`fig_…`), a UUID, a share link/URL, or its publicId.")}},async(Q)=>{try{return J(await G(`/v1/figs/${encodeURIComponent(Q.id)}`))}catch(Z){return B(Z)}});x.registerTool("figura_comment",{title:"Figura: comment",description:"Add a comment to a visualization.",inputSchema:{fig_id:$.string().describe("The fig to comment on — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),body:$.string().describe("Comment text.")}},async(Q)=>{try{return J(await G(`/v1/figs/${encodeURIComponent(Q.fig_id)}/comments`,{method:"POST",body:{body:Q.body}}))}catch(Z){return B(Z)}});x.registerTool("figura_request_feedback",{title:"Figura: request feedback",description:"Ask a teammate to review a fig. Resolve `from` to a team member (by name or email); they get a notification (in-app, push, email) and the discussion happens in the fig's comment thread. Use this when the user says they want a specific person's feedback/eyes/review on a fig. Returns { ok, request: { to, status }, figUrl }.",inputSchema:{id:$.string().describe("The fig to request feedback on — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),from:$.string().describe("The teammate to ask, by name or email (resolved within the team)."),note:$.string().optional().describe("Optional message for them (e.g. what to look at).")}},async(Q)=>{try{let Z={from:Q.from};if(Q.note!==void 0)Z.note=Q.note;return J(await G(`/v1/figs/${encodeURIComponent(Q.id)}/request-feedback`,{method:"POST",body:Z}))}catch(Z){return B(Z)}});x.registerTool("figura_list_sources",{title:"Figura: list sources",description:"List the company-brain source-spine connectors for the team, with event counts and last-synced times.",inputSchema:{}},async()=>{try{return J(await G("/v1/sources"))}catch(Q){return B(Q)}});x.registerTool("figura_sync_source",{title:"Figura: sync source",description:"Ingest new events from a connected source into the spine. Returns { ingested, fetched, nextCursor }.",inputSchema:{id:$.string().describe("The source id to sync (from figura_list_sources).")}},async(Q)=>{try{return J(await G(`/v1/sources/${encodeURIComponent(Q.id)}/sync`,{method:"POST"}))}catch(Z){return B(Z)}});x.registerTool("figura_mine_screens",{title:"Figura: mine screens",description:"Build the app's screen catalog from a connected git source's CURRENT file tree (framework-aware, convention-based — no file bodies, no fig generation, no credits). Returns { screens: [{slug,name,path,framework}], framework, count, commitSha, truncated }.",inputSchema:{id:$.string().describe("The git source id to mine (from figura_list_sources).")}},async(Q)=>{try{return J(await G(`/v1/sources/${encodeURIComponent(Q.id)}/mine-screens`,{method:"POST"}))}catch(Z){return B(Z)}});x.registerTool("figura_list_screens",{title:"Figura: list screens",description:"Read the team's mined screen catalog — the app's current screens ({slug,name,path,framework}) plus when it was last mined. Free, read-only. Run figura_mine_screens first to populate it.",inputSchema:{}},async()=>{try{return J(await G("/v1/sources/screens"))}catch(Q){return B(Q)}});x.registerTool("figura_update_fig",{title:"Figura: update fig",description:"Update a fig's METADATA only (title/description/area/tags/status). Set status='archived' to soft-delete. For library membership (draft ⇄ published) prefer figura_commit_fig — a status PATCH here is a silent metadata setter that never notifies the team. To change the fig's HTML, use figura_revise_fig — it saves a new version and never destroys the old one. update cannot touch the HTML.",inputSchema:{id:$.string().describe("The fig to update — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),title:$.string().optional(),description:$.string().optional(),area:M(),tags:$.array($.string()).optional().describe("Replaces the existing tags."),status:$.enum(["draft","published","archived"]).optional()}},async(Q)=>{try{let Z={};if(Q.title!==void 0)Z.title=Q.title;if(Q.description!==void 0)Z.description=Q.description;if(Q.area!==void 0)Z.area=Q.area;if(Q.tags!==void 0)Z.tags=Q.tags;if(Q.status!==void 0)Z.status=Q.status;return J(await G(`/v1/figs/${encodeURIComponent(Q.id)}`,{method:"PATCH",body:Z}))}catch(Z){return B(Z)}});x.registerTool("figura_delete_fig",{title:"Figura: delete fig",description:"Archive a fig (soft-delete; leaves the library, public link stops resolving) or permanently delete it with hard=true.",inputSchema:{id:$.string().describe("The fig to delete — its id (`fig_…`), a UUID, a share link/URL, or its publicId."),hard:$.boolean().optional().describe("Permanently delete instead of archive.")}},async(Q)=>{try{return J(await G(`/v1/figs/${encodeURIComponent(Q.id)}${Q.hard?"?hard=true":""}`,{method:"DELETE"}))}catch(Z){return B(Z)}});(async()=>{let{apiUrl:Q}=await F();await $Q(P,O,_(Q))})();await x.connect(new uQ);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "figura-mcp",
3
- "version": "0.17.0",
3
+ "version": "0.17.2",
4
4
  "description": "Model Context Protocol server for the Figura visualization SaaS",
5
5
  "license": "MIT",
6
6
  "type": "module",