@bicharts/chart-mcp 0.6.81 → 0.6.82

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.mjs +1 -1
  2. package/package.json +3 -3
package/dist/index.mjs CHANGED
@@ -245,7 +245,7 @@ data:
245
245
 
246
246
  `,a.enqueue(t.encode(o)),!0}catch(o){return this.onerror?.(o),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(a,t){try{let r=a.headers.get("accept");if(!r?.includes("application/json")||!r.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let n=a.headers.get("content-type");if(!n||!n.includes("application/json"))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let o={headers:Object.fromEntries(a.headers.entries()),url:new URL(a.url)},i;if(t?.parsedBody!==void 0)i=t.parsedBody;else try{i=await a.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let s;try{Array.isArray(i)?s=i.map(y=>j8.parse(y)):s=[j8.parse(i)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let l=s.some(qo);if(l){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(s.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!l){let y=this.validateSession(a);if(y)return y;let N=this.validateProtocolVersion(a);if(N)return N}if(!s.some(_4)){for(let y of s)this.onmessage?.(y,{authInfo:t?.authInfo,requestInfo:o});return new Response(null,{status:202})}let c=crypto.randomUUID(),d=s.find(y=>qo(y)),h=d?d.params.protocolVersion:a.headers.get("mcp-protocol-version")??Ud;if(this._enableJsonResponse)return new Promise(y=>{this._streamMapping.set(c,{resolveJson:y,cleanup:()=>{this._streamMapping.delete(c)}});for(let N of s)_4(N)&&this._requestToStreamMapping.set(N.id,c);for(let N of s)this.onmessage?.(N,{authInfo:t?.authInfo,requestInfo:o})});let m=new TextEncoder,p,g=new ReadableStream({start:y=>{p=y},cancel:()=>{this._streamMapping.delete(c)}}),f={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(f["mcp-session-id"]=this.sessionId);for(let y of s)_4(y)&&(this._streamMapping.set(c,{controller:p,encoder:m,cleanup:()=>{this._streamMapping.delete(c);try{p.close()}catch{}}}),this._requestToStreamMapping.set(y.id,c));await this.writePrimingEvent(p,m,c,h);for(let y of s){let N,k;_4(y)&&this._eventStore&&h>="2025-11-25"&&(N=()=>{this.closeSSEStream(y.id)},k=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(y,{authInfo:t?.authInfo,requestInfo:o,closeSSEStream:N,closeStandaloneSSEStream:k})}return new Response(g,{status:200,headers:f})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(r)})}}async handleDeleteRequest(a){let t=this.validateSession(a);if(t)return t;let r=this.validateProtocolVersion(a);return r||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(a){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let t=a.headers.get("mcp-session-id");if(!t)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(t!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(a){let t=a.headers.get("mcp-protocol-version");if(t!==null&&!ht.includes(t))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${ht.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${ht.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:a})=>{a()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(a){let t=this._requestToStreamMapping.get(a);if(!t)return;let r=this._streamMapping.get(t);r&&r.cleanup()}closeStandaloneSSEStream(){let a=this._streamMapping.get(this._standaloneSseStreamId);a&&a.cleanup()}async send(a,t){let r=t?.relatedRequestId;if((i4(a)||pt(a))&&(r=a.id),r===void 0){if(i4(a)||pt(a))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,a));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&this.writeSSEEvent(s.controller,s.encoder,a,i);return}let n=this._requestToStreamMapping.get(r);if(!n)throw new Error(`No connection established for request ID: ${String(r)}`);let o=this._streamMapping.get(n);if(!this._enableJsonResponse&&o?.controller&&o?.encoder){let i;this._eventStore&&(i=await this._eventStore.storeEvent(n,a)),this.writeSSEEvent(o.controller,o.encoder,a,i)}if(i4(a)||pt(a)){this._requestResponseMap.set(r,a);let i=Array.from(this._requestToStreamMapping.entries()).filter(([l,u])=>u===n).map(([l])=>l);if(i.every(l=>this._requestResponseMap.has(l))){if(!o)throw new Error(`No connection established for request ID: ${String(r)}`);if(this._enableJsonResponse&&o.resolveJson){let l={"Content-Type":"application/json"};this.sessionId!==void 0&&(l["mcp-session-id"]=this.sessionId);let u=i.map(c=>this._requestResponseMap.get(c));u.length===1?o.resolveJson(new Response(JSON.stringify(u[0]),{status:200,headers:l})):o.resolveJson(new Response(JSON.stringify(u),{status:200,headers:l}))}else o.cleanup();for(let l of i)this._requestResponseMap.delete(l),this._requestToStreamMapping.delete(l)}}}};var Cn=class{constructor(a={}){this._requestContext=new WeakMap,this._webStandardTransport=new vn(a),this._requestListener=Mu(async t=>{let r=this._requestContext.get(t);return this._webStandardTransport.handleRequest(t,{authInfo:r?.authInfo,parsedBody:r?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(a){this._webStandardTransport.onclose=a}get onclose(){return this._webStandardTransport.onclose}set onerror(a){this._webStandardTransport.onerror=a}get onerror(){return this._webStandardTransport.onerror}set onmessage(a){this._webStandardTransport.onmessage=a}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(a,t){return this._webStandardTransport.send(a,t)}async handleRequest(a,t,r){let n=a.auth;await Mu(async i=>this._webStandardTransport.handleRequest(i,{authInfo:n,parsedBody:r}),{overrideGlobalObjects:!1})(a,t)}closeSSEStream(a){this._webStandardTransport.closeSSEStream(a)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};var Y$=16*1024*1024;function Ck(e,a){let t=i=>{let s=e.indexOf(i);return s>=0&&s+1<e.length?e[s+1]:void 0},r=e.includes("--http")||/^(1|true|yes|on)$/i.test((a.BIC_MCP_HOSTED??"").trim()),n=t("--port")??a.BIC_MCP_HTTP_PORT??"8799",o=Number(n);if(!Number.isInteger(o)||o<0||o>65535)throw new Error(`--port must be a whole number from 0 to 65535 (got "${n}").`);return{http:r,host:t("--host")??"127.0.0.1",port:o}}function wn(e,a,t,r={}){if(e.headersSent){e.end();return}e.writeHead(a,{"Content-Type":"application/json","Cache-Control":"no-store",...r}),e.end(JSON.stringify(t))}function c7(e,a,t,r,n={}){wn(e,a,{jsonrpc:"2.0",error:{code:t,message:r},id:null},n)}function Q$(e,a,t){return new Promise((r,n)=>{let o=[],i=0,s=!1;e.on("data",l=>{if(!s){if(i+=l.length,i>t){s=!0,o.length=0,c7(a,413,-32600,`The request is larger than this server accepts (${Math.floor(t/1048576)} MB). Send the table at the chart's grain - aggregated - or with fewer columns.`,{Connection:"close"}),r(null);return}o.push(l)}}),e.on("end",()=>{s||r(Buffer.concat(o).toString("utf-8"))}),e.on("error",n)})}async function eH(e,a,t){let r=sS(e.headers.authorization);if(!r){c7(a,401,-32001,"Sign in to use this chart server: connect to it from your app, which sends your account's access token with each request.",{"WWW-Authenticate":"Bearer"});return}let n=await Q$(e,a,t.maxBodyBytes??Y$);if(n===null)return;let o;try{o=JSON.parse(n)}catch{c7(a,400,-32700,"Parse error: the request body isn't JSON.");return}let i=t.newServer(),s=new Cn({sessionIdGenerator:void 0});a.on("close",()=>{s.close().catch(()=>{}),i.close().catch(()=>{})}),await i.connect(s);let l=lS(e.headers[zl.toLowerCase()]);await nS({accessToken:r,...l?{clientIp:l}:{}},()=>s.handleRequest(e,a,o))}function wk(e){let a=e.log??(r=>{process.stderr.write(r+`
247
247
  `)}),t=J$((r,n)=>{let o=new URL(r.url??"/","http://localhost").pathname;if(o==="/healthz"){if(r.method!=="GET"&&r.method!=="HEAD"){wn(n,405,{error:"Use GET."},{Allow:"GET"});return}wn(n,200,{ok:!0,server:"bic-chart",version:e.version});return}if(o!=="/mcp"){wn(n,404,{error:"Not found. The MCP endpoint is /mcp."});return}if(r.method!=="POST"){c7(n,405,-32e3,"Method not allowed: this server is stateless, so it takes POST only.",{Allow:"POST"});return}eH(r,n,e).catch(i=>{a(`[bic-chart http] request failed (${i?.name??"Error"})`),c7(n,500,-32603,"Internal error: the chart server couldn't handle this request. Try again.")})});return new Promise((r,n)=>{t.once("error",n),t.listen(e.port,e.host,()=>{t.off("error",n),r(t)})})}var Pk=["assess_data_shape","list_eligible_charts","generate_chart","get_guide","preview_request"],d7="This hosted server receives your table, profiles it in memory and sends only the profile to generation; rows aren't stored or logged.",Uk={csv_path:"this hosted server can't read files on your machine, so pass the table as data or csv_text",project_dir:"this hosted server can't see your project folder, so pass language or renderer instead",out_dir:"this hosted server returns the chart inline; it can't write to your machine",preview_html:"this hosted server returns the chart inline; it can't write to your machine"},An=e=>`Not accepted by this hosted server: ${Uk[e]}.`,Mn={csv_path:U.string().optional().describe(An("csv_path")),project_dir:U.string().optional().describe(An("project_dir"))},Mk={out_dir:U.string().optional().describe(An("out_dir")),preview_html:U.boolean().optional().describe(An("preview_html"))},Ak=U.enum(["javascript","typescript","python",""]).optional(),_k=["csv_path","project_dir","out_dir","preview_html"],Tk={assess_data_shape:{description:`Profile a dataset: per-column types, cardinality, ranges, measure/dimension roles, temporal/ordinal detection, and cross-column signals (nesting, shared values, association) - the same measurement engine the BIC Power BI visual uses before generating a chart. Pass the table as data ({columns, rows}) or csv_text. ${d7} This tool sends nothing on.`,inputs:{csv_path:Mn.csv_path},refuse:["csv_path"]},list_eligible_charts:{description:"The AUTHORITATIVE list of chart types that can render this dataset - the server's own eligibility engine, NOT a guess. Pass the table as data ({columns, rows}) or csv_text. "+d7+" Ranked for JavaScript (D3) unless you pass language ('python' ranks Plotly and matplotlib) or renderer ('D3'/'PLOTLY'/... for one renderer, '' for every renderer). No model runs, but the call is METERED: free within a generous hourly allowance, then usage credits per call.",inputs:{...Mn,language:Ak.describe("Project source language: javascript/typescript ranks D3 and Vega, python ranks Plotly and matplotlib. Omit for JavaScript; `renderer`, when given, overrides it.")},refuse:["csv_path","project_dir"]},generate_chart:{description:`Generate ready-to-render chart code for a dataset: the backend picks a suitable chart type (or honors chart_type) and returns code that has passed its eligibility gates and quality checks. Pass the table as data ({columns, rows}) or csv_text. ${d7} The code and the render-ready data come back inline in the reply; this server writes no files. JavaScript (D3) unless you pass language or renderer. The D3 code is a portable render(container, data, options) function meant to be MERGED into your own app; an integration contract describes exactly how to call it. A generation uses your account's credits.`,inputs:{...Mn,...Mk,language:Ak.describe("Project source language: javascript/typescript generates D3 (the renderer @bicharts/chart-host draws), python lets the backend pick within Plotly/matplotlib. Omit for JavaScript (D3); `renderer`, when given, overrides it.")},refuse:_k},preview_request:{description:`Shows exactly what a chart generation would send on for these arguments - the measured shape of your data (column names, types, counts, ranges), the settings, and whether any sample rows travel - with the credentials removed. It sends nothing on and costs nothing. ${d7} Takes the same arguments as a generation.`,inputs:{...Mn,...Mk},refuse:_k},get_guide:{description:"How to build an app with these charts, from the guide this server ships. Free, and it sends nothing on. topic 'fabric-app' (the default) is what a Microsoft Fabric App on the Rayfin data app template needs; 'all' is the whole guide, including Blazor; 'chart-shapes' lists every chart type with the columns, limits and renderers it needs. Some steps the guide describes, the ones that write into a project, need the local server (npx -y @bicharts/chart-mcp) rather than this one."}};function Rk(e,a){let t=(a??[]).filter(r=>{let n=e?.[r];return n!=null&&n!==!1&&n!==""});return t.length===0?null:t.map(r=>`${r} isn't accepted here: ${Uk[r]}.`).join(" ")}var zk=["This is RegiaBI's hosted chart server. When a request asks for RegiaBI charts, it means these tools.",d7+" It can't read or write files on your machine: pass each table as data ({columns, rows}) or csv_text, and the chart comes back inline.","Asked which charts suit the data? Answer from list_eligible_charts, not from general knowledge.","Five rules for charts that fit on the first try:","1. Pass the chart's WHOLE result at its grain, not a sample: what fits depends on its counts.","2. Give columns the plain names your app renders with (rename Table[Column] first), unchanged at render time.","3. Call list_eligible_charts on that data before choosing, and choose what answers the question as asked. Where a chart has controls drawn inside the chart, build no input beside it.","4. Host the code with @bicharts/chart-host. generate_chart returns the code, the render-ready rows and the binding: pass them as they are, and never hand-build __rowIdx__ or __geo* columns.","5. Use `prompt` for what the chart shows; selection, cross-filtering, sizing and theming are the host's: filter with useBicFilter + selects, read a chart's sliders with useBicControls + controls (@bicharts/chart-host/react). Never write a select handler, toggle or clear.","Building an app? get_guide has the setup steps. The local server (npx -y @bicharts/chart-mcp) adds project tools that write the chart files into your app for you."].join(`
248
- `);function y8(e,a){return pn(e,a).dir??Ja(e??process.cwd())}var _u="0.6.81",Ek=[],Pn=null,k3={registerTool(e,a,t){Ek.push({name:e,config:a,cb:t})},get server(){if(!Pn)throw new Error("The local server isn't running in this process.");return Pn.server}};function Ik(e){let a=e?new C2({name:"bic-chart",version:_u},{instructions:zk}):new C2({name:"bic-chart",version:_u},{instructions:uk});e||(a.server.registerCapabilities({logging:{}}),Kb(t=>{a.server.sendLoggingMessage({level:"notice",logger:"sign-in",data:t}).catch(()=>{})}));for(let t of Ek){if(e&&!Pk.includes(t.name))continue;let r=e?Tk[t.name]:void 0,n={...t.config,...r?{description:r.description,inputSchema:{...t.config.inputSchema,...r.inputs??{}}}:{},annotations:{title:t.config.title,...t.config.annotations}},o=r?.refuse?(i,s)=>{let l=Rk(i,r.refuse);return l?{isError:!0,content:[{type:"text",text:l}]}:t.cb(i,s)}:t.cb;a.registerTool(t.name,n,o)}return a}var h7="2026-10-09T12:35:03Z src:99b988e27cce (34 files)",Pu="@bicharts/chart-host@0.6.81, @bicharts/shape-core@0.6.81",aH=U.object({columns:U.array(U.object({name:U.string(),dataType:U.enum(["String","Integer","Decimal","DateTime"]).optional().describe("Known type (DAX/semantic-model callers have it); omit to infer from values."),isMeasure:U.boolean().optional().describe("Known measure/dimension role; omit to apply the numeric-non-identifier heuristic. A semantic-model caller should set this."),format:U.string().optional().describe('Format string from the model (e.g. "$#,##0") \u2192 modelFormat.'),description:U.string().optional().describe("Column description from the model \u2192 modelDesc.")})).min(1),rows:U.array(U.union([U.array(U.any()),U.record(U.string(),U.any())])).min(1).describe("Rows as positional arrays aligned to columns, OR objects keyed by column name.")}).describe("A pre-typed {columns, rows} table (DAX query results, dataframe, arrow). Use INSTEAD of csv_path/csv_text."),Uu={csv_path:U.string().optional().describe("Path to a CSV file (header row required)."),csv_text:U.string().optional().describe("Inline CSV text (alternative to csv_path)."),data:aH.optional().describe("A pre-typed {columns, rows} table \u2014 the shape a Fabric DAX query / dataframe already has. Alternative to csv_path/csv_text; when columns carry isMeasure/format/description the shape matches PBI fidelity with no guessing."),measures:U.array(U.string()).optional().describe("Columns to treat as MEASURES (the PBI 'Values' well \u2014 fields the chart aggregates). Numeric non-identifier columns are measures by default."),dimensions:U.array(U.string()).optional().describe("Columns to treat as DIMENSIONS (a PBI category/axis well \u2014 fields to group/break by). Use for numeric codes/years that should NOT be aggregated."),formats:U.record(U.string(),U.string()).optional().describe(`Per-column number/date FORMAT STRING (e.g. {"Revenue":"$#,##0","Margin":"0.0%"}). PBI supplies these from its model; a CSV can't, so provide them to steer number formatting.`),descriptions:U.record(U.string(),U.string()).optional().describe("Per-column human DESCRIPTION \u2014 gives the model semantic context the bare column name lacks."),group_by:U.array(U.string()).optional().describe("Columns that are the PRIMARY series/breakdown (the PBI 'Group by' well); the backend leads the visualization with these."),non_additive:U.array(U.string()).optional().describe("MEASURE columns that must NOT be summed (a ratio/average/rate \u2014 use mean, never stack). Usually auto-detected; this is an authoritative override."),privacy_level:U.enum(["0","10","20","30"]).optional().describe("How much detail to compute/share: 0 names only, 10 +counts, 20 +detailed stats (default), 30 +obfuscated sample rows."),culture:U.string().regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/).max(35).optional().describe("The caller's language and region as a BCP 47 tag such as 'de-DE', 'fr' or 'ja-JP'. Default 'en-US'. It is the language the chart's own text is written in (titles, axis labels, legends, notes), and it breaks the tie when a CSV's numbers or dates are ambiguous: 12.500 as twelve thousand five hundred or twelve and a half, 05.03.2024 as 5 March or 3 May. Set it from the end user's locale when you know it; it does not translate the data.")};function f8(e){return{measures:e.measures,dimensions:e.dimensions,formats:e.formats,descriptions:e.descriptions,groupBy:e.group_by,nonAdditive:e.non_additive,privacyLevel:e.privacy_level??"20",locale:e.culture||void 0}}function Tn(e){if(e.data)return oy(e.data.columns,e.data.rows,f8(e));if(e.csv_text)return $4(e.csv_text,f8(e));if(e.csv_path)return $4(p7(Ja(e.csv_path),"utf-8"),f8(e));throw new Error("Provide one of: data ({columns, rows}), csv_text, or csv_path.")}k3.registerTool("assess_data_shape",{title:"Assess data shape",description:"Profile a dataset locally (no data leaves the machine): per-column types, cardinality, ranges, measure/dimension roles, temporal/ordinal detection, and cross-column signals (nesting, shared values, association). This is the same measurement engine the BIC Power BI visual uses before generating a chart.",inputSchema:Uu,annotations:{readOnlyHint:!0,openWorldHint:!1}},async e=>{let a=Tn(e),t={totalRows:a.totalRows,leafCardinality:a.index.getLeafCardinality(),columns:a.shape},r=g4()?null:vS(process.env);return{content:[{type:"text",text:JSON.stringify(t,null,2)},...r?[{type:"text",text:r}]:[]]}});k3.registerTool("get_guide",{title:"Read the build guide",description:"How to build an app with these charts, from the guide this package ships. Local and free: no network, no credentials. topic 'fabric-app' (the default) is what a Microsoft Fabric App on the Rayfin data app template needs: what to pull, generating, wiring in React, the Fabric App section and the time-savers. 'all' is the whole guide, including Blazor. 'chart-shapes' lists every chart type with the columns, limits and renderers it needs.",inputSchema:{topic:U.enum(hk).optional().describe("'fabric-app' (default), 'all', or 'chart-shapes'.")},annotations:{readOnlyHint:!0,openWorldHint:!1}},async e=>{try{return{content:[{type:"text",text:pk(e.topic??"fabric-app")}]}}catch(a){return{isError:!0,content:[{type:"text",text:`The guide could not be read from this package (${a?.message??a}). It is also published as skills/bic-charts/SKILL.md inside @bicharts/chart-mcp on npm.`}]}}});k3.registerTool("list_eligible_charts",{title:"List eligible chart types",description:"The AUTHORITATIVE list of chart types that can render this dataset \u2014 the server's own eligibility engine, NOT a local guess. Profiles the data locally, then sends that profile to the backend. NO LLM in the loop, but this is a NETWORK call and it is METERED \u2014 see the licensing note below. By default the tool DETECTS the project's language (JS/TS vs Python from the working dir) and returns the charts for THAT language, SCOPED and ordered by how well each type fits this data (best first; `order: 'variety'` favors newer and less-common types instead), each tagged with its source language and renderer. Pass `language` ('javascript'|'python') to force it, or `renderer` ('D3'/'PLOTLY'/\u2026) to rank one specific renderer, or renderer '' for the full renderer-agnostic eligibility across ALL renderers (also ranked, by chart type alone, with no renderer/language tag). If the language can't be auto-detected and none is given, the tool asks you to specify one. Needs an account: eligibility IS the engine, so programmatic access to it is licensed. With nothing configured, the first call opens a browser sign-in, waits for it and then answers (a license key in the environment is the alternative for a machine with no browser). Free within a generous hourly allowance; beyond it each call draws usage credits. The reply carries a text block and a structured table: one row per chart type with its rank, name, preview flag, fit verdict, description, language and renderer. Rows flagged alsoWorthALook are a few picks from below the top fits, drawn so an offer can include something different; the fit order itself never changes.",inputSchema:{...Uu,language:U.enum(["javascript","typescript","python",""]).optional().describe("Project source language \u2192 the server ranks across that language's renderers (javascript/typescript = D3/Vega, python = Plotly/matplotlib). Omit to AUTO-DETECT from the working dir; `renderer` (if given) overrides this."),project_dir:U.string().optional().describe("Directory to auto-detect the project language from (default: the folder setup_fabric_app used, else the working directory or the one project folder directly inside it)."),renderer:U.enum(["D3","PLOTLY","PYMATPLOT","VEGA",""]).optional().describe("Force a specific renderer (overrides `language`): a concrete renderer ranks that renderer's charts; '' = the full renderer-agnostic eligibility (all renderers, ranked by chart type alone). Omit to use `language`/auto-detection."),level_of_detail:U.enum(["High","Medium","Low",""]).optional().describe("The user's own preference for how much of the data to see, as they've stated it. 'High' = every observation as its own mark, 'Medium' = every row shown as a distribution, 'Low' = one mark per category. Ranks this list the same way a generation would. Unset when they haven't stated one; unset changes nothing."),name_filter:U.string().optional().describe("Show only chart types matching this text (the same matcher the Power BI and Excel chart-type lists use). Three tiers, first non-empty one wins outright: the term starting a WORD in the name ('gan' -> Gantt chart, and NOT Organization chart), then mid-word in the name ('eth' -> Choropleth), then the description. A name match therefore SUPPRESSES description matches. Case- and accent-insensitive and, by default, space- and punctuation-insensitive too ('barchart' and 'bar-chart' find Bar chart; see name_filter_match). Minimum two characters, and it never reorders - the picker's ranking is preserved and the ranks stay as issued. Applied after ranking and before `top`."),name_filter_match:U.enum(["loose","exact"]).optional().describe("How name_filter matches a name. 'loose' (the default) ignores accents, case, spaces and punctuation, so 'barchart' finds Bar chart. 'exact' folds accents and case and collapses repeated spaces, and nothing else: a name typed without its space or hyphen matches nothing. The same setting the Power BI and Excel chart-type lists offer."),order:U.enum(["fit","variety"]).optional().describe("How the list is ordered. 'fit' (the default) = by how well each chart type fits THIS data, nothing else - use it to choose a chart for a question. 'variety' = the picker's selection order, which favors newer and less-common types on purpose - use it when the user wants to explore or be surprised. Both lists hold the same chart types; only the order differs."),top:U.number().optional().describe("Show only the top-N ranked results. Omit for all."),width:U.number().optional().describe("Viewport width px (default 800) \u2014 affects small-viewport / facet-budget gates."),height:U.number().optional().describe("Viewport height px (default 600).")},outputSchema:sk,annotations:{readOnlyHint:!0,openWorldHint:!0}},async e=>{let a=Tn(e),t="",r="",n="",o="";if(e.renderer!==void 0)t=e.renderer;else if(e.language)r=e.language;else if(g4())r="javascript",n=" (language: javascript, this server's default - pass language or renderer for another)";else{let N=dn(y8(e.project_dir,l8));N.language?(r=N.language,n=` (auto-detected language: ${N.language} \u2014 ${N.reason})`):o=`Couldn't tell the project's language (${N.reason}), so this is the list across all renderers; pass language: "javascript" or "python", or project_dir, to narrow it.
248
+ `);function y8(e,a){return pn(e,a).dir??Ja(e??process.cwd())}var _u="0.6.82",Ek=[],Pn=null,k3={registerTool(e,a,t){Ek.push({name:e,config:a,cb:t})},get server(){if(!Pn)throw new Error("The local server isn't running in this process.");return Pn.server}};function Ik(e){let a=e?new C2({name:"bic-chart",version:_u},{instructions:zk}):new C2({name:"bic-chart",version:_u},{instructions:uk});e||(a.server.registerCapabilities({logging:{}}),Kb(t=>{a.server.sendLoggingMessage({level:"notice",logger:"sign-in",data:t}).catch(()=>{})}));for(let t of Ek){if(e&&!Pk.includes(t.name))continue;let r=e?Tk[t.name]:void 0,n={...t.config,...r?{description:r.description,inputSchema:{...t.config.inputSchema,...r.inputs??{}}}:{},annotations:{title:t.config.title,...t.config.annotations}},o=r?.refuse?(i,s)=>{let l=Rk(i,r.refuse);return l?{isError:!0,content:[{type:"text",text:l}]}:t.cb(i,s)}:t.cb;a.registerTool(t.name,n,o)}return a}var h7="2026-10-09T13:10:06Z src:190b43a88a22 (34 files)",Pu="@bicharts/chart-host@0.6.82, @bicharts/shape-core@0.6.82",aH=U.object({columns:U.array(U.object({name:U.string(),dataType:U.enum(["String","Integer","Decimal","DateTime"]).optional().describe("Known type (DAX/semantic-model callers have it); omit to infer from values."),isMeasure:U.boolean().optional().describe("Known measure/dimension role; omit to apply the numeric-non-identifier heuristic. A semantic-model caller should set this."),format:U.string().optional().describe('Format string from the model (e.g. "$#,##0") \u2192 modelFormat.'),description:U.string().optional().describe("Column description from the model \u2192 modelDesc.")})).min(1),rows:U.array(U.union([U.array(U.any()),U.record(U.string(),U.any())])).min(1).describe("Rows as positional arrays aligned to columns, OR objects keyed by column name.")}).describe("A pre-typed {columns, rows} table (DAX query results, dataframe, arrow). Use INSTEAD of csv_path/csv_text."),Uu={csv_path:U.string().optional().describe("Path to a CSV file (header row required)."),csv_text:U.string().optional().describe("Inline CSV text (alternative to csv_path)."),data:aH.optional().describe("A pre-typed {columns, rows} table \u2014 the shape a Fabric DAX query / dataframe already has. Alternative to csv_path/csv_text; when columns carry isMeasure/format/description the shape matches PBI fidelity with no guessing."),measures:U.array(U.string()).optional().describe("Columns to treat as MEASURES (the PBI 'Values' well \u2014 fields the chart aggregates). Numeric non-identifier columns are measures by default."),dimensions:U.array(U.string()).optional().describe("Columns to treat as DIMENSIONS (a PBI category/axis well \u2014 fields to group/break by). Use for numeric codes/years that should NOT be aggregated."),formats:U.record(U.string(),U.string()).optional().describe(`Per-column number/date FORMAT STRING (e.g. {"Revenue":"$#,##0","Margin":"0.0%"}). PBI supplies these from its model; a CSV can't, so provide them to steer number formatting.`),descriptions:U.record(U.string(),U.string()).optional().describe("Per-column human DESCRIPTION \u2014 gives the model semantic context the bare column name lacks."),group_by:U.array(U.string()).optional().describe("Columns that are the PRIMARY series/breakdown (the PBI 'Group by' well); the backend leads the visualization with these."),non_additive:U.array(U.string()).optional().describe("MEASURE columns that must NOT be summed (a ratio/average/rate \u2014 use mean, never stack). Usually auto-detected; this is an authoritative override."),privacy_level:U.enum(["0","10","20","30"]).optional().describe("How much detail to compute/share: 0 names only, 10 +counts, 20 +detailed stats (default), 30 +obfuscated sample rows."),culture:U.string().regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/).max(35).optional().describe("The caller's language and region as a BCP 47 tag such as 'de-DE', 'fr' or 'ja-JP'. Default 'en-US'. It is the language the chart's own text is written in (titles, axis labels, legends, notes), and it breaks the tie when a CSV's numbers or dates are ambiguous: 12.500 as twelve thousand five hundred or twelve and a half, 05.03.2024 as 5 March or 3 May. Set it from the end user's locale when you know it; it does not translate the data.")};function f8(e){return{measures:e.measures,dimensions:e.dimensions,formats:e.formats,descriptions:e.descriptions,groupBy:e.group_by,nonAdditive:e.non_additive,privacyLevel:e.privacy_level??"20",locale:e.culture||void 0}}function Tn(e){if(e.data)return oy(e.data.columns,e.data.rows,f8(e));if(e.csv_text)return $4(e.csv_text,f8(e));if(e.csv_path)return $4(p7(Ja(e.csv_path),"utf-8"),f8(e));throw new Error("Provide one of: data ({columns, rows}), csv_text, or csv_path.")}k3.registerTool("assess_data_shape",{title:"Assess data shape",description:"Profile a dataset locally (no data leaves the machine): per-column types, cardinality, ranges, measure/dimension roles, temporal/ordinal detection, and cross-column signals (nesting, shared values, association). This is the same measurement engine the BIC Power BI visual uses before generating a chart.",inputSchema:Uu,annotations:{readOnlyHint:!0,openWorldHint:!1}},async e=>{let a=Tn(e),t={totalRows:a.totalRows,leafCardinality:a.index.getLeafCardinality(),columns:a.shape},r=g4()?null:vS(process.env);return{content:[{type:"text",text:JSON.stringify(t,null,2)},...r?[{type:"text",text:r}]:[]]}});k3.registerTool("get_guide",{title:"Read the build guide",description:"How to build an app with these charts, from the guide this package ships. Local and free: no network, no credentials. topic 'fabric-app' (the default) is what a Microsoft Fabric App on the Rayfin data app template needs: what to pull, generating, wiring in React, the Fabric App section and the time-savers. 'all' is the whole guide, including Blazor. 'chart-shapes' lists every chart type with the columns, limits and renderers it needs.",inputSchema:{topic:U.enum(hk).optional().describe("'fabric-app' (default), 'all', or 'chart-shapes'.")},annotations:{readOnlyHint:!0,openWorldHint:!1}},async e=>{try{return{content:[{type:"text",text:pk(e.topic??"fabric-app")}]}}catch(a){return{isError:!0,content:[{type:"text",text:`The guide could not be read from this package (${a?.message??a}). It is also published as skills/bic-charts/SKILL.md inside @bicharts/chart-mcp on npm.`}]}}});k3.registerTool("list_eligible_charts",{title:"List eligible chart types",description:"The AUTHORITATIVE list of chart types that can render this dataset \u2014 the server's own eligibility engine, NOT a local guess. Profiles the data locally, then sends that profile to the backend. NO LLM in the loop, but this is a NETWORK call and it is METERED \u2014 see the licensing note below. By default the tool DETECTS the project's language (JS/TS vs Python from the working dir) and returns the charts for THAT language, SCOPED and ordered by how well each type fits this data (best first; `order: 'variety'` favors newer and less-common types instead), each tagged with its source language and renderer. Pass `language` ('javascript'|'python') to force it, or `renderer` ('D3'/'PLOTLY'/\u2026) to rank one specific renderer, or renderer '' for the full renderer-agnostic eligibility across ALL renderers (also ranked, by chart type alone, with no renderer/language tag). If the language can't be auto-detected and none is given, the tool asks you to specify one. Needs an account: eligibility IS the engine, so programmatic access to it is licensed. With nothing configured, the first call opens a browser sign-in, waits for it and then answers (a license key in the environment is the alternative for a machine with no browser). Free within a generous hourly allowance; beyond it each call draws usage credits. The reply carries a text block and a structured table: one row per chart type with its rank, name, preview flag, fit verdict, description, language and renderer. Rows flagged alsoWorthALook are a few picks from below the top fits, drawn so an offer can include something different; the fit order itself never changes.",inputSchema:{...Uu,language:U.enum(["javascript","typescript","python",""]).optional().describe("Project source language \u2192 the server ranks across that language's renderers (javascript/typescript = D3/Vega, python = Plotly/matplotlib). Omit to AUTO-DETECT from the working dir; `renderer` (if given) overrides this."),project_dir:U.string().optional().describe("Directory to auto-detect the project language from (default: the folder setup_fabric_app used, else the working directory or the one project folder directly inside it)."),renderer:U.enum(["D3","PLOTLY","PYMATPLOT","VEGA",""]).optional().describe("Force a specific renderer (overrides `language`): a concrete renderer ranks that renderer's charts; '' = the full renderer-agnostic eligibility (all renderers, ranked by chart type alone). Omit to use `language`/auto-detection."),level_of_detail:U.enum(["High","Medium","Low",""]).optional().describe("The user's own preference for how much of the data to see, as they've stated it. 'High' = every observation as its own mark, 'Medium' = every row shown as a distribution, 'Low' = one mark per category. Ranks this list the same way a generation would. Unset when they haven't stated one; unset changes nothing."),name_filter:U.string().optional().describe("Show only chart types matching this text (the same matcher the Power BI and Excel chart-type lists use). Three tiers, first non-empty one wins outright: the term starting a WORD in the name ('gan' -> Gantt chart, and NOT Organization chart), then mid-word in the name ('eth' -> Choropleth), then the description. A name match therefore SUPPRESSES description matches. Case- and accent-insensitive and, by default, space- and punctuation-insensitive too ('barchart' and 'bar-chart' find Bar chart; see name_filter_match). Minimum two characters, and it never reorders - the picker's ranking is preserved and the ranks stay as issued. Applied after ranking and before `top`."),name_filter_match:U.enum(["loose","exact"]).optional().describe("How name_filter matches a name. 'loose' (the default) ignores accents, case, spaces and punctuation, so 'barchart' finds Bar chart. 'exact' folds accents and case and collapses repeated spaces, and nothing else: a name typed without its space or hyphen matches nothing. The same setting the Power BI and Excel chart-type lists offer."),order:U.enum(["fit","variety"]).optional().describe("How the list is ordered. 'fit' (the default) = by how well each chart type fits THIS data, nothing else - use it to choose a chart for a question. 'variety' = the picker's selection order, which favors newer and less-common types on purpose - use it when the user wants to explore or be surprised. Both lists hold the same chart types; only the order differs."),top:U.number().optional().describe("Show only the top-N ranked results. Omit for all."),width:U.number().optional().describe("Viewport width px (default 800) \u2014 affects small-viewport / facet-budget gates."),height:U.number().optional().describe("Viewport height px (default 600).")},outputSchema:sk,annotations:{readOnlyHint:!0,openWorldHint:!0}},async e=>{let a=Tn(e),t="",r="",n="",o="";if(e.renderer!==void 0)t=e.renderer;else if(e.language)r=e.language;else if(g4())r="javascript",n=" (language: javascript, this server's default - pass language or renderer for another)";else{let N=dn(y8(e.project_dir,l8));N.language?(r=N.language,n=` (auto-detected language: ${N.language} \u2014 ${N.reason})`):o=`Couldn't tell the project's language (${N.reason}), so this is the list across all renderers; pass language: "javascript" or "python", or project_dir, to narrow it.
249
249
  `}let i=await Ll({shape:a.shape,totalRows:a.totalRows,leafCardinality:a.index.getLeafCardinality(),geoExtent:a.index.getGeoExtent(),width:e.width,height:e.height,renderer:t,language:r,levelOfDetail:e.level_of_detail||void 0,order:e.order??"fit"});if(!i.ok)return{isError:!0,content:[{type:"text",text:nu(i)?i.errorMessage:`Could not list eligible charts: ${i.errorMessage}`}]};let s=i.charts.length>0&&i.charts[0].rank!==void 0,l=r?`${r}`:t||"all renderers",u=i.charts,c=u.length,d="all",h=N=>lk({rows:N,order:e.order??"fit",eligibleCount:c,filter:e.name_filter?{text:e.name_filter,tier:d}:null,metering:t7}),m=ob(e.name_filter_match),p=q2(u,e.name_filter,Br,m);u=p.rows,d=p.tier;let g;if(s){e.top&&e.top>0&&(u=u.slice(0,e.top));let N=(e.order??"fit")==="variety"?'ordered for variety (newer and less-common types first; order: "fit" ranks by fit to this data)':'ordered by fit to this data (order: "variety" favors newer and less-common types)';g=`Top ${u.length} chart type(s) for this data in ${l}, ${N} (authoritative \u2014 the server's eligibility engine; ${t7})${n}:`}else g=`${u.length} chart type(s) can render this data \u2014 renderer-agnostic eligibility (authoritative \u2014 the server's eligibility engine; ${t7}):`;if(g=o+g,p.tier!=="all"){let N=p.tier==="desc"?" (no NAME matched; these matched on description)":p.tier==="namePart"?" (matched mid-word in the name)":"";g=`Filtered to "${e.name_filter}"${N}: ${u.length} of ${c} eligible chart type(s). The other ${c-u.length} are eligible and simply do not match the filter.
250
250
  `+g}let f=ik(u);if(u.length===0&&p.tier!=="all"&&c>0){let N=q2(i.refused,e.name_filter,ib,m),k=N.tier==="name"||N.tier==="namePart"?N.rows.filter(_=>_.reason).slice(0,3):[],w=k.length>0?`
251
251
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bicharts/chart-mcp",
3
- "version": "0.6.81",
3
+ "version": "0.6.82",
4
4
  "description": "MCP (Model Context Protocol) stdio server for BIC AI charts: profile a dataset locally, then generate chart code that has passed the BIC backend's render gates. Works with any MCP-capable client (Claude Code, Claude Desktop, Cursor, Copilot Studio). An account pays to author charts; the code it writes is yours and runs with no licence.",
5
5
  "keywords": [
6
6
  "mcp",
@@ -47,8 +47,8 @@
47
47
  },
48
48
  "// dependencies": "NONE, deliberately. dist/ bundles every module the server uses, so a runtime dependency installs nothing it needs - it only makes npx fetch that package (and its tree) before the first start. Everything the bundle carries is a devDependency; scripts/verify-package.mjs fails the release if a dependency appears or a shipped file imports anything but Node's built-ins.",
49
49
  "devDependencies": {
50
- "@bicharts/chart-host": "^0.6.81",
51
- "@bicharts/shape-core": "^0.6.81",
50
+ "@bicharts/chart-host": "^0.6.82",
51
+ "@bicharts/shape-core": "^0.6.82",
52
52
  "@modelcontextprotocol/sdk": "^1.0.0",
53
53
  "@types/node": "^20.0.0",
54
54
  "@types/papaparse": "^5.3.14",