@bicharts/chart-mcp 0.6.120 → 0.6.121

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -366,7 +366,7 @@ data:
366
366
 
367
367
  `,t.enqueue(a.encode(i)),!0}catch(i){return this.onerror?.(i),!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(t,a){try{let r=t.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=t.headers.get("content-type");if(!UO(n))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 i={headers:Object.fromEntries(t.headers.entries()),url:new URL(t.url)},o;if(a?.parsedBody!==void 0)o=a.parsedBody;else try{let b=await RO(t,this._maxRequestBodySize);if(b.tooLarge){let v=TO(this._maxRequestBodySize);return this.onerror?.(new Error(v)),this.createJsonErrorResponse(413,-32e3,v)}o=JSON.parse(b.text)}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}if(Array.isArray(o)&&o.length>100)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${100} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${100} messages`);let s;try{Array.isArray(o)?s=o.map(b=>V2.parse(b)):s=[V2.parse(o)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let l=s.some(pp);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 b=this.validateSession(t);if(b)return b;let v=this.validateProtocolVersion(t);if(v)return v}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!s.some(vn)){for(let b of s)this.onmessage?.(b,{authInfo:a?.authInfo,requestInfo:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),d=s.find(b=>pp(b)),h=d?d.params.protocolVersion:t.headers.get("mcp-protocol-version")??wW;if(this._enableJsonResponse)return new Promise(b=>{this._streamMapping.set(c,{resolveJson:b,cleanup:()=>{this._streamMapping.delete(c)}});for(let v of s)vn(v)&&this._requestToStreamMapping.set(v.id,c);for(let v of s)this.onmessage?.(v,{authInfo:a?.authInfo,requestInfo:i})});let p=new TextEncoder,m,g,f=new ReadableStream({start:b=>{m=b},cancel:()=>{g!==void 0&&clearInterval(g),this._streamMapping.get(c)?.controller===m&&this._streamMapping.delete(c)}}),y={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(y["mcp-session-id"]=this.sessionId);for(let b of s)vn(b)&&(this._streamMapping.set(c,{controller:m,encoder:p,cleanup:()=>{g!==void 0&&clearInterval(g),this._streamMapping.delete(c);try{m.close()}catch{}}}),this._requestToStreamMapping.set(b.id,c));try{await this.writePrimingEvent(m,p,c,h);for(let b of s){let v,k;vn(b)&&this._eventStore&&h>="2025-11-25"&&(v=()=>{this.closeSSEStream(b.id)},k=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(b,{authInfo:a?.authInfo,requestInfo:i,closeSSEStream:v,closeStandaloneSSEStream:k})}}catch(b){this._streamMapping.get(c)?.cleanup(),this._resumableStreams.delete(c);for(let v of s)vn(v)&&this._requestToStreamMapping.delete(v.id);throw b}return this._streamMapping.get(c)?.controller===m&&(g=this.startKeepAlive(m,p)),new Response(f,{status:200,headers:y})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(r)})}}async handleDeleteRequest(t){let a=this.validateSession(t);if(a)return a;let r=this.validateProtocolVersion(t);if(r)return r;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(t){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 a=t.headers.get("mcp-session-id");if(!a)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(a!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let a=t.headers.get("mcp-protocol-version");if(a!==null&&!ti.includes(a))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${a} (supported versions: ${ti.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${a} (supported versions: ${ti.join(", ")})`)}async close(){this._closed||(this._closed=!0,this._streamMapping.forEach(({cleanup:t})=>{t()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.clear(),this.onclose?.())}closeSSEStream(t){let a=this._requestToStreamMapping.get(t);if(!a)return;let r=this._streamMapping.get(a);r&&r.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,a){let r=a?.relatedRequestId;if((Nn(t)||ai(t))&&(r=t.id),r===void 0){if(Nn(t)||ai(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let o;this._eventStore&&(o=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&(o===void 0||!s.replayedEventIds?.has(o))&&this.writeSSEEvent(s.controller,s.encoder,t,o);return}let n=this._requestToStreamMapping.get(r);if(!n)throw new Error(`No connection established for request ID: ${String(r)}`);let i=this._streamMapping.get(n);if(!this._enableJsonResponse){let o;this._eventStore&&(o=await this._eventStore.storeEvent(n,t),i=this._streamMapping.get(n)),i?.controller&&i?.encoder&&(o===void 0||!i.replayedEventIds?.has(o))&&this.writeSSEEvent(i.controller,i.encoder,t,o)&&o!==void 0&&this._resumableStreams.add(n)}if(Nn(t)||ai(t)){this._requestResponseMap.set(r,t);let o=Array.from(this._requestToStreamMapping.entries()).filter(([l,u])=>u===n).map(([l])=>l);if(o.every(l=>this._requestResponseMap.has(l))){if(!i){if(this._closed){for(let l of o)this._requestResponseMap.delete(l),this._requestToStreamMapping.delete(l);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(n)){for(let l of o)this._requestResponseMap.delete(l),this._requestToStreamMapping.delete(l);this._resumableStreams.delete(n);return}for(let l of o)this._requestResponseMap.delete(l),this._requestToStreamMapping.delete(l);throw new Error(`No connection established for request ID: ${String(r)}`)}if(this._enableJsonResponse&&i.resolveJson){let l={"Content-Type":"application/json"};this.sessionId!==void 0&&(l["mcp-session-id"]=this.sessionId);let u=o.map(c=>this._requestResponseMap.get(c));u.length===1?i.resolveJson(new Response(JSON.stringify(u[0]),{status:200,headers:l})):i.resolveJson(new Response(JSON.stringify(u),{status:200,headers:l}))}else i.cleanup();for(let l of o)this._requestResponseMap.delete(l),this._requestToStreamMapping.delete(l);this._resumableStreams.delete(n)}}}};var iu=class{constructor(t={}){this._requestContext=new WeakMap,this._webStandardTransport=new ru(t),this._requestListener=Zv(async a=>{let r=this._requestContext.get(a);return this._webStandardTransport.handleRequest(a,{authInfo:r?.authInfo,parsedBody:r?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(t){this._webStandardTransport.onclose=t}get onclose(){return this._webStandardTransport.onclose}set onerror(t){this._webStandardTransport.onerror=t}get onerror(){return this._webStandardTransport.onerror}set onmessage(t){this._webStandardTransport.onmessage=t}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(t,a){return this._webStandardTransport.send(t,a)}async handleRequest(t,a,r){let n=t.auth;await Zv(async o=>this._webStandardTransport.handleRequest(o,{authInfo:n,parsedBody:r}),{overrideGlobalObjects:!1})(t,a)}closeSSEStream(t){this._webStandardTransport.closeSSEStream(t)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};var rse=16*1024*1024;function $O(e,t){let a=o=>{let s=e.indexOf(o);return s>=0&&s+1<e.length?e[s+1]:void 0},r=e.includes("--http")||/^(1|true|yes|on)$/i.test((t.BIC_MCP_HOSTED??"").trim()),n=a("--port")??t.BIC_MCP_HTTP_PORT??"8799",i=Number(n);if(!Number.isInteger(i)||i<0||i>65535)throw new Error(`--port must be a whole number from 0 to 65535 (got "${n}").`);return{http:r,host:a("--host")??"127.0.0.1",port:i}}function ou(e,t,a,r={}){if(e.headersSent){e.end();return}e.writeHead(t,{"Content-Type":"application/json","Cache-Control":"no-store",...r}),e.end(JSON.stringify(a))}function Es(e,t,a,r,n={}){ou(e,t,{jsonrpc:"2.0",error:{code:a,message:r},id:null},n)}function ise(e,t,a){return new Promise((r,n)=>{let i=[],o=0,s=!1;e.on("data",l=>{if(!s){if(o+=l.length,o>a){s=!0,i.length=0,Es(t,413,-32600,`The request is larger than this server accepts (${Math.floor(a/1048576)} MB). Send the table at the chart's grain - aggregated - or with fewer columns.`,{Connection:"close"}),r(null);return}i.push(l)}}),e.on("end",()=>{s||r(Buffer.concat(i).toString("utf-8"))}),e.on("error",n)})}async function ose(e,t,a){let r=TT(e.headers.authorization);if(!r){Es(t,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 ise(e,t,a.maxBodyBytes??rse);if(n===null)return;let i;try{i=JSON.parse(n)}catch{Es(t,400,-32700,"Parse error: the request body isn't JSON.");return}let o=a.newServer(),s=new iu({sessionIdGenerator:void 0});t.on("close",()=>{s.close().catch(()=>{}),o.close().catch(()=>{})}),await o.connect(s);let l=ET(e.headers[wb.toLowerCase()]);await IT({accessToken:r,...l?{clientIp:l}:{}},()=>s.handleRequest(e,t,i))}function OO(e){let t=e.log??(r=>{process.stderr.write(r+`
368
368
  `)}),a=nse((r,n)=>{let i=new URL(r.url??"/","http://localhost").pathname;if(i==="/healthz"){if(r.method!=="GET"&&r.method!=="HEAD"){ou(n,405,{error:"Use GET."},{Allow:"GET"});return}ou(n,200,{ok:!0,server:"bic-chart",version:e.version});return}if(i!=="/mcp"){ou(n,404,{error:"Not found. The MCP endpoint is /mcp."});return}if(r.method!=="POST"){Es(n,405,-32e3,"Method not allowed: this server is stateless, so it takes POST only.",{Allow:"POST"});return}ose(r,n,e).catch(o=>{t(`[bic-chart http] request failed (${o?.name??"Error"})`),Es(n,500,-32603,"Internal error: the chart server couldn't handle this request. Try again.")})});return new Promise((r,n)=>{a.once("error",n),a.listen(e.port,e.host,()=>{a.off("error",n),r(a)})})}var jO=["assess_data_shape","list_eligible_charts","generate_chart","get_guide","preview_request","check_request"],mo="This hosted server receives your table, profiles it in memory and sends only the profile to generation; rows aren't stored or logged.",FO={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"},su=e=>`Not accepted by this hosted server: ${FO[e]}.`,Rs={csv_path:_.string().optional().describe(su("csv_path")),project_dir:_.string().optional().describe(su("project_dir"))},DO={out_dir:_.string().optional().describe(su("out_dir")),preview_html:_.boolean().optional().describe(su("preview_html"))},Qv=_.enum(["javascript","typescript","python",""]).optional(),LO=["csv_path","project_dir","out_dir","preview_html"],BO={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. ${mo} This tool sends nothing on.`,inputs:{csv_path:Rs.csv_path},refuse:["csv_path"]},list_eligible_charts:{description:"The AUTHORITATIVE list of chart types (maps, tables a reader works with and app widgets included) that can render this dataset - the server's own eligibility engine, NOT a guess. Pass the table as data ({columns, rows}) or csv_text. "+mo+" 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:{...Rs,language:Qv.describe("Project source language: javascript/typescript ranks D3, 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. ${mo} 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. ${sl}`,inputs:{...Rs,...DO,language:Qv.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:LO},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. ${mo} Takes the same arguments as a generation.`,inputs:{...Rs,...DO},refuse:LO},check_request:{description:`Checks a chart request against this data before anything is generated. Takes the same arguments as a generation - the chart type and every setting (date grain, limit, overlay, required columns, rows policy, data labels and the rest) - and answers, in the server's own words, each ask this data can't honor and why: a channel the data doesn't have, too little of one for the ask, or a name the catalog doesn't know. When the chart type itself is denied, it also lists up to five chart types that fit this data, best fit first. An OK names the asks it checked. Pass the table as data ({columns, rows}) or csv_text. ${mo} No model runs and no generation credits are spent, but the call is METERED like the eligibility list: free within a generous hourly allowance, then usage credits per call. The reply carries a text block and a structured result: the verdict (OK or DENY), the asks checked, each finding with its kind and reason, and the alternatives.`,inputs:{...Rs,language:Qv.describe("Project source language: javascript/typescript checks the request as a D3 generation, python as a Plotly/matplotlib one. Omit for JavaScript (D3); `renderer`, when given, overrides it.")},refuse:["csv_path","project_dir"]},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; 'settings' lists the choices a person can make about a chart, with their options and defaults. 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 HO(e,t){let a=(t??[]).filter(r=>{let n=e?.[r];return n!=null&&n!==!1&&n!==""});return a.length===0?null:a.map(r=>`${r} isn't accepted here: ${FO[r]}.`).join(" ")}var GO=["This is RegiaBI's hosted chart server: it builds charts, maps, tables a reader works with and app widgets from a table you send. A request for RegiaBI means these tools.",mo+" It can't reach your files: pass each table as data ({columns, rows}) or csv_text; the chart returns inline.","Which visuals suit the data? Answer from list_eligible_charts, not general knowledge.","Six rules for charts that fit on the first try:","1. Pass the chart's WHOLE result at its grain, not a sample: counts decide what fits.","2. Name columns as your app renders them (rename Table[Column]), unchanged at render time.","3. To pick a type, call list_eligible_charts on that data first and choose what answers the question as asked. Pass chart_type only for a type the person named; else leave it unset and the engine chooses. Named a type or ask? Run check_request first; say what it denies and why, don't generate around it. Build no input beside a visual's own controls.","4. Host the code with @bicharts/chart-host. generate_chart returns the code, the render-ready rows and the binding: pass them as is; 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 (a lasso too), read a chart's sliders with useBicControls + controls (@bicharts/chart-host/react). Never write a select handler, toggle or clear.","6. The person chooses chart forms (familiar or unusual), language and region, and how much data shows and which way is good (get_guide topic 'settings'). Unstated: ask once, one question listing the options, before the first generate_chart; pass only what they say, never a guess from the data. Can't ask: use defaults and report in your final message what `settings` shows the engine chose.","Building an app? get_guide has the setup; the local server (npx -y @bicharts/chart-mcp) writes into your app."].join(`
369
- `);function $s(e,t){return Ol(e,t).dir??Dr(e??process.cwd())}var tN="0.6.120",VO=[],fo=null,q1={registerTool(e,t,a){VO.push({name:e,config:t,cb:a})},get server(){if(!fo)throw new Error("The local server isn't running in this process.");return fo.server}};function XO(e){let t=e?new R8({name:"bic-chart",version:tN},{instructions:GO}):new R8({name:"bic-chart",version:tN},{instructions:q$});e||(t.server.registerCapabilities({logging:{}}),vT(a=>{t.server.sendLoggingMessage({level:"notice",logger:"sign-in",data:a}).catch(()=>{})}));for(let a of VO){if(e&&!jO.includes(a.name))continue;let r=e?BO[a.name]:void 0,n={...a.config,...r?{description:r.description,inputSchema:{...a.config.inputSchema,...r.inputs??{}}}:{},annotations:{title:a.config.title,...a.config.annotations}},i=r?.refuse?(o,s)=>{let l=HO(o,r.refuse);return l?{isError:!0,content:[{type:"text",text:l}]}:a.cb(o,s)}:a.cb;t.registerTool(a.name,n,i)}return t}var zs="2026-11-12T18:45:57Z src:0e8d9d91d5e2 (46 files)",aN="@bicharts/chart-host@0.6.120, @bicharts/shape-core@0.6.120",sse=_.object({columns:_.array(_.object({name:_.string(),dataType:_.enum(["String","Integer","Decimal","DateTime"]).optional().describe("Known type (DAX/semantic-model callers have it); omit to infer from values."),isMeasure:_.boolean().optional().describe("Known measure/dimension role; omit to apply the numeric-non-identifier heuristic. A semantic-model caller should set this."),format:_.string().optional().describe('Format string from the model (e.g. "$#,##0") \u2192 modelFormat.'),description:_.string().optional().describe("Column description from the model \u2192 modelDesc.")})).min(1),rows:_.array(_.union([_.array(_.any()),_.record(_.string(),_.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."),rN={csv_path:_.string().optional().describe("Path to a CSV file (header row required)."),csv_text:_.string().optional().describe("Inline CSV text (alternative to csv_path)."),data:sse.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:_.array(_.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:_.array(_.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:_.record(_.string(),_.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:_.record(_.string(),_.string()).optional().describe("Per-column human DESCRIPTION \u2014 gives the model semantic context the bare column name lacks."),group_by:_.array(_.string()).optional().describe("Columns that are the PRIMARY series/breakdown (the PBI 'Group by' well); the backend leads the visualization with these."),non_additive:_.array(_.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:_.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:xr(_.string().regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/).max(35).refine(e=>_3(e)!==void 0,{error:e=>`'${String(e.input)}' is not a valid language tag; use a form such as 'de-DE', 'fr', 'ja-JP', 'es-419' or 'zh-Hant-TW'.`})).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 go(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 Os(e){if(e.data)return P0(e.data.columns,e.data.rows,go(e));if(e.csv_text)return b3(e.csv_text,go(e));if(e.csv_path)return b3(nN(Dr(e.csv_path),"utf-8"),go(e));throw new Error("Provide one of: data ({columns, rows}), csv_text, or csv_path.")}q1.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:rN,annotations:{readOnlyHint:!0,openWorldHint:!1}},async e=>{let t=Os(e),a={totalRows:t.totalRows,leafCardinality:t.index.getLeafCardinality(),columns:t.shape},r=P1()?null:rE(process.env);return{content:[{type:"text",text:JSON.stringify(a,null,2)},...r?[{type:"text",text:r}]:[]]}});q1.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. 'settings' lists the choices a person can make about a chart, with their options and defaults.",inputSchema:{topic:_.enum(tO).optional().describe("'fabric-app' (default), 'all', 'chart-shapes', or 'settings'.")},annotations:{readOnlyHint:!0,openWorldHint:!1}},async e=>{try{return{content:[{type:"text",text:aO(e.topic??"fabric-app")}]}}catch(t){return{isError:!0,content:[{type:"text",text:`The guide could not be read from this package (${t?.message??t}). It is also published as skills/bic-charts/SKILL.md inside @bicharts/chart-mcp on npm.`}]}}});q1.registerTool("list_eligible_charts",{title:"List eligible chart types",description:"The AUTHORITATIVE list of chart types (maps, tables a reader works with and app widgets included) 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:{...rN,language:_.enum(["javascript","typescript","python",""]).optional().describe("Project source language \u2192 the server ranks across that language's renderers (javascript/typescript = D3, python = Plotly/matplotlib). Omit to AUTO-DETECT from the working dir; `renderer` (if given) overrides this."),project_dir:_.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:_.enum(["D3","PLOTLY","PYMATPLOT",""]).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:xr(_.enum(["High","Medium","Low",""])).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."),chart_style:xr(_.enum(["traditional","non_traditional",""])).describe("The user's own preference for which family of charts the list covers, as they've stated it. 'traditional' lists only the familiar forms (bar, stacked and grouped bar, line, area, pie, donut, card, gauge), 'non_traditional' lists only the other chart types; a type outside the chosen family is left out. Unset when they haven't stated one; unset changes nothing."),name_filter:_.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:_.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:_.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:_.number().optional().describe("Show only the top-N ranked results. Omit for all."),width:_.number().optional().describe("Viewport width px (default 800) \u2014 affects small-viewport / facet-budget gates."),height:_.number().optional().describe("Viewport height px (default 600).")},outputSchema:X$,annotations:{readOnlyHint:!0,openWorldHint:!0}},async e=>{let t=Os(e),a="",r="",n="",i="";if(e.renderer!==void 0)a=e.renderer;else if(e.language)r=e.language;else if(P1())r="javascript",n=" (language: javascript, this server's default - pass language or renderer for another)";else{let b=$l($s(e.project_dir,ro));b.language?(r=b.language,n=` (auto-detected language: ${b.language} \u2014 ${b.reason})`):i=`Couldn't tell the project's language (${b.reason}), so this is the list across all renderers; pass language: "javascript" or "python", or project_dir, to narrow it.
369
+ `);function $s(e,t){return Ol(e,t).dir??Dr(e??process.cwd())}var tN="0.6.121",VO=[],fo=null,q1={registerTool(e,t,a){VO.push({name:e,config:t,cb:a})},get server(){if(!fo)throw new Error("The local server isn't running in this process.");return fo.server}};function XO(e){let t=e?new R8({name:"bic-chart",version:tN},{instructions:GO}):new R8({name:"bic-chart",version:tN},{instructions:q$});e||(t.server.registerCapabilities({logging:{}}),vT(a=>{t.server.sendLoggingMessage({level:"notice",logger:"sign-in",data:a}).catch(()=>{})}));for(let a of VO){if(e&&!jO.includes(a.name))continue;let r=e?BO[a.name]:void 0,n={...a.config,...r?{description:r.description,inputSchema:{...a.config.inputSchema,...r.inputs??{}}}:{},annotations:{title:a.config.title,...a.config.annotations}},i=r?.refuse?(o,s)=>{let l=HO(o,r.refuse);return l?{isError:!0,content:[{type:"text",text:l}]}:a.cb(o,s)}:a.cb;t.registerTool(a.name,n,i)}return t}var zs="2026-11-12T22:09:57Z src:a48292e754a4 (46 files)",aN="@bicharts/chart-host@0.6.121, @bicharts/shape-core@0.6.121",sse=_.object({columns:_.array(_.object({name:_.string(),dataType:_.enum(["String","Integer","Decimal","DateTime"]).optional().describe("Known type (DAX/semantic-model callers have it); omit to infer from values."),isMeasure:_.boolean().optional().describe("Known measure/dimension role; omit to apply the numeric-non-identifier heuristic. A semantic-model caller should set this."),format:_.string().optional().describe('Format string from the model (e.g. "$#,##0") \u2192 modelFormat.'),description:_.string().optional().describe("Column description from the model \u2192 modelDesc.")})).min(1),rows:_.array(_.union([_.array(_.any()),_.record(_.string(),_.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."),rN={csv_path:_.string().optional().describe("Path to a CSV file (header row required)."),csv_text:_.string().optional().describe("Inline CSV text (alternative to csv_path)."),data:sse.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:_.array(_.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:_.array(_.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:_.record(_.string(),_.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:_.record(_.string(),_.string()).optional().describe("Per-column human DESCRIPTION \u2014 gives the model semantic context the bare column name lacks."),group_by:_.array(_.string()).optional().describe("Columns that are the PRIMARY series/breakdown (the PBI 'Group by' well); the backend leads the visualization with these."),non_additive:_.array(_.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:_.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:xr(_.string().regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/).max(35).refine(e=>_3(e)!==void 0,{error:e=>`'${String(e.input)}' is not a valid language tag; use a form such as 'de-DE', 'fr', 'ja-JP', 'es-419' or 'zh-Hant-TW'.`})).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 go(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 Os(e){if(e.data)return P0(e.data.columns,e.data.rows,go(e));if(e.csv_text)return b3(e.csv_text,go(e));if(e.csv_path)return b3(nN(Dr(e.csv_path),"utf-8"),go(e));throw new Error("Provide one of: data ({columns, rows}), csv_text, or csv_path.")}q1.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:rN,annotations:{readOnlyHint:!0,openWorldHint:!1}},async e=>{let t=Os(e),a={totalRows:t.totalRows,leafCardinality:t.index.getLeafCardinality(),columns:t.shape},r=P1()?null:rE(process.env);return{content:[{type:"text",text:JSON.stringify(a,null,2)},...r?[{type:"text",text:r}]:[]]}});q1.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. 'settings' lists the choices a person can make about a chart, with their options and defaults.",inputSchema:{topic:_.enum(tO).optional().describe("'fabric-app' (default), 'all', 'chart-shapes', or 'settings'.")},annotations:{readOnlyHint:!0,openWorldHint:!1}},async e=>{try{return{content:[{type:"text",text:aO(e.topic??"fabric-app")}]}}catch(t){return{isError:!0,content:[{type:"text",text:`The guide could not be read from this package (${t?.message??t}). It is also published as skills/bic-charts/SKILL.md inside @bicharts/chart-mcp on npm.`}]}}});q1.registerTool("list_eligible_charts",{title:"List eligible chart types",description:"The AUTHORITATIVE list of chart types (maps, tables a reader works with and app widgets included) 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:{...rN,language:_.enum(["javascript","typescript","python",""]).optional().describe("Project source language \u2192 the server ranks across that language's renderers (javascript/typescript = D3, python = Plotly/matplotlib). Omit to AUTO-DETECT from the working dir; `renderer` (if given) overrides this."),project_dir:_.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:_.enum(["D3","PLOTLY","PYMATPLOT",""]).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:xr(_.enum(["High","Medium","Low",""])).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."),chart_style:xr(_.enum(["traditional","non_traditional",""])).describe("The user's own preference for which family of charts the list covers, as they've stated it. 'traditional' lists only the familiar forms (bar, stacked and grouped bar, line, area, pie, donut, card, gauge), 'non_traditional' lists only the other chart types; a type outside the chosen family is left out. Unset when they haven't stated one; unset changes nothing."),name_filter:_.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:_.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:_.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:_.number().optional().describe("Show only the top-N ranked results. Omit for all."),width:_.number().optional().describe("Viewport width px (default 800) \u2014 affects small-viewport / facet-budget gates."),height:_.number().optional().describe("Viewport height px (default 600).")},outputSchema:X$,annotations:{readOnlyHint:!0,openWorldHint:!0}},async e=>{let t=Os(e),a="",r="",n="",i="";if(e.renderer!==void 0)a=e.renderer;else if(e.language)r=e.language;else if(P1())r="javascript",n=" (language: javascript, this server's default - pass language or renderer for another)";else{let b=$l($s(e.project_dir,ro));b.language?(r=b.language,n=` (auto-detected language: ${b.language} \u2014 ${b.reason})`):i=`Couldn't tell the project's language (${b.reason}), so this is the list across all renderers; pass language: "javascript" or "python", or project_dir, to narrow it.
370
370
  `}let o=await Ub({shape:t.shape,totalRows:t.totalRows,leafCardinality:t.index.getLeafCardinality(),dataComplete:Vb(e,P1()),geoExtent:t.index.getGeoExtent(),width:e.width,height:e.height,renderer:a,language:r,levelOfDetail:e.level_of_detail||void 0,order:e.order??"fit",chartStyle:e.chart_style||void 0,mcpClient:qO()});if(!o.ok)return{isError:!0,content:[{type:"text",text:El(o)?o.errorMessage:`Could not list eligible charts: ${o.errorMessage}`}]};let s=o.charts.length>0&&o.charts[0].rank!==void 0,l=r?`${r}`:a||"all renderers",u=o.charts,c=u.length,d="all",h=b=>V$({rows:b,order:e.order??"fit",eligibleCount:c,filter:e.name_filter?{text:e.name_filter,tier:d}:null,metering:Ur}),p=mU(e.name_filter_match),m=ds(u,e.name_filter,el,p);u=m.rows,d=m.tier;let g;if(s){e.top&&e.top>0&&(u=u.slice(0,e.top));let b=(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}, ${b} (authoritative \u2014 the server's eligibility engine; ${Ur})${n}:`}else g=`${u.length} chart type(s) can render this data \u2014 renderer-agnostic eligibility (authoritative \u2014 the server's eligibility engine; ${Ur}):`;if(g=i+g,m.tier!=="all"){let b=m.tier==="desc"?" (no NAME matched; these matched on description)":m.tier==="namePart"?" (matched mid-word in the name)":"";g=`Filtered to "${e.name_filter}"${b}: ${u.length} of ${c} eligible chart type(s). The other ${c-u.length} are eligible and simply do not match the filter.
371
371
  `+g}let f=K$(u);if(u.length===0&&m.tier!=="all"&&c>0){let b=ds(o.refused,e.name_filter,gU,p),v=b.tier==="name"||b.tier==="namePart"?b.rows.filter(w=>w.reason).slice(0,3):[],k=v.length>0?`
372
372
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bicharts/chart-mcp",
3
- "version": "0.6.120",
3
+ "version": "0.6.121",
4
4
  "description": "AI Data Components for Power BI, Excel, Fabric Apps and the web, over MCP: working what-if apps, interactive tables and bivariate maps first, plus about 90 everyday chart types, with selection and cross-filtering already wired. It profiles your table locally; the code it writes is yours and runs with no license.",
5
5
  "keywords": [
6
6
  "mcp",
@@ -51,8 +51,8 @@
51
51
  },
52
52
  "// 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.",
53
53
  "devDependencies": {
54
- "@bicharts/chart-host": "^0.6.120",
55
- "@bicharts/shape-core": "^0.6.120",
54
+ "@bicharts/chart-host": "^0.6.121",
55
+ "@bicharts/shape-core": "^0.6.121",
56
56
  "@modelcontextprotocol/sdk": "^1.32.1",
57
57
  "@types/node": "^26.6.5",
58
58
  "@types/papaparse": "^5.3.14",