@directive-run/mcp 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- 'use strict';var crypto=require('crypto'),claudePlugin=require('@directive-run/claude-plugin'),knowledge=require('@directive-run/knowledge'),scaffold=require('@directive-run/scaffold'),mcp_js=require('@modelcontextprotocol/sdk/server/mcp.js'),zod=require('zod'),url=require('url'),worker_threads=require('worker_threads'),lint=require('@directive-run/lint'),sandbox=require('@directive-run/sandbox'),http=require('http'),sse_js=require('@modelcontextprotocol/sdk/server/sse.js');var ke=Object.create;var W=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var De=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var $e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _e(t))!Ee.call(e,i)&&i!==r&&W(e,i,{get:()=>t[i],enumerable:!(n=Se(t,i))||n.enumerable});return e};var Re=(e,t,r)=>(r=e!=null?ke(Te(e)):{},$e(W(r,"default",{value:e,enumerable:true}),e));var ie=De((Ct,A)=>{var B=(function(){var e=String.fromCharCode,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function i(o,s){if(!n[o]){n[o]={};for(var u=0;u<o.length;u++)n[o][o.charAt(u)]=u;}return n[o][s]}var a={compressToBase64:function(o){if(o==null)return "";var s=a._compress(o,6,function(u){return t.charAt(u)});switch(s.length%4){default:case 0:return s;case 1:return s+"===";case 2:return s+"==";case 3:return s+"="}},decompressFromBase64:function(o){return o==null?"":o==""?null:a._decompress(o.length,32,function(s){return i(t,o.charAt(s))})},compressToUTF16:function(o){return o==null?"":a._compress(o,15,function(s){return e(s+32)})+" "},decompressFromUTF16:function(o){return o==null?"":o==""?null:a._decompress(o.length,16384,function(s){return o.charCodeAt(s)-32})},compressToUint8Array:function(o){for(var s=a.compress(o),u=new Uint8Array(s.length*2),d=0,p=s.length;d<p;d++){var y=s.charCodeAt(d);u[d*2]=y>>>8,u[d*2+1]=y%256;}return u},decompressFromUint8Array:function(o){if(o==null)return a.decompress(o);for(var s=new Array(o.length/2),u=0,d=s.length;u<d;u++)s[u]=o[u*2]*256+o[u*2+1];var p=[];return s.forEach(function(y){p.push(e(y));}),a.decompress(p.join(""))},compressToEncodedURIComponent:function(o){return o==null?"":a._compress(o,6,function(s){return r.charAt(s)})},decompressFromEncodedURIComponent:function(o){return o==null?"":o==""?null:(o=o.replace(/ /g,"+"),a._decompress(o.length,32,function(s){return i(r,o.charAt(s))}))},compress:function(o){return a._compress(o,16,function(s){return e(s)})},_compress:function(o,s,u){if(o==null)return "";var d,p,y={},b={},k="",T="",v="",w=2,$=3,f=2,h=[],c=0,l=0,x;for(x=0;x<o.length;x+=1)if(k=o.charAt(x),Object.prototype.hasOwnProperty.call(y,k)||(y[k]=$++,b[k]=true),T=v+k,Object.prototype.hasOwnProperty.call(y,T))v=T;else {if(Object.prototype.hasOwnProperty.call(b,v)){if(v.charCodeAt(0)<256){for(d=0;d<f;d++)c=c<<1,l==s-1?(l=0,h.push(u(c)),c=0):l++;for(p=v.charCodeAt(0),d=0;d<8;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;}else {for(p=1,d=0;d<f;d++)c=c<<1|p,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=0;for(p=v.charCodeAt(0),d=0;d<16;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;}w--,w==0&&(w=Math.pow(2,f),f++),delete b[v];}else for(p=y[v],d=0;d<f;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;w--,w==0&&(w=Math.pow(2,f),f++),y[T]=$++,v=String(k);}if(v!==""){if(Object.prototype.hasOwnProperty.call(b,v)){if(v.charCodeAt(0)<256){for(d=0;d<f;d++)c=c<<1,l==s-1?(l=0,h.push(u(c)),c=0):l++;for(p=v.charCodeAt(0),d=0;d<8;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;}else {for(p=1,d=0;d<f;d++)c=c<<1|p,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=0;for(p=v.charCodeAt(0),d=0;d<16;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;}w--,w==0&&(w=Math.pow(2,f),f++),delete b[v];}else for(p=y[v],d=0;d<f;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;w--,w==0&&(w=Math.pow(2,f),f++);}for(p=2,d=0;d<f;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;for(;;)if(c=c<<1,l==s-1){h.push(u(c));break}else l++;return h.join("")},decompress:function(o){return o==null?"":o==""?null:a._decompress(o.length,32768,function(s){return o.charCodeAt(s)})},_decompress:function(o,s,u){var d=[],y=4,b=4,k=3,T="",v=[],w,$,f,h,c,l,x,g={val:u(0),position:s,index:1};for(w=0;w<3;w+=1)d[w]=w;for(f=0,c=Math.pow(2,2),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;switch(f){case 0:for(f=0,c=Math.pow(2,8),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;x=e(f);break;case 1:for(f=0,c=Math.pow(2,16),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;x=e(f);break;case 2:return ""}for(d[3]=x,$=x,v.push(x);;){if(g.index>o)return "";for(f=0,c=Math.pow(2,k),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;switch(x=f){case 0:for(f=0,c=Math.pow(2,8),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;d[b++]=e(f),x=b-1,y--;break;case 1:for(f=0,c=Math.pow(2,16),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;d[b++]=e(f),x=b-1,y--;break;case 2:return v.join("")}if(y==0&&(y=Math.pow(2,k),k++),d[x])T=d[x];else if(x===b)T=$+$.charAt(0);else return null;v.push(T),d[b++]=$+T.charAt(0),y--,$=T,y==0&&(y=Math.pow(2,k),k++);}}};return a})();typeof define=="function"&&define.amd?define(function(){return B}):typeof A<"u"&&A!=null?A.exports=B:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return B});});var C=[{name:"@directive-run/ai",version:"1.17.2",description:"AI guardrails and orchestration for Directive. Prompt injection, PII detection, cost tracking, multi-agent patterns.",homepage:"https://directive.run",keywords:["directive","ai","agents","guardrails","orchestration","llm","constraint-driven","ai-safety","prompt-injection","pii-detection","cost-tracking","multi-agent","openai","anthropic","ollama","gemini"],dependencies:[],peerDependencies:["@directive-run/core"],optionalDependencies:[],exports:[".","./anthropic","./devtools","./evals","./gemini","./guardrails","./mcp","./multi-agent","./ollama","./openai","./predicate","./testing"],directory:"ai",published:true},{name:"@directive-run/claude-plugin",version:"1.17.2",description:"Claude Code plugin for Directive \u2014 12 skills covering modules, constraints, resolvers, derivations, AI orchestration, and adapters. Installable via Claude Code's plugin marketplace or consumable programmatically as an npm package.",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","claude","claude-code","skills","ai-rules","plugin","agents","knowledge"],dependencies:[],peerDependencies:[],optionalDependencies:[],exports:["."],directory:"claude-plugin",published:true},{name:"@directive-run/cli",version:"1.17.2",description:"CLI tools for Directive \u2014 AI coding rules, scaffolding, and more.",homepage:"https://directive.run",keywords:["directive","cli","ai-rules","cursor","copilot","claude","windsurf","cline","llms-txt"],dependencies:["@clack/prompts","@directive-run/knowledge","@directive-run/scaffold","picocolors"],peerDependencies:["@directive-run/timeline"],optionalDependencies:[],exports:[".","./llms.txt"],directory:"cli",published:true},{name:"@directive-run/core",version:"1.17.2",description:"The constraint-driven runtime for TypeScript. Declare what must be true \u2014 the runtime makes it happen.",homepage:"https://directive.run",keywords:["directive","constraint-driven","state-management","constraints","reactive","runtime","typescript","ai-guardrails","zero-dependencies","auto-tracking","framework-agnostic","declarative"],dependencies:[],peerDependencies:[],optionalDependencies:[],exports:[".","./adapter-utils","./internals","./migration","./plugins","./testing","./worker"],directory:"core",published:true},{name:"@directive-run/el",version:"1.1.0",description:"Vanilla DOM adapter for Directive. Typed element creation + reactive bindings + JSX runtime.",homepage:"https://directive.run",keywords:["directive","vanilla","dom","elements","jsx","htm","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","htm"],optionalDependencies:[],exports:[".","./htm","./jsx-dev-runtime","./jsx-runtime"],directory:"el",published:true},{name:"@directive-run/knowledge",version:"1.17.2",description:"Knowledge files, examples, and validation for Directive \u2014 the constraint-driven TypeScript runtime.",homepage:"https://directive.run",keywords:["directive","knowledge","ai-rules","examples"],dependencies:[],peerDependencies:[],optionalDependencies:[],exports:["."],directory:"knowledge",published:true},{name:"@directive-run/lint",version:"0.1.2",description:"ts-morph-based static analysis for Directive code. Rule registry + executable checks + autofixes. Consumed by @directive-run/mcp (review_source, fix_code tools) and the future `directive doctor lint` CLI command. Anti-pattern data sourced from @directive-run/knowledge so rule IDs stay in lock-step.",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","lint","ast","ts-morph","review","anti-patterns"],dependencies:[],peerDependencies:[],optionalDependencies:["ts-morph"],exports:[".","./executable","./worker"],directory:"lint",published:true},{name:"@directive-run/lit",version:"1.17.2",description:"Lit web components adapter for Directive.",homepage:"https://directive.run",keywords:["directive","lit","web-components","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","lit"],optionalDependencies:[],exports:["."],directory:"lit",published:true},{name:"@directive-run/mcp",version:"0.5.0",description:"Model Context Protocol server that exposes Directive to AI clients \u2014 knowledge files, code examples, and Claude Code skill bundles today, with room to grow into runtime introspection and tooling. stdio for local clients (Claude Desktop, Cursor, MCP Inspector), SSE for hosted deployments at mcp.directive.run.",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","mcp","model-context-protocol","knowledge","ai-rules","sse","stdio"],dependencies:["@directive-run/claude-plugin","@directive-run/knowledge","@directive-run/lint","@directive-run/sandbox","@directive-run/scaffold","@modelcontextprotocol/sdk","lz-string","zod"],peerDependencies:[],optionalDependencies:["ts-morph"],exports:["."],directory:"mcp",published:true},{name:"@directive-run/mutator",version:"0.3.1",description:"Discriminated mutation helper for Directive \u2014 collapse the pendingAction ceremony to a typed handler map.",homepage:"https://directive.run",keywords:["directive","mutator","state-management","discriminated-union","optimistic-update"],dependencies:[],peerDependencies:["@directive-run/core"],optionalDependencies:[],exports:["."],directory:"mutator",published:true},{name:"@directive-run/optimistic",version:"0.2.0",description:"Resolver-scope optimistic update + automatic rollback for Directive.",homepage:"https://directive.run",keywords:["directive","optimistic","rollback","snapshot","state-management"],dependencies:[],peerDependencies:["@directive-run/core"],optionalDependencies:[],exports:["."],directory:"optimistic",published:true},{name:"@directive-run/query",version:"1.2.0",description:"Declarative data fetching for Directive. Constraint-driven queries with causal cache invalidation.",homepage:"https://directive.run",keywords:["directive","data-fetching","query","cache","stale-while-revalidate","constraint-driven","reactive","typescript"],dependencies:[],peerDependencies:["@directive-run/core"],optionalDependencies:[],exports:["."],directory:"query",published:true},{name:"@directive-run/react",version:"1.17.2",description:"React hooks and components for Directive.",homepage:"https://directive.run",keywords:["directive","react","hooks","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","@directive-run/query","react"],optionalDependencies:[],exports:["."],directory:"react",published:true},{name:"@directive-run/sandbox",version:"0.1.0",description:"Execute Directive snippets server-side and return a structured transcript (logs + facts + errors). Consumed by @directive-run/mcp's run_in_sandbox tool and directive.run/playground's live DevTools panel. Uses worker_threads + esbuild bundling + an AST allowlist validator so user-supplied TypeScript runs with a bounded surface (allowlisted imports, allowlisted API calls, 5s wall clock, 32 MB heap).",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","sandbox","worker-threads","execute","transcript"],dependencies:["@directive-run/core"],peerDependencies:[],optionalDependencies:["esbuild","ts-morph"],exports:[".","./worker"],directory:"sandbox",published:true},{name:"@directive-run/scaffold",version:"0.2.0",description:"Pure source-string generators for Directive modules and orchestrators. Shared substrate consumed by @directive-run/cli (its `directive new` command) and @directive-run/mcp (its `generate_module` tool). Zero runtime dependencies.",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","scaffold","codegen","module-generator"],dependencies:[],peerDependencies:[],optionalDependencies:[],exports:["."],directory:"scaffold",published:true},{name:"@directive-run/solid",version:"1.17.2",description:"Solid.js signals adapter for Directive.",homepage:"https://directive.run",keywords:["directive","solid","solidjs","signals","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","@directive-run/query","solid-js"],optionalDependencies:[],exports:["."],directory:"solid",published:true},{name:"@directive-run/svelte",version:"1.17.2",description:"Svelte stores adapter for Directive.",homepage:"https://directive.run",keywords:["directive","svelte","stores","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","@directive-run/query","svelte"],optionalDependencies:[],exports:["."],directory:"svelte",published:true},{name:"@directive-run/timeline",version:"0.3.1",description:"Time-travel test REPL for Directive. Auto-renders the causal-graph timeline of any failing test.",homepage:"https://directive.run",keywords:["directive","time-travel","test-debugging","vitest","causal-graph","state-management"],dependencies:[],peerDependencies:["@directive-run/core","vitest"],optionalDependencies:[],exports:[".","./matchers","./reporter"],directory:"timeline",published:true},{name:"@directive-run/vite-plugin-api-proxy",version:"0.1.1",description:"",keywords:[],dependencies:[],peerDependencies:["vite"],optionalDependencies:[],exports:["."],directory:"vite-plugin-api-proxy",published:false},{name:"@directive-run/vue",version:"1.17.2",description:"Vue composition API adapter for Directive.",homepage:"https://directive.run",keywords:["directive","vue","composition-api","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","@directive-run/query","vue"],optionalDependencies:[],exports:["."],directory:"vue",published:true}],Y="2026-06-06T20:19:25.752Z";var X=2e5,J=5e3,Me=/^[\w./-]{1,128}$/,S=class extends Error{constructor(r,n){super(r);this.code=n;}};function Z(e){let t=Buffer.byteLength(e.source,"utf8");if(t>X)throw new S(`source is ${t} bytes (max ${X})`,"source-too-large");let r="fileName"in e?e.fileName:void 0;if(r!==void 0&&!Me.test(r))throw new S("invalid fileName","bad-filename")}async function Oe(){let e=await undefined("@directive-run/lint/worker");return url.fileURLToPath(e)}async function q(e){let t=await Oe(),r=new worker_threads.Worker(t,{stderr:false}),n=null;try{return await new Promise((i,a)=>{let o=!1;r.once("message",s=>{o=!0,s.ok&&s.result!==void 0?i(s.result):a(new S(s.error??"worker returned without result","worker-error"));}),r.once("error",s=>{o=!0,a(new S(s.message,"worker-error"));}),r.once("exit",s=>{!o&&s!==0&&s!==null&&a(new S(`worker exited with code ${s} before responding`,"worker-error"));}),n=setTimeout(()=>{r.terminate(),a(new S(`parse exceeded ${J}ms budget`,"timeout"));},J),r.postMessage(e);})}finally{n&&clearTimeout(n),await r.terminate().catch(()=>{});}}function Q(){return !(process.env.DIRECTIVE_MCP_USE_LINT_WORKER==="0"||process.env.VITEST==="true")}async function ee(e){return Z(e),Q()?q({kind:"run",source:e.source,options:{fileName:e.fileName,ruleFilter:e.ruleFilter}}):lint.runRules(e.source,{fileName:e.fileName,ruleFilter:e.ruleFilter})}async function te(e){return Z(e),Q()?q({kind:"fix",source:e.source,finding:e.finding}):lint.applyFix(e.source,e.finding)}var Ce=3600*1e3,Ue=3e3,re=new Map;function U(){return C.map(e=>({name:e.name,summary:e.description,published:e.published}))}async function ne(e){let t=C.find(i=>i.name===e);if(!t)return;let{liveVersion:r,stale:n}=await Ne(t);return Be(t,r,n)}function Be(e,t,r){return {name:e.name,description:e.description,homepage:e.homepage,keywords:e.keywords,dependencies:e.dependencies,peerDependencies:e.peerDependencies,optionalDependencies:e.optionalDependencies,exports:e.exports,published:e.published,npmUrl:e.published?`https://www.npmjs.com/package/${e.name}`:void 0,bakedVersion:e.version,liveVersion:t,stale:r}}async function Ne(e){if(!e.published)return {stale:true};let t=re.get(e.name);if(t&&Date.now()-t.fetchedAt<Ce)return {liveVersion:t.liveVersion,stale:t.liveVersion===void 0};let r=await Fe(e.name);return re.set(e.name,{fetchedAt:Date.now(),liveVersion:r.liveVersion,latest:r.liveVersion,error:r.error}),{liveVersion:r.liveVersion,stale:r.liveVersion===void 0}}async function Fe(e){let t=`https://registry.npmjs.org/${encodeURIComponent(e).replace(/%2F/g,"/")}/latest`,r=new AbortController,n=setTimeout(()=>r.abort(),Ue);try{let i=await fetch(t,{signal:r.signal});if(!i.ok)return {error:`HTTP ${i.status}`};let a=await i.json();return typeof a.version=="string"?{liveVersion:a.version}:{error:"no version field"}}catch(i){return {error:i.message}}finally{clearTimeout(n);}}var N=Re(ie()),D=8e3,je="https://directive.run/playground",Ve="https://directive.run/run",_=class extends Error{constructor(r,n){super(r);this.code=n;}};function oe(e){if(e>D)throw new _(`payload is ${e} bytes (max ${D}). Payloads larger than ${D} bytes don't fit reliably in a URL \u2014 copy the source into a fresh Stackblitz project instead.`,"source-too-large")}function se(e){return encodeURIComponent(e)}function ae(e){return e==="instant"?Ve:je}function Ge(e,t,r){if(e.length===0)throw new _("source is empty","source-empty");let n=Buffer.byteLength(e,"utf8");oe(n);let a=[`src=${(0, N.compressToEncodedURIComponent)(e)}`];t&&a.push(`t=${se(t)}`);let o=`${ae(r)}#${a.join("&")}`;return {url:o,sizeBytes:n,urlBytes:Buffer.byteLength(o,"utf8"),fileCount:1,mode:r,title:t}}function ze(e,t,r){if(e.length===0)throw new _("files array is empty","source-empty");for(let u of e){if(typeof u.path!="string"||u.path.length===0)throw new _("every file must have a non-empty path","invalid-file");if(typeof u.source!="string"||u.source.length===0)throw new _(`file '${u.path}' has empty source`,"invalid-file")}let n=JSON.stringify(e),i=Buffer.byteLength(n,"utf8");oe(i);let o=[`files=${(0, N.compressToEncodedURIComponent)(n)}`];t&&o.push(`t=${se(t)}`);let s=`${ae(r)}#${o.join("&")}`;return {url:s,sizeBytes:i,urlBytes:Buffer.byteLength(s,"utf8"),fileCount:e.length,mode:r,title:t}}function F(e){let t=e.mode??"preview",r=typeof e.source=="string",n=Array.isArray(e.files);if(r&&n)throw new _("pass either `source` or `files`, not both","both-source-and-files");if(!r&&!n)throw new _("pass either `source` (single file) or `files` (multi-file array)","no-input");return n?ze(e.files,e.title,t):Ge(e.source,e.title,t)}var P=2e5,ce=10,Ke=/^[\w./-]{1,128}$/,R=class extends Error{constructor(r,n){super(r);this.code=n;}};function We(e){if(e.files){if(e.files.length>ce)throw new R(`payload exceeds ${ce} files`,"input-invalid");let t=0;for(let r of e.files){if(!Ke.test(r.path))throw new R(`invalid file path: '${r.path}'`,"input-invalid");t+=Buffer.byteLength(r.source,"utf8");}if(t>P)throw new R(`payload is ${t} bytes (max ${P})`,"input-too-large")}else if(e.source){let t=Buffer.byteLength(e.source,"utf8");if(t>P)throw new R(`source is ${t} bytes (max ${P})`,"input-too-large")}}async function le(e){return We(e),sandbox.runInSandbox(e)}var ue="0.5.0",he=50,pe=200,ge=512;function dt(e){return e.length>pe?`${e.slice(0,pe)}\u2026`:e}function me(e,t,r){let n=e.toLowerCase(),i=[];for(let[a,o]of t){let s=o.split(`
1
+ 'use strict';var crypto=require('crypto'),claudePlugin=require('@directive-run/claude-plugin'),knowledge=require('@directive-run/knowledge'),scaffold=require('@directive-run/scaffold'),mcp_js=require('@modelcontextprotocol/sdk/server/mcp.js'),zod=require('zod'),url=require('url'),worker_threads=require('worker_threads'),lint=require('@directive-run/lint'),sandbox=require('@directive-run/sandbox'),http=require('http'),sse_js=require('@modelcontextprotocol/sdk/server/sse.js');var ke=Object.create;var W=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var De=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Re=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _e(t))!Ee.call(e,i)&&i!==r&&W(e,i,{get:()=>t[i],enumerable:!(n=Se(t,i))||n.enumerable});return e};var $e=(e,t,r)=>(r=e!=null?ke(Te(e)):{},Re(W(r,"default",{value:e,enumerable:true}),e));var ie=De((Ct,A)=>{var B=(function(){var e=String.fromCharCode,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function i(o,s){if(!n[o]){n[o]={};for(var u=0;u<o.length;u++)n[o][o.charAt(u)]=u;}return n[o][s]}var a={compressToBase64:function(o){if(o==null)return "";var s=a._compress(o,6,function(u){return t.charAt(u)});switch(s.length%4){default:case 0:return s;case 1:return s+"===";case 2:return s+"==";case 3:return s+"="}},decompressFromBase64:function(o){return o==null?"":o==""?null:a._decompress(o.length,32,function(s){return i(t,o.charAt(s))})},compressToUTF16:function(o){return o==null?"":a._compress(o,15,function(s){return e(s+32)})+" "},decompressFromUTF16:function(o){return o==null?"":o==""?null:a._decompress(o.length,16384,function(s){return o.charCodeAt(s)-32})},compressToUint8Array:function(o){for(var s=a.compress(o),u=new Uint8Array(s.length*2),d=0,p=s.length;d<p;d++){var y=s.charCodeAt(d);u[d*2]=y>>>8,u[d*2+1]=y%256;}return u},decompressFromUint8Array:function(o){if(o==null)return a.decompress(o);for(var s=new Array(o.length/2),u=0,d=s.length;u<d;u++)s[u]=o[u*2]*256+o[u*2+1];var p=[];return s.forEach(function(y){p.push(e(y));}),a.decompress(p.join(""))},compressToEncodedURIComponent:function(o){return o==null?"":a._compress(o,6,function(s){return r.charAt(s)})},decompressFromEncodedURIComponent:function(o){return o==null?"":o==""?null:(o=o.replace(/ /g,"+"),a._decompress(o.length,32,function(s){return i(r,o.charAt(s))}))},compress:function(o){return a._compress(o,16,function(s){return e(s)})},_compress:function(o,s,u){if(o==null)return "";var d,p,y={},b={},k="",T="",v="",w=2,R=3,f=2,h=[],c=0,l=0,x;for(x=0;x<o.length;x+=1)if(k=o.charAt(x),Object.prototype.hasOwnProperty.call(y,k)||(y[k]=R++,b[k]=true),T=v+k,Object.prototype.hasOwnProperty.call(y,T))v=T;else {if(Object.prototype.hasOwnProperty.call(b,v)){if(v.charCodeAt(0)<256){for(d=0;d<f;d++)c=c<<1,l==s-1?(l=0,h.push(u(c)),c=0):l++;for(p=v.charCodeAt(0),d=0;d<8;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;}else {for(p=1,d=0;d<f;d++)c=c<<1|p,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=0;for(p=v.charCodeAt(0),d=0;d<16;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;}w--,w==0&&(w=Math.pow(2,f),f++),delete b[v];}else for(p=y[v],d=0;d<f;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;w--,w==0&&(w=Math.pow(2,f),f++),y[T]=R++,v=String(k);}if(v!==""){if(Object.prototype.hasOwnProperty.call(b,v)){if(v.charCodeAt(0)<256){for(d=0;d<f;d++)c=c<<1,l==s-1?(l=0,h.push(u(c)),c=0):l++;for(p=v.charCodeAt(0),d=0;d<8;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;}else {for(p=1,d=0;d<f;d++)c=c<<1|p,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=0;for(p=v.charCodeAt(0),d=0;d<16;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;}w--,w==0&&(w=Math.pow(2,f),f++),delete b[v];}else for(p=y[v],d=0;d<f;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;w--,w==0&&(w=Math.pow(2,f),f++);}for(p=2,d=0;d<f;d++)c=c<<1|p&1,l==s-1?(l=0,h.push(u(c)),c=0):l++,p=p>>1;for(;;)if(c=c<<1,l==s-1){h.push(u(c));break}else l++;return h.join("")},decompress:function(o){return o==null?"":o==""?null:a._decompress(o.length,32768,function(s){return o.charCodeAt(s)})},_decompress:function(o,s,u){var d=[],y=4,b=4,k=3,T="",v=[],w,R,f,h,c,l,x,g={val:u(0),position:s,index:1};for(w=0;w<3;w+=1)d[w]=w;for(f=0,c=Math.pow(2,2),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;switch(f){case 0:for(f=0,c=Math.pow(2,8),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;x=e(f);break;case 1:for(f=0,c=Math.pow(2,16),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;x=e(f);break;case 2:return ""}for(d[3]=x,R=x,v.push(x);;){if(g.index>o)return "";for(f=0,c=Math.pow(2,k),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;switch(x=f){case 0:for(f=0,c=Math.pow(2,8),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;d[b++]=e(f),x=b-1,y--;break;case 1:for(f=0,c=Math.pow(2,16),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),f|=(h>0?1:0)*l,l<<=1;d[b++]=e(f),x=b-1,y--;break;case 2:return v.join("")}if(y==0&&(y=Math.pow(2,k),k++),d[x])T=d[x];else if(x===b)T=R+R.charAt(0);else return null;v.push(T),d[b++]=R+T.charAt(0),y--,R=T,y==0&&(y=Math.pow(2,k),k++);}}};return a})();typeof define=="function"&&define.amd?define(function(){return B}):typeof A<"u"&&A!=null?A.exports=B:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return B});});var C=[{name:"@directive-run/ai",version:"1.17.2",description:"AI guardrails and orchestration for Directive. Prompt injection, PII detection, cost tracking, multi-agent patterns.",homepage:"https://directive.run",keywords:["directive","ai","agents","guardrails","orchestration","llm","constraint-driven","ai-safety","prompt-injection","pii-detection","cost-tracking","multi-agent","openai","anthropic","ollama","gemini"],dependencies:[],peerDependencies:["@directive-run/core"],optionalDependencies:[],exports:[".","./anthropic","./devtools","./evals","./gemini","./guardrails","./mcp","./multi-agent","./ollama","./openai","./predicate","./testing"],directory:"ai",published:true},{name:"@directive-run/claude-plugin",version:"1.17.2",description:"Claude Code plugin for Directive \u2014 12 skills covering modules, constraints, resolvers, derivations, AI orchestration, and adapters. Installable via Claude Code's plugin marketplace or consumable programmatically as an npm package.",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","claude","claude-code","skills","ai-rules","plugin","agents","knowledge"],dependencies:[],peerDependencies:[],optionalDependencies:[],exports:["."],directory:"claude-plugin",published:true},{name:"@directive-run/cli",version:"1.17.2",description:"CLI tools for Directive \u2014 AI coding rules, scaffolding, and more.",homepage:"https://directive.run",keywords:["directive","cli","ai-rules","cursor","copilot","claude","windsurf","cline","llms-txt"],dependencies:["@clack/prompts","@directive-run/knowledge","@directive-run/scaffold","picocolors"],peerDependencies:["@directive-run/timeline"],optionalDependencies:[],exports:[".","./llms.txt"],directory:"cli",published:true},{name:"@directive-run/core",version:"1.17.2",description:"The constraint-driven runtime for TypeScript. Declare what must be true \u2014 the runtime makes it happen.",homepage:"https://directive.run",keywords:["directive","constraint-driven","state-management","constraints","reactive","runtime","typescript","ai-guardrails","zero-dependencies","auto-tracking","framework-agnostic","declarative"],dependencies:[],peerDependencies:[],optionalDependencies:[],exports:[".","./adapter-utils","./internals","./migration","./plugins","./testing","./worker"],directory:"core",published:true},{name:"@directive-run/el",version:"1.1.0",description:"Vanilla DOM adapter for Directive. Typed element creation + reactive bindings + JSX runtime.",homepage:"https://directive.run",keywords:["directive","vanilla","dom","elements","jsx","htm","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","htm"],optionalDependencies:[],exports:[".","./htm","./jsx-dev-runtime","./jsx-runtime"],directory:"el",published:true},{name:"@directive-run/knowledge",version:"1.17.2",description:"Knowledge files, examples, and validation for Directive \u2014 the constraint-driven TypeScript runtime.",homepage:"https://directive.run",keywords:["directive","knowledge","ai-rules","examples"],dependencies:[],peerDependencies:[],optionalDependencies:[],exports:["."],directory:"knowledge",published:true},{name:"@directive-run/lint",version:"0.1.2",description:"ts-morph-based static analysis for Directive code. Rule registry + executable checks + autofixes. Consumed by @directive-run/mcp (review_source, fix_code tools) and the future `directive doctor lint` CLI command. Anti-pattern data sourced from @directive-run/knowledge so rule IDs stay in lock-step.",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","lint","ast","ts-morph","review","anti-patterns"],dependencies:[],peerDependencies:[],optionalDependencies:["ts-morph"],exports:[".","./executable","./worker"],directory:"lint",published:true},{name:"@directive-run/lit",version:"1.17.2",description:"Lit web components adapter for Directive.",homepage:"https://directive.run",keywords:["directive","lit","web-components","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","lit"],optionalDependencies:[],exports:["."],directory:"lit",published:true},{name:"@directive-run/mcp",version:"0.5.2",description:"Model Context Protocol server that exposes Directive to AI clients \u2014 knowledge files, code examples, and Claude Code skill bundles today, with room to grow into runtime introspection and tooling. stdio for local clients (Claude Desktop, Cursor, MCP Inspector), SSE for hosted deployments at mcp.directive.run.",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","mcp","model-context-protocol","knowledge","ai-rules","sse","stdio"],dependencies:["@directive-run/claude-plugin","@directive-run/knowledge","@directive-run/lint","@directive-run/sandbox","@directive-run/scaffold","@modelcontextprotocol/sdk","lz-string","zod"],peerDependencies:[],optionalDependencies:["ts-morph"],exports:["."],directory:"mcp",published:true},{name:"@directive-run/mutator",version:"0.3.1",description:"Discriminated mutation helper for Directive \u2014 collapse the pendingAction ceremony to a typed handler map.",homepage:"https://directive.run",keywords:["directive","mutator","state-management","discriminated-union","optimistic-update"],dependencies:[],peerDependencies:["@directive-run/core"],optionalDependencies:[],exports:["."],directory:"mutator",published:true},{name:"@directive-run/optimistic",version:"0.2.0",description:"Resolver-scope optimistic update + automatic rollback for Directive.",homepage:"https://directive.run",keywords:["directive","optimistic","rollback","snapshot","state-management"],dependencies:[],peerDependencies:["@directive-run/core"],optionalDependencies:[],exports:["."],directory:"optimistic",published:true},{name:"@directive-run/query",version:"1.2.0",description:"Declarative data fetching for Directive. Constraint-driven queries with causal cache invalidation.",homepage:"https://directive.run",keywords:["directive","data-fetching","query","cache","stale-while-revalidate","constraint-driven","reactive","typescript"],dependencies:[],peerDependencies:["@directive-run/core"],optionalDependencies:[],exports:["."],directory:"query",published:true},{name:"@directive-run/react",version:"1.17.2",description:"React hooks and components for Directive.",homepage:"https://directive.run",keywords:["directive","react","hooks","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","@directive-run/query","react"],optionalDependencies:[],exports:["."],directory:"react",published:true},{name:"@directive-run/sandbox",version:"0.3.0",description:"Execute Directive snippets server-side and return a structured transcript (logs + facts + errors). Consumed by @directive-run/mcp's run_in_sandbox tool and directive.run/playground's live DevTools panel. Uses worker_threads + esbuild bundling + an AST allowlist validator so user-supplied TypeScript runs with a bounded surface (allowlisted imports, allowlisted API calls, 5s wall clock, 32 MB heap).",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","sandbox","worker-threads","execute","transcript"],dependencies:["@directive-run/core"],peerDependencies:[],optionalDependencies:["esbuild","ts-morph"],exports:[".","./worker"],directory:"sandbox",published:true},{name:"@directive-run/scaffold",version:"0.2.0",description:"Pure source-string generators for Directive modules and orchestrators. Shared substrate consumed by @directive-run/cli (its `directive new` command) and @directive-run/mcp (its `generate_module` tool). Zero runtime dependencies.",homepage:"https://directive.run/docs/ide-integration",keywords:["directive","scaffold","codegen","module-generator"],dependencies:[],peerDependencies:[],optionalDependencies:[],exports:["."],directory:"scaffold",published:true},{name:"@directive-run/solid",version:"1.17.2",description:"Solid.js signals adapter for Directive.",homepage:"https://directive.run",keywords:["directive","solid","solidjs","signals","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","@directive-run/query","solid-js"],optionalDependencies:[],exports:["."],directory:"solid",published:true},{name:"@directive-run/svelte",version:"1.17.2",description:"Svelte stores adapter for Directive.",homepage:"https://directive.run",keywords:["directive","svelte","stores","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","@directive-run/query","svelte"],optionalDependencies:[],exports:["."],directory:"svelte",published:true},{name:"@directive-run/timeline",version:"0.3.1",description:"Time-travel test REPL for Directive. Auto-renders the causal-graph timeline of any failing test.",homepage:"https://directive.run",keywords:["directive","time-travel","test-debugging","vitest","causal-graph","state-management"],dependencies:[],peerDependencies:["@directive-run/core","vitest"],optionalDependencies:[],exports:[".","./matchers","./reporter"],directory:"timeline",published:true},{name:"@directive-run/vite-plugin-api-proxy",version:"0.1.1",description:"",keywords:[],dependencies:[],peerDependencies:["vite"],optionalDependencies:[],exports:["."],directory:"vite-plugin-api-proxy",published:false},{name:"@directive-run/vue",version:"1.17.2",description:"Vue composition API adapter for Directive.",homepage:"https://directive.run",keywords:["directive","vue","composition-api","state-management","reactive","constraint-driven"],dependencies:[],peerDependencies:["@directive-run/core","@directive-run/query","vue"],optionalDependencies:[],exports:["."],directory:"vue",published:true}],Y="2026-06-07T18:14:35.535Z";var X=2e5,J=5e3,Le=/^[\w./-]{1,128}$/,S=class extends Error{constructor(r,n){super(r);this.code=n;}};function Z(e){let t=Buffer.byteLength(e.source,"utf8");if(t>X)throw new S(`source is ${t} bytes (max ${X})`,"source-too-large");let r="fileName"in e?e.fileName:void 0;if(r!==void 0&&!Le.test(r))throw new S("invalid fileName","bad-filename")}async function Oe(){let e=await undefined("@directive-run/lint/worker");return url.fileURLToPath(e)}async function q(e){let t=await Oe(),r=new worker_threads.Worker(t,{stderr:false}),n=null;try{return await new Promise((i,a)=>{let o=!1;r.once("message",s=>{o=!0,s.ok&&s.result!==void 0?i(s.result):a(new S(s.error??"worker returned without result","worker-error"));}),r.once("error",s=>{o=!0,a(new S(s.message,"worker-error"));}),r.once("exit",s=>{!o&&s!==0&&s!==null&&a(new S(`worker exited with code ${s} before responding`,"worker-error"));}),n=setTimeout(()=>{r.terminate(),a(new S(`parse exceeded ${J}ms budget`,"timeout"));},J),r.postMessage(e);})}finally{n&&clearTimeout(n),await r.terminate().catch(()=>{});}}function Q(){return !(process.env.DIRECTIVE_MCP_USE_LINT_WORKER==="0"||process.env.VITEST==="true")}async function ee(e){return Z(e),Q()?q({kind:"run",source:e.source,options:{fileName:e.fileName,ruleFilter:e.ruleFilter}}):lint.runRules(e.source,{fileName:e.fileName,ruleFilter:e.ruleFilter})}async function te(e){return Z(e),Q()?q({kind:"fix",source:e.source,finding:e.finding}):lint.applyFix(e.source,e.finding)}var Ce=3600*1e3,Ue=3e3,re=new Map;function U(){return C.map(e=>({name:e.name,summary:e.description,published:e.published}))}async function ne(e){let t=C.find(i=>i.name===e);if(!t)return;let{liveVersion:r,stale:n}=await Ne(t);return Be(t,r,n)}function Be(e,t,r){return {name:e.name,description:e.description,homepage:e.homepage,keywords:e.keywords,dependencies:e.dependencies,peerDependencies:e.peerDependencies,optionalDependencies:e.optionalDependencies,exports:e.exports,published:e.published,npmUrl:e.published?`https://www.npmjs.com/package/${e.name}`:void 0,bakedVersion:e.version,liveVersion:t,stale:r}}async function Ne(e){if(!e.published)return {stale:true};let t=re.get(e.name);if(t&&Date.now()-t.fetchedAt<Ce)return {liveVersion:t.liveVersion,stale:t.liveVersion===void 0};let r=await Fe(e.name);return re.set(e.name,{fetchedAt:Date.now(),liveVersion:r.liveVersion,latest:r.liveVersion,error:r.error}),{liveVersion:r.liveVersion,stale:r.liveVersion===void 0}}async function Fe(e){let t=`https://registry.npmjs.org/${encodeURIComponent(e).replace(/%2F/g,"/")}/latest`,r=new AbortController,n=setTimeout(()=>r.abort(),Ue);try{let i=await fetch(t,{signal:r.signal});if(!i.ok)return {error:`HTTP ${i.status}`};let a=await i.json();return typeof a.version=="string"?{liveVersion:a.version}:{error:"no version field"}}catch(i){return {error:i.message}}finally{clearTimeout(n);}}var N=$e(ie()),D=8e3,je="https://directive.run/playground",Ve="https://directive.run/run",_=class extends Error{constructor(r,n){super(r);this.code=n;}};function oe(e){if(e>D)throw new _(`payload is ${e} bytes (max ${D}). Payloads larger than ${D} bytes don't fit reliably in a URL \u2014 copy the source into a fresh Stackblitz project instead.`,"source-too-large")}function se(e){return encodeURIComponent(e)}function ae(e){return e==="instant"?Ve:je}function Ge(e,t,r){if(e.length===0)throw new _("source is empty","source-empty");let n=Buffer.byteLength(e,"utf8");oe(n);let a=[`src=${(0, N.compressToEncodedURIComponent)(e)}`];t&&a.push(`t=${se(t)}`);let o=`${ae(r)}#${a.join("&")}`;return {url:o,sizeBytes:n,urlBytes:Buffer.byteLength(o,"utf8"),fileCount:1,mode:r,title:t}}function ze(e,t,r){if(e.length===0)throw new _("files array is empty","source-empty");for(let u of e){if(typeof u.path!="string"||u.path.length===0)throw new _("every file must have a non-empty path","invalid-file");if(typeof u.source!="string"||u.source.length===0)throw new _(`file '${u.path}' has empty source`,"invalid-file")}let n=JSON.stringify(e),i=Buffer.byteLength(n,"utf8");oe(i);let o=[`files=${(0, N.compressToEncodedURIComponent)(n)}`];t&&o.push(`t=${se(t)}`);let s=`${ae(r)}#${o.join("&")}`;return {url:s,sizeBytes:i,urlBytes:Buffer.byteLength(s,"utf8"),fileCount:e.length,mode:r,title:t}}function F(e){let t=e.mode??"preview",r=typeof e.source=="string",n=Array.isArray(e.files);if(r&&n)throw new _("pass either `source` or `files`, not both","both-source-and-files");if(!r&&!n)throw new _("pass either `source` (single file) or `files` (multi-file array)","no-input");return n?ze(e.files,e.title,t):Ge(e.source,e.title,t)}var P=2e5,ce=10,Ke=/^[\w./-]{1,128}$/,$=class extends Error{constructor(r,n){super(r);this.code=n;}};function We(e){if(e.files){if(e.files.length>ce)throw new $(`payload exceeds ${ce} files`,"input-invalid");let t=0;for(let r of e.files){if(!Ke.test(r.path))throw new $(`invalid file path: '${r.path}'`,"input-invalid");t+=Buffer.byteLength(r.source,"utf8");}if(t>P)throw new $(`payload is ${t} bytes (max ${P})`,"input-too-large")}else if(e.source){let t=Buffer.byteLength(e.source,"utf8");if(t>P)throw new $(`source is ${t} bytes (max ${P})`,"input-too-large")}}async function le(e){return We(e),sandbox.runInSandbox(e)}var ue="0.5.2",he=50,pe=200,ge=512;function dt(e){return e.length>pe?`${e.slice(0,pe)}\u2026`:e}function me(e,t,r){let n=e.toLowerCase(),i=[];for(let[a,o]of t){let s=o.split(`
2
2
  `);for(let u=0;u<s.length;u++){let d=s[u];if(d.toLowerCase().includes(n)&&(i.push(`${a}${r}:${u+1}: ${dt(d)}`),i.length>=he))return i}}return i}function fe(e,t){return t.length===0?`No matches for '${e}'.`:`${t.length===he?`${t.length}+ matches (truncated):`:`${t.length} matches:`}
3
3
  ${t.join(`
4
- `)}`}var M=null;function ut(){if(M)return M;let e=crypto.createHash("sha256");for(let[t,r]of Array.from(knowledge.getAllKnowledge()).sort(([n],[i])=>n.localeCompare(i)))e.update(t),e.update("\0"),e.update(r),e.update("\0");return M=e.digest("hex").slice(0,16),M}var I={transport:"stdio",authEnabled:false};function ve(e){I=e;}function O(e,t,r){r.length!==0&&e.push("",`**${t}:**`,...r.map(n=>`- ${n}`));}function pt(e){let t=[`# ${e.name}`,e.description,"",`**Version (live):** ${e.liveVersion??"unknown"}`,`**Version (baked):** ${e.bakedVersion}${e.stale?" (live fetch failed; using baked)":""}`,`**Published to npm:** ${e.published?"yes":"no (private workspace package)"}`];return e.homepage&&t.push(`**Homepage:** ${e.homepage}`),e.npmUrl&&t.push(`**npm:** ${e.npmUrl}`),O(t,"Dependencies",e.dependencies),O(t,"Peer dependencies",e.peerDependencies),O(t,"Optional dependencies",e.optionalDependencies),O(t,"Exports",e.exports),t.join(`
4
+ `)}`}var L=null;function ut(){if(L)return L;let e=crypto.createHash("sha256");for(let[t,r]of Array.from(knowledge.getAllKnowledge()).sort(([n],[i])=>n.localeCompare(i)))e.update(t),e.update("\0"),e.update(r),e.update("\0");return L=e.digest("hex").slice(0,16),L}var I={transport:"stdio",authEnabled:false};function ve(e){I=e;}function O(e,t,r){r.length!==0&&e.push("",`**${t}:**`,...r.map(n=>`- ${n}`));}function pt(e){let t=[`# ${e.name}`,e.description,"",`**Version (live):** ${e.liveVersion??"unknown"}`,`**Version (baked):** ${e.bakedVersion}${e.stale?" (live fetch failed; using baked)":""}`,`**Published to npm:** ${e.published?"yes":"no (private workspace package)"}`];return e.homepage&&t.push(`**Homepage:** ${e.homepage}`),e.npmUrl&&t.push(`**npm:** ${e.npmUrl}`),O(t,"Dependencies",e.dependencies),O(t,"Peer dependencies",e.peerDependencies),O(t,"Optional dependencies",e.optionalDependencies),O(t,"Exports",e.exports),t.join(`
5
5
  `)}function G(){let e=new mcp_js.McpServer({name:"directive",version:ue});return e.registerTool("list_knowledge",{title:"List Directive knowledge files",description:"List every knowledge file shipped in @directive-run/knowledge. Returns the file names (without .md) that can be passed to get_knowledge. Covers core docs (engine, facts, constraints, resolvers, derivations, effects, plugins, modules, systems, testing) and AI docs (orchestrator, agents, adapters, guardrails, memory, MCP, RAG, security, evals, budget, multi-agent).",inputSchema:{}},async()=>{let t=knowledge.getAllKnowledge(),r=Array.from(t.keys()).sort();return {content:[{type:"text",text:`${r.length} knowledge files:
6
6
  ${r.join(`
7
7
  `)}`}]}}),e.registerTool("get_knowledge",{title:"Get a Directive knowledge file",description:"Fetch the full Markdown contents of one Directive knowledge file by name. Use list_knowledge first to discover available names. Names match the file stem (e.g. 'constraints', 'ai-orchestrator', 'api-skeleton').",inputSchema:{name:zod.z.string().min(1).describe("The knowledge file name (no .md suffix). Example: 'constraints', 'ai-orchestrator', 'api-skeleton'.")}},async({name:t})=>{let r=knowledge.getKnowledge(t);return r?{content:[{type:"text",text:r}]}:{isError:true,content:[{type:"text",text:`Knowledge file not found: '${t}'. Call list_knowledge to see available names.`}]}}),e.registerTool("list_examples",{title:"List Directive code examples",description:"List every code example shipped in @directive-run/knowledge. Examples are minimal, working TypeScript files demonstrating one concept each. Pass the returned names to get_example.",inputSchema:{}},async()=>{let t=knowledge.getAllExamples(),r=Array.from(t.keys()).sort();return {content:[{type:"text",text:`${r.length} examples:
@@ -45,8 +45,8 @@ ${a}`);return {content:[{type:"text",text:n.join(`
45
45
 
46
46
  `)}]}}),e.registerTool("playground_link",{title:"Build a shareable playground link for a Directive snippet (single- or multi-file)",description:"Turn TypeScript source into a directive.run URL the user can click to open a real running project. Two input shapes:\n\n\u2022 `source` (single string) \u2014 for snippets that are already runnable (`get_example`, `fix_code` output, hand-written demos). Lands as `src/main.ts` in a StackBlitz project preloaded with @directive-run/core.\n\n\u2022 `files` (array of {path, source}) \u2014 for paired output from `generate_module` (which returns both a library `moduleSource` AND a runnable `runnerSource`). Pass `[{path: 'src/<name>.ts', source: moduleSource}, {path: 'src/main.ts', source: runnerSource}]` so the playground boots a project that actually demonstrates behavior. THIS IS THE NORMAL WAY TO HAND OFF `generate_module` OUTPUT.\n\nOptional `mode`: `'preview'` (default \u2014 code + Open-in-StackBlitz button, the only Directive-branded surface, recommended for first-time users) or `'instant'` (thin auto-submit redirect, lands in StackBlitz in ~600ms with no preview UI). Use `'instant'` after the user has road-tested one link, or when they explicitly want 'just open it'.\n\nPayload travels in the URL hash so it never reaches server logs. 8 KB cap on raw input.",inputSchema:{source:zod.z.string().min(1).max(D).optional().describe(`Single-file source (mutually exclusive with \`files\`). Use for already-runnable code from \`get_example\` / \`fix_code\`. Max ${D} bytes.`),files:zod.z.array(zod.z.object({path:zod.z.string().min(1).max(120).describe("Relative path inside the StackBlitz project, e.g. 'src/counter.ts' or 'src/main.ts'. One file should be 'src/main.ts' (the entry point tsx runs)."),source:zod.z.string().min(1).describe("File contents.")})).min(1).max(10).optional().describe(`Multi-file payload (mutually exclusive with \`source\`). Use for \`generate_module\` paired output. JSON-encoded array gets compressed; the encoded payload must stay under ${D} bytes.`),title:zod.z.string().min(1).max(120).optional().describe("Optional short label shown as the editor tab title on the playground page. Defaults to 'Untitled snippet'."),mode:zod.z.enum(["preview","instant"]).optional().describe("URL flavor: 'preview' (default) routes via directive.run/playground (preview + Open-in-StackBlitz button). 'instant' routes via directive.run/run (thin auto-submit redirect, lands directly in StackBlitz).")}},async({source:t,files:r,title:n,mode:i})=>{try{let a=F({source:t,files:r,title:n,mode:i}),o={url:a.url,mode:a.mode,fileCount:a.fileCount,sizeBytes:a.sizeBytes,urlBytes:a.urlBytes,title:a.title??null};return {content:[{type:"text",text:`<directive-data>
47
47
  ${JSON.stringify(o,null,2)}
48
- </directive-data>`}]}}catch(a){return {isError:true,content:[{type:"text",text:`playground_link failed \u2014 ${a instanceof _?`${a.code}: ${a.message}`:a.message}`}]}}}),e.registerTool("run_in_sandbox",{title:"Execute a Directive snippet and return its observed behavior",description:"Execute a Directive snippet inside a bounded worker_threads sandbox and return its observed behavior: console.log/warn/error output, the post-settle facts snapshot, any errors that occurred, and a `playgroundUrl` the user can click to edit the same snippet in StackBlitz.\n\nPair with `generate_module` to show the user what the generated module ACTUALLY DID when it ran (not just what it declares). Two input shapes match `playground_link`: pass `source` (single string) for already-runnable snippets (`get_example`, `fix_code`, hand-written demos), OR pass `files: [{path, source}]` for paired output from `generate_module` (the runner ends up at `src/main.ts` and is what tsx runs).\n\nSandbox boundary: an AST allowlist validator rejects imports outside `@directive-run/{core,ai,query}` and identifier references to FS / network / eval surfaces (process, require, fetch, fs, etc.); the worker has a 5-second wall-clock budget (clamped to [100ms, 10s]) and a 32 MB heap ceiling. Validator rejection, bundle failure, runtime error, and timeout all return structured results in `errors` rather than throwing.",inputSchema:{source:zod.z.string().min(1).max(D).optional().describe(`Single-file source (mutually exclusive with \`files\`). Use for already-runnable code. Max ${D} bytes.`),files:zod.z.array(zod.z.object({path:zod.z.string().min(1).max(120).describe("Relative path inside the sandbox, e.g. 'src/counter.ts'. One file MUST be 'src/main.ts' \u2014 that's the entry point the worker imports."),source:zod.z.string().min(1).describe("File contents.")})).min(1).max(10).optional().describe("Multi-file payload (mutually exclusive with `source`). Use for `generate_module` paired output."),timeoutMs:zod.z.number().int().min(100).max(1e4).optional().describe("Wall-clock execution budget in milliseconds. Default 5000. Clamped to [100, 10000].")}},async({source:t,files:r,timeoutMs:n})=>{try{let i=await le({source:t,files:r,timeoutMs:n}),a=null;try{a=F({source:t,files:r}).url;}catch{}let o={logs:i.logs,facts:i.facts,errors:i.errors,durationMs:i.durationMs,timedOut:i.timedOut,playgroundUrl:a};return {content:[{type:"text",text:`<directive-data>
48
+ </directive-data>`}]}}catch(a){return {isError:true,content:[{type:"text",text:`playground_link failed \u2014 ${a instanceof _?`${a.code}: ${a.message}`:a.message}`}]}}}),e.registerTool("run_in_sandbox",{title:"Execute a Directive snippet and return its observed behavior",description:"Execute a Directive snippet and return its observed behavior. Use `run_in_sandbox` when you want the transcript IN-CHAT (so you or your next reasoning step can see what happened). Use `playground_link` instead when you want to hand the USER an interactive URL. Both accept identical `source` / `files` shapes \u2014 copy the same payload across if you want both.\n\nResponse payload: `logs[]` (captured console.log/warn/error), `facts` (post-settle snapshot), `errors[]` (validation/bundle/runtime/timeout messages), `durationMs`, `timedOut`, and `playgroundUrl` (click-through to StackBlitz for the same snippet).\n\nDecoding errors:\n\u2022 `'<path>:<line>:<col> \u2014 <reason>'` \u2192 validation rejection (snippet hit the AST allowlist). REWRITE the snippet; re-running with the same input will reject again.\n\u2022 `'wall-clock budget of Nms elapsed'` plus `timedOut: true` \u2192 likely infinite loop or unawaited promise. Don't retry; surface to user.\n\u2022 `'cannot resolve \"./X\" from \"./Y\"'` or any `esbuild ...` \u2192 bundle failure; check file paths and imports.\n\u2022 Any other string \u2192 runtime throw (may be intentional from the module's logic; check `facts` to confirm).\n\nSandbox boundary (v0.3.0): the AST allowlist validator rejects (a) imports outside `@directive-run/{core, ai, query, react, vue, svelte, solid, lit, el, optimistic, timeline, mutator, knowledge, scaffold, claude-plugin, lint}` plus relative `./*.js` paths inside the payload, (b) free-identifier references to FS / network / eval surfaces (`process`, `require`, `fetch`, `eval`, `Buffer`, `setTimeout`, etc.), (c) `globalThis.process` / `Reflect.get(globalThis, ...)` / `.constructor` / `Function(...)` and other property-access bypass chains, (d) `@directive-run/{cli, mcp, sandbox, vite-plugin-api-proxy}` (build/CLI/sandbox tooling). The worker has a 5-second wall-clock budget (clamped to [100ms, 10s]) and a 32 MB heap ceiling.\n\nNote: `react/vue/svelte/solid/lit` import OK, but their runtime hooks (`useState`, etc.) need a DOM and throw in this Node sandbox. For UI demos, prefer `playground_link` (StackBlitz has a DOM).\n\nValidator rejection, bundle failure, runtime error, and timeout all return structured results in `errors` rather than throwing.",inputSchema:{source:zod.z.string().min(1).max(D).optional().describe(`Single-file source (mutually exclusive with \`files\`). Use for already-runnable code. Max ${D} bytes.`),files:zod.z.array(zod.z.object({path:zod.z.string().min(1).max(120).describe("Relative path inside the sandbox, e.g. 'src/counter.ts'. One file MUST be 'src/main.ts' \u2014 that's the entry point the worker imports."),source:zod.z.string().min(1).describe("File contents.")})).min(1).max(10).optional().describe("Multi-file payload (mutually exclusive with `source`). Use for `generate_module` paired output."),timeoutMs:zod.z.number().int().min(100).max(1e4).optional().describe("Wall-clock execution budget in milliseconds. Default 5000. Clamped to [100, 10000].")}},async({source:t,files:r,timeoutMs:n})=>{try{let i=await le({source:t,files:r,timeoutMs:n}),a=null;try{a=F({source:t,files:r}).url;}catch{}let o={logs:i.logs,facts:i.facts,errors:i.errors,durationMs:i.durationMs,timedOut:i.timedOut,playgroundUrl:a};return {content:[{type:"text",text:`<directive-data>
49
49
  ${JSON.stringify(o,null,2)}
50
- </directive-data>`}]}}catch(i){return {isError:true,content:[{type:"text",text:`run_in_sandbox failed \u2014 ${i instanceof R?`${i.code}: ${i.message}`:i.message}`}]}}}),e}var ye="/messages",we="/sse",ft="/healthz",ht=1e6,vt=64,yt=300*1e3,wt=3e4,xt=new Set(["127.0.0.1","localhost","::1","0:0:0:0:0:0:0:1"]),H=class extends Error{};function bt(e){return xt.has(e.toLowerCase())}function kt(e){let t=e.port??3e3,r=e.host??"127.0.0.1",n=e.logger??console,i=e.token??process.env.DIRECTIVE_MCP_TOKEN??void 0;if(!bt(r)&&!i)throw new H("Public hosts require a token. Pass --token <value> or set DIRECTIVE_MCP_TOKEN, or bind to 127.0.0.1 for local dev.");return {port:t,host:r,logger:n,token:i,allowOrigins:e.allowOrigins??[],bodyLimitBytes:e.bodyLimitBytes??ht,maxSessions:e.maxSessions??vt,idleTimeoutMs:e.idleTimeoutMs??yt}}function xe(e,t){if(!t)return true;let r=e.headers.authorization;return typeof r!="string"?false:/^Bearer\s+(.+)$/i.exec(r)?.[1]?.trim()===t}function be(e,t){if(t.length===0)return true;let r=e.headers.origin;return typeof r!="string"?false:t.includes(r)}function E(e,t,r,n={}){e.writeHead(t,{"Content-Type":"text/plain",...n}),e.end(r);}function K(e,t){ve({transport:"sse",authEnabled:t,sessionCount:e.size});}var z=0;async function St(e,t,r,n){if(!xe(e,n.token)){E(t,401,"unauthorized");return}if(!be(e,n.allowOrigins)){E(t,403,"origin not allowed");return}if(r.size+z>=n.maxSessions){E(t,429,"session cap reached",{"Retry-After":"60"});return}z+=1;let i=false;try{let a=new sse_js.SSEServerTransport(ye,t),o=G();r.set(a.sessionId,{transport:a,lastActivity:Date.now()}),i=!0,K(r,!!n.token);let s=()=>{r.delete(a.sessionId),K(r,!!n.token);};t.on("close",s),a.onclose=s,await o.connect(a),n.logger.log(`[directive-mcp] sse session opened: ${a.sessionId}`);}finally{z-=1;}}async function _t(e,t,r,n,i){if(!xe(e,i.token)){E(t,401,"unauthorized");return}if(!be(e,i.allowOrigins)){E(t,403,"origin not allowed");return}let a=Number(e.headers["content-length"]??"0");if(Number.isFinite(a)&&a>i.bodyLimitBytes){E(t,413,`body exceeds ${i.bodyLimitBytes} bytes`);return}let o=r.searchParams.get("sessionId");if(!o){E(t,400,"missing sessionId query parameter");return}let s=n.get(o);if(!s){E(t,404,`unknown session: ${o}`);return}s.lastActivity=Date.now();let u=0,d=false;e.on("data",p=>{u+=Buffer.byteLength(p),u>i.bodyLimitBytes&&!d&&(d=true,E(t,413,`body exceeds ${i.bodyLimitBytes} bytes`),e.destroy());}),!d&&await s.transport.handlePostMessage(e,t);}async function Tt(e,t,r,n){let i=new URL(e.url??"/",`http://${e.headers.host??n.host}`);if(e.method==="GET"&&i.pathname===ft){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}if(e.method==="GET"&&i.pathname===we){await St(e,t,r,n);return}if(e.method==="POST"&&i.pathname===ye){await _t(e,t,i,r,n);return}E(t,404,"not found");}function Et(e,t){return setInterval(()=>{let r=Date.now();for(let[n,i]of e)r-i.lastActivity>t.idleTimeoutMs&&(e.delete(n),i.transport.close().catch(()=>{}),K(e,!!t.token),t.logger.log(`[directive-mcp] pruned idle session: ${n}`));},wt).unref()}async function Dt(e={}){let t=kt(e),r=new Map,n=http.createServer(async(a,o)=>{try{await Tt(a,o,r,t);}catch(s){t.logger.error("[directive-mcp] request error:",s),o.headersSent||o.writeHead(500,{"Content-Type":"text/plain"}),o.end("internal server error");}}),i=Et(r,t);return n.on("close",()=>{clearInterval(i);}),await new Promise(a=>{n.listen(t.port,t.host,()=>{t.logger.log(`[directive-mcp] sse server listening at http://${t.host}:${t.port}${we}${t.token?" (auth: bearer-token)":" (auth: none, loopback only)"}`),a();});}),n}
50
+ </directive-data>`}]}}catch(i){return {isError:true,content:[{type:"text",text:`run_in_sandbox failed \u2014 ${i instanceof $?`${i.code}: ${i.message}`:i.message}`}]}}}),e}var ye="/messages",we="/sse",ft="/healthz",ht=1e6,vt=64,yt=300*1e3,wt=3e4,xt=new Set(["127.0.0.1","localhost","::1","0:0:0:0:0:0:0:1"]),H=class extends Error{};function bt(e){return xt.has(e.toLowerCase())}function kt(e){let t=e.port??3e3,r=e.host??"127.0.0.1",n=e.logger??console,i=e.token??process.env.DIRECTIVE_MCP_TOKEN??void 0;if(!bt(r)&&!i)throw new H("Public hosts require a token. Pass --token <value> or set DIRECTIVE_MCP_TOKEN, or bind to 127.0.0.1 for local dev.");return {port:t,host:r,logger:n,token:i,allowOrigins:e.allowOrigins??[],bodyLimitBytes:e.bodyLimitBytes??ht,maxSessions:e.maxSessions??vt,idleTimeoutMs:e.idleTimeoutMs??yt}}function xe(e,t){if(!t)return true;let r=e.headers.authorization;return typeof r!="string"?false:/^Bearer\s+(.+)$/i.exec(r)?.[1]?.trim()===t}function be(e,t){if(t.length===0)return true;let r=e.headers.origin;return typeof r!="string"?false:t.includes(r)}function E(e,t,r,n={}){e.writeHead(t,{"Content-Type":"text/plain",...n}),e.end(r);}function K(e,t){ve({transport:"sse",authEnabled:t,sessionCount:e.size});}var z=0;async function St(e,t,r,n){if(!xe(e,n.token)){E(t,401,"unauthorized");return}if(!be(e,n.allowOrigins)){E(t,403,"origin not allowed");return}if(r.size+z>=n.maxSessions){E(t,429,"session cap reached",{"Retry-After":"60"});return}z+=1;let i=false;try{let a=new sse_js.SSEServerTransport(ye,t),o=G();r.set(a.sessionId,{transport:a,lastActivity:Date.now()}),i=!0,K(r,!!n.token);let s=()=>{r.delete(a.sessionId),K(r,!!n.token);};t.on("close",s),a.onclose=s,await o.connect(a),n.logger.log(`[directive-mcp] sse session opened: ${a.sessionId}`);}finally{z-=1;}}async function _t(e,t,r,n,i){if(!xe(e,i.token)){E(t,401,"unauthorized");return}if(!be(e,i.allowOrigins)){E(t,403,"origin not allowed");return}let a=Number(e.headers["content-length"]??"0");if(Number.isFinite(a)&&a>i.bodyLimitBytes){E(t,413,`body exceeds ${i.bodyLimitBytes} bytes`);return}let o=r.searchParams.get("sessionId");if(!o){E(t,400,"missing sessionId query parameter");return}let s=n.get(o);if(!s){E(t,404,`unknown session: ${o}`);return}s.lastActivity=Date.now();let u=0,d=false;e.on("data",p=>{u+=Buffer.byteLength(p),u>i.bodyLimitBytes&&!d&&(d=true,E(t,413,`body exceeds ${i.bodyLimitBytes} bytes`),e.destroy());}),!d&&await s.transport.handlePostMessage(e,t);}async function Tt(e,t,r,n){let i=new URL(e.url??"/",`http://${e.headers.host??n.host}`);if(e.method==="GET"&&i.pathname===ft){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}if(e.method==="GET"&&i.pathname===we){await St(e,t,r,n);return}if(e.method==="POST"&&i.pathname===ye){await _t(e,t,i,r,n);return}E(t,404,"not found");}function Et(e,t){return setInterval(()=>{let r=Date.now();for(let[n,i]of e)r-i.lastActivity>t.idleTimeoutMs&&(e.delete(n),i.transport.close().catch(()=>{}),K(e,!!t.token),t.logger.log(`[directive-mcp] pruned idle session: ${n}`));},wt).unref()}async function Dt(e={}){let t=kt(e),r=new Map,n=http.createServer(async(a,o)=>{try{await Tt(a,o,r,t);}catch(s){t.logger.error("[directive-mcp] request error:",s),o.headersSent||o.writeHead(500,{"Content-Type":"text/plain"}),o.end("internal server error");}}),i=Et(r,t);return n.on("close",()=>{clearInterval(i);}),await new Promise(a=>{n.listen(t.port,t.host,()=>{t.logger.log(`[directive-mcp] sse server listening at http://${t.host}:${t.port}${we}${t.token?" (auth: bearer-token)":" (auth: none, loopback only)"}`),a();});}),n}
51
51
  exports.createDirectiveServer=G;exports.startSseServer=Dt;//# sourceMappingURL=index.cjs.map
52
52
  //# sourceMappingURL=index.cjs.map