@directive-run/mcp 0.4.0 → 0.5.1

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/README.md CHANGED
@@ -166,7 +166,7 @@ Endpoints:
166
166
  - `POST /messages?sessionId=…` — client→server JSON-RPC messages.
167
167
  - `GET /healthz` — liveness probe.
168
168
 
169
- ## Tools (21)
169
+ ## Tools (22)
170
170
 
171
171
  ### Knowledge
172
172
 
@@ -228,6 +228,7 @@ Endpoints:
228
228
  | Tool | Purpose |
229
229
  |---|---|
230
230
  | `playground_link` | Turn TypeScript source into a clickable URL that boots a real Directive project in StackBlitz. Two shapes: pass `source` (single string) for already-runnable snippets from `get_example` / `fix_code`, OR pass `files: [{path, source}, …]` for the paired library + runner output from `generate_module`. Optional `mode: "preview" \| "instant"` — `"preview"` (default) lands on `directive.run/playground` with code + Open-in-StackBlitz button; `"instant"` lands on `directive.run/run` which auto-submits the StackBlitz form (no preview UI). 8 KB cap on raw input. Payload travels in the URL hash so it never reaches server logs. |
231
+ | `run_in_sandbox` | Execute a Directive snippet inside a bounded worker_threads sandbox and return its observed behavior — captured `console.log/warn/error` lines, the post-`settle()` facts snapshot, structured errors, plus a `playgroundUrl` for click-through editing in StackBlitz. Pair with `generate_module` to show the user what the generated module ACTUALLY DID when it ran. **v0.3.0 boundary:** AST allowlist permits `@directive-run/{core, ai, query, react, vue, svelte, solid, lit, el, optimistic, timeline, mutator, knowledge, scaffold, claude-plugin, lint}` + relative `./*.js`; rejects FS/network/eval identifier references AND their property-access bypass chains (`globalThis.process`, `Reflect.get(globalThis, …)`, `.constructor`, `Function(...)`). 5-second wall-clock budget (clamped to [100ms, 10s]), 32 MB heap. Note: `react/vue/svelte/solid/lit` import OK but their runtime hooks throw in Node — use `playground_link` for UI demos. |
231
232
 
232
233
  **Composition for a "try it now" link:** `generate_module` returns paired `{moduleSource, runnerSource, suggestedFilenames}` — pass both to `playground_link` as a `files` array (the runner is the entry point at `src/main.ts`) and the user clicks ONE URL that boots a project where `tsx src/main.ts` actually logs Directive facts to the StackBlitz terminal. For `get_example` / `fix_code` output (already runnable), pass the single `source` string instead.
233
234
 
package/dist/cli.js CHANGED
@@ -1,52 +1,54 @@
1
1
  #!/usr/bin/env node
2
- import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {createHash}from'crypto';import {getAllSkills,getSkill}from'@directive-run/claude-plugin';import {getAllKnowledge,getKnowledge,getAllExamples,getExample,getCompositionsFor,getReverseCompositionsFor,getAntiPatterns,getAntiPatternById,MIGRATION_SOURCES,getMigrationPattern}from'@directive-run/knowledge';import {MODULE_SECTIONS,validateModuleName,generateOrchestrator,generateModule,suggestFileNames,requiredPackages}from'@directive-run/scaffold';import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {z as z$1}from'zod';import {fileURLToPath}from'url';import {Worker}from'worker_threads';import {runRules,applyFix}from'@directive-run/lint';import {createServer}from'http';import {SSEServerTransport}from'@modelcontextprotocol/sdk/server/sse.js';var xe=Object.create;var K=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var Ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var De=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Se(t))!Te.call(e,o)&&o!==r&&K(e,o,{get:()=>t[o],enumerable:!(n=be(t,o))||n.enumerable});return e};var Re=(e,t,r)=>(r=e!=null?xe(_e(e)):{},De(K(r,"default",{value:e,enumerable:true}),e));var ne=Ee((Mt,I)=>{var B=(function(){var e=String.fromCharCode,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",n={};function o(i,s){if(!n[i]){n[i]={};for(var u=0;u<i.length;u++)n[i][i.charAt(u)]=u;}return n[i][s]}var a={compressToBase64:function(i){if(i==null)return "";var s=a._compress(i,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(i){return i==null?"":i==""?null:a._decompress(i.length,32,function(s){return o(t,i.charAt(s))})},compressToUTF16:function(i){return i==null?"":a._compress(i,15,function(s){return e(s+32)})+" "},decompressFromUTF16:function(i){return i==null?"":i==""?null:a._decompress(i.length,16384,function(s){return i.charCodeAt(s)-32})},compressToUint8Array:function(i){for(var s=a.compress(i),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(i){if(i==null)return a.decompress(i);for(var s=new Array(i.length/2),u=0,d=s.length;u<d;u++)s[u]=i[u*2]*256+i[u*2+1];var p=[];return s.forEach(function(y){p.push(e(y));}),a.decompress(p.join(""))},compressToEncodedURIComponent:function(i){return i==null?"":a._compress(i,6,function(s){return r.charAt(s)})},decompressFromEncodedURIComponent:function(i){return i==null?"":i==""?null:(i=i.replace(/ /g,"+"),a._decompress(i.length,32,function(s){return o(r,i.charAt(s))}))},compress:function(i){return a._compress(i,16,function(s){return e(s)})},_compress:function(i,s,u){if(i==null)return "";var d,p,y={},x={},b="",T="",v="",w=2,D=3,m=2,h=[],c=0,l=0,k;for(k=0;k<i.length;k+=1)if(b=i.charAt(k),Object.prototype.hasOwnProperty.call(y,b)||(y[b]=D++,x[b]=true),T=v+b,Object.prototype.hasOwnProperty.call(y,T))v=T;else {if(Object.prototype.hasOwnProperty.call(x,v)){if(v.charCodeAt(0)<256){for(d=0;d<m;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<m;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,m),m++),delete x[v];}else for(p=y[v],d=0;d<m;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,m),m++),y[T]=D++,v=String(b);}if(v!==""){if(Object.prototype.hasOwnProperty.call(x,v)){if(v.charCodeAt(0)<256){for(d=0;d<m;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<m;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,m),m++),delete x[v];}else for(p=y[v],d=0;d<m;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,m),m++);}for(p=2,d=0;d<m;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(i){return i==null?"":i==""?null:a._decompress(i.length,32768,function(s){return i.charCodeAt(s)})},_decompress:function(i,s,u){var d=[],y=4,x=4,b=3,T="",v=[],w,D,m,h,c,l,k,g={val:u(0),position:s,index:1};for(w=0;w<3;w+=1)d[w]=w;for(m=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++)),m|=(h>0?1:0)*l,l<<=1;switch(m){case 0:for(m=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++)),m|=(h>0?1:0)*l,l<<=1;k=e(m);break;case 1:for(m=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++)),m|=(h>0?1:0)*l,l<<=1;k=e(m);break;case 2:return ""}for(d[3]=k,D=k,v.push(k);;){if(g.index>i)return "";for(m=0,c=Math.pow(2,b),l=1;l!=c;)h=g.val&g.position,g.position>>=1,g.position==0&&(g.position=s,g.val=u(g.index++)),m|=(h>0?1:0)*l,l<<=1;switch(k=m){case 0:for(m=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++)),m|=(h>0?1:0)*l,l<<=1;d[x++]=e(m),k=x-1,y--;break;case 1:for(m=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++)),m|=(h>0?1:0)*l,l<<=1;d[x++]=e(m),k=x-1,y--;break;case 2:return v.join("")}if(y==0&&(y=Math.pow(2,b),b++),d[k])T=d[k];else if(k===x)T=D+D.charAt(0);else return null;v.push(T),d[x++]=D+T.charAt(0),y--,D=T,y==0&&(y=Math.pow(2,b),b++);}}};return a})();typeof define=="function"&&define.amd?define(function(){return B}):typeof I<"u"&&I!=null?I.exports=B:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return B});});var N=[{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.4.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/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/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}],W="2026-06-06T15:00:31.074Z";var Y=2e5,X=5e3,Oe=/^[\w./-]{1,128}$/,S=class extends Error{constructor(r,n){super(r);this.code=n;}};function J(e){let t=Buffer.byteLength(e.source,"utf8");if(t>Y)throw new S(`source is ${t} bytes (max ${Y})`,"source-too-large");let r="fileName"in e?e.fileName:void 0;if(r!==void 0&&!Oe.test(r))throw new S("invalid fileName","bad-filename")}async function Ce(){let e=await import.meta.resolve("@directive-run/lint/worker");return fileURLToPath(e)}async function Z(e){let t=await Ce(),r=new Worker(t,{stderr:false}),n=null;try{return await new Promise((o,a)=>{let i=!1;r.once("message",s=>{i=!0,s.ok&&s.result!==void 0?o(s.result):a(new S(s.error??"worker returned without result","worker-error"));}),r.once("error",s=>{i=!0,a(new S(s.message,"worker-error"));}),r.once("exit",s=>{!i&&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 ${X}ms budget`,"timeout"));},X),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 Q(e){return J(e),q()?Z({kind:"run",source:e.source,options:{fileName:e.fileName,ruleFilter:e.ruleFilter}}):runRules(e.source,{fileName:e.fileName,ruleFilter:e.ruleFilter})}async function ee(e){return J(e),q()?Z({kind:"fix",source:e.source,finding:e.finding}):applyFix(e.source,e.finding)}var Le=3600*1e3,Me=3e3,te=new Map;function U(){return N.map(e=>({name:e.name,summary:e.description,published:e.published}))}async function re(e){let t=N.find(o=>o.name===e);if(!t)return;let{liveVersion:r,stale:n}=await Ue(t);return Ne(t,r,n)}function Ne(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 Ue(e){if(!e.published)return {stale:true};let t=te.get(e.name);if(t&&Date.now()-t.fetchedAt<Le)return {liveVersion:t.liveVersion,stale:t.liveVersion===void 0};let r=await Be(e.name);return te.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 Be(e){let t=`https://registry.npmjs.org/${encodeURIComponent(e).replace(/%2F/g,"/")}/latest`,r=new AbortController,n=setTimeout(()=>r.abort(),Me);try{let o=await fetch(t,{signal:r.signal});if(!o.ok)return {error:`HTTP ${o.status}`};let a=await o.json();return typeof a.version=="string"?{liveVersion:a.version}:{error:"no version field"}}catch(o){return {error:o.message}}finally{clearTimeout(n);}}var F=Re(ne()),R=8e3,Fe="https://directive.run/playground",je="https://directive.run/run",_=class extends Error{constructor(r,n){super(r);this.code=n;}};function ie(e){if(e>R)throw new _(`payload is ${e} bytes (max ${R}). Payloads larger than ${R} bytes don't fit reliably in a URL \u2014 copy the source into a fresh Stackblitz project instead.`,"source-too-large")}function oe(e){return encodeURIComponent(e)}function se(e){return e==="instant"?je:Fe}function Ve(e,t,r){if(e.length===0)throw new _("source is empty","source-empty");let n=Buffer.byteLength(e,"utf8");ie(n);let a=[`src=${(0, F.compressToEncodedURIComponent)(e)}`];t&&a.push(`t=${oe(t)}`);let i=`${se(r)}#${a.join("&")}`;return {url:i,sizeBytes:n,urlBytes:Buffer.byteLength(i,"utf8"),fileCount:1,mode:r,title:t}}function Ge(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),o=Buffer.byteLength(n,"utf8");ie(o);let i=[`files=${(0, F.compressToEncodedURIComponent)(n)}`];t&&i.push(`t=${oe(t)}`);let s=`${se(r)}#${i.join("&")}`;return {url:s,sizeBytes:o,urlBytes:Buffer.byteLength(s,"utf8"),fileCount:e.length,mode:r,title:t}}function ae(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?Ge(e.files,e.title,t):Ve(e.source,e.title,t)}var le="0.4.0",me=50,de=200,ue=512;function st(e){return e.length>de?`${e.slice(0,de)}\u2026`:e}function pe(e,t,r){let n=e.toLowerCase(),o=[];for(let[a,i]of t){let s=i.split(`
3
- `);for(let u=0;u<s.length;u++){let d=s[u];if(d.toLowerCase().includes(n)&&(o.push(`${a}${r}:${u+1}: ${st(d)}`),o.length>=me))return o}}return o}function ge(e,t){return t.length===0?`No matches for '${e}'.`:`${t.length===me?`${t.length}+ matches (truncated):`:`${t.length} matches:`}
2
+ import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {createHash}from'crypto';import {getAllSkills,getSkill}from'@directive-run/claude-plugin';import {getAllKnowledge,getKnowledge,getAllExamples,getExample,getCompositionsFor,getReverseCompositionsFor,getAntiPatterns,getAntiPatternById,MIGRATION_SOURCES,getMigrationPattern}from'@directive-run/knowledge';import {MODULE_SECTIONS,validateModuleName,generateOrchestrator,generateModule,suggestFileNames,requiredPackages}from'@directive-run/scaffold';import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {z}from'zod';import {fileURLToPath}from'url';import {Worker}from'worker_threads';import {runRules,applyFix}from'@directive-run/lint';import {runInSandbox}from'@directive-run/sandbox';import {createServer}from'http';import {SSEServerTransport}from'@modelcontextprotocol/sdk/server/sse.js';var Te=Object.create;var X=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Ie=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ae=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of De(t))!$e.call(e,i)&&i!==r&&X(e,i,{get:()=>t[i],enumerable:!(n=Ee(t,i))||n.enumerable});return e};var Pe=(e,t,r)=>(r=e!=null?Te(Re(e)):{},Ae(X(r,"default",{value:e,enumerable:true}),e));var se=Ie((Gt,A)=>{var j=(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={},x={},k="",T="",v="",w=2,R=3,f=2,h=[],c=0,l=0,b;for(b=0;b<o.length;b+=1)if(k=o.charAt(b),Object.prototype.hasOwnProperty.call(y,k)||(y[k]=R++,x[k]=true),T=v+k,Object.prototype.hasOwnProperty.call(y,T))v=T;else {if(Object.prototype.hasOwnProperty.call(x,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 x[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(x,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 x[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,x=4,k=3,T="",v=[],w,R,f,h,c,l,b,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;b=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;b=e(f);break;case 2:return ""}for(d[3]=b,R=b,v.push(b);;){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(b=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[x++]=e(f),b=x-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[x++]=e(f),b=x-1,y--;break;case 2:return v.join("")}if(y==0&&(y=Math.pow(2,k),k++),d[b])T=d[b];else if(b===x)T=R+R.charAt(0);else return null;v.push(T),d[x++]=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 j}):typeof A<"u"&&A!=null?A.exports=j:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return j});});var N=[{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.1",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.2.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}],J="2026-06-07T17:29:43.961Z";var q=2e5,Z=5e3,Ue=/^[\w./-]{1,128}$/,S=class extends Error{constructor(r,n){super(r);this.code=n;}};function Q(e){let t=Buffer.byteLength(e.source,"utf8");if(t>q)throw new S(`source is ${t} bytes (max ${q})`,"source-too-large");let r="fileName"in e?e.fileName:void 0;if(r!==void 0&&!Ue.test(r))throw new S("invalid fileName","bad-filename")}async function Be(){let e=await import.meta.resolve("@directive-run/lint/worker");return fileURLToPath(e)}async function ee(e){let t=await Be(),r=new 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 ${Z}ms budget`,"timeout"));},Z),r.postMessage(e);})}finally{n&&clearTimeout(n),await r.terminate().catch(()=>{});}}function te(){return !(process.env.DIRECTIVE_MCP_USE_LINT_WORKER==="0"||process.env.VITEST==="true")}async function re(e){return Q(e),te()?ee({kind:"run",source:e.source,options:{fileName:e.fileName,ruleFilter:e.ruleFilter}}):runRules(e.source,{fileName:e.fileName,ruleFilter:e.ruleFilter})}async function ne(e){return Q(e),te()?ee({kind:"fix",source:e.source,finding:e.finding}):applyFix(e.source,e.finding)}var Ne=3600*1e3,Fe=3e3,ie=new Map;function F(){return N.map(e=>({name:e.name,summary:e.description,published:e.published}))}async function oe(e){let t=N.find(i=>i.name===e);if(!t)return;let{liveVersion:r,stale:n}=await Ve(t);return je(t,r,n)}function je(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 Ve(e){if(!e.published)return {stale:true};let t=ie.get(e.name);if(t&&Date.now()-t.fetchedAt<Ne)return {liveVersion:t.liveVersion,stale:t.liveVersion===void 0};let r=await Ge(e.name);return ie.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 Ge(e){let t=`https://registry.npmjs.org/${encodeURIComponent(e).replace(/%2F/g,"/")}/latest`,r=new AbortController,n=setTimeout(()=>r.abort(),Fe);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 V=Pe(se()),D=8e3,He="https://directive.run/playground",ze="https://directive.run/run",_=class extends Error{constructor(r,n){super(r);this.code=n;}};function ae(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 ce(e){return encodeURIComponent(e)}function le(e){return e==="instant"?ze:He}function Ke(e,t,r){if(e.length===0)throw new _("source is empty","source-empty");let n=Buffer.byteLength(e,"utf8");ae(n);let a=[`src=${(0, V.compressToEncodedURIComponent)(e)}`];t&&a.push(`t=${ce(t)}`);let o=`${le(r)}#${a.join("&")}`;return {url:o,sizeBytes:n,urlBytes:Buffer.byteLength(o,"utf8"),fileCount:1,mode:r,title:t}}function We(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");ae(i);let o=[`files=${(0, V.compressToEncodedURIComponent)(n)}`];t&&o.push(`t=${ce(t)}`);let s=`${le(r)}#${o.join("&")}`;return {url:s,sizeBytes:i,urlBytes:Buffer.byteLength(s,"utf8"),fileCount:e.length,mode:r,title:t}}function G(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?We(e.files,e.title,t):Ke(e.source,e.title,t)}var P=2e5,de=10,Xe=/^[\w./-]{1,128}$/,$=class extends Error{constructor(r,n){super(r);this.code=n;}};function Je(e){if(e.files){if(e.files.length>de)throw new $(`payload exceeds ${de} files`,"input-invalid");let t=0;for(let r of e.files){if(!Xe.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 ue(e){return Je(e),runInSandbox(e)}var ge="0.5.1",ye=50,me=200,fe=512;function gt(e){return e.length>me?`${e.slice(0,me)}\u2026`:e}function he(e,t,r){let n=e.toLowerCase(),i=[];for(let[a,o]of t){let s=o.split(`
3
+ `);for(let u=0;u<s.length;u++){let d=s[u];if(d.toLowerCase().includes(n)&&(i.push(`${a}${r}:${u+1}: ${gt(d)}`),i.length>=ye))return i}}return i}function ve(e,t){return t.length===0?`No matches for '${e}'.`:`${t.length===ye?`${t.length}+ matches (truncated):`:`${t.length} matches:`}
4
4
  ${t.join(`
5
- `)}`}var A=null;function at(){if(A)return A;let e=createHash("sha256");for(let[t,r]of Array.from(getAllKnowledge()).sort(([n],[o])=>n.localeCompare(o)))e.update(t),e.update("\0"),e.update(r),e.update("\0");return A=e.digest("hex").slice(0,16),A}var $={transport:"stdio",authEnabled:false};function C(e){$=e;}function O(e,t,r){r.length!==0&&e.push("",`**${t}:**`,...r.map(n=>`- ${n}`));}function ct(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(`
6
- `)}function L(){let e=new McpServer({name:"directive",version:le});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=getAllKnowledge(),r=Array.from(t.keys()).sort();return {content:[{type:"text",text:`${r.length} knowledge files:
5
+ `)}`}var M=null;function mt(){if(M)return M;let e=createHash("sha256");for(let[t,r]of Array.from(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 L(e){I=e;}function C(e,t,r){r.length!==0&&e.push("",`**${t}:**`,...r.map(n=>`- ${n}`));}function ft(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}`),C(t,"Dependencies",e.dependencies),C(t,"Peer dependencies",e.peerDependencies),C(t,"Optional dependencies",e.optionalDependencies),C(t,"Exports",e.exports),t.join(`
6
+ `)}function U(){let e=new McpServer({name:"directive",version:ge});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=getAllKnowledge(),r=Array.from(t.keys()).sort();return {content:[{type:"text",text:`${r.length} knowledge files:
7
7
  ${r.join(`
8
- `)}`}]}}),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:z$1.string().min(1).describe("The knowledge file name (no .md suffix). Example: 'constraints', 'ai-orchestrator', 'api-skeleton'.")}},async({name:t})=>{let r=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=getAllExamples(),r=Array.from(t.keys()).sort();return {content:[{type:"text",text:`${r.length} examples:
8
+ `)}`}]}}),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:z.string().min(1).describe("The knowledge file name (no .md suffix). Example: 'constraints', 'ai-orchestrator', 'api-skeleton'.")}},async({name:t})=>{let r=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=getAllExamples(),r=Array.from(t.keys()).sort();return {content:[{type:"text",text:`${r.length} examples:
9
9
  ${r.join(`
10
- `)}`}]}}),e.registerTool("get_example",{title:"Get a Directive code example",description:"Fetch the source of one Directive code example by name. Use list_examples first to discover available names. Returns raw TypeScript.",inputSchema:{name:z$1.string().min(1).describe("The example file name (no .ts suffix). Example: 'basic-module', 'ai-orchestrator'.")}},async({name:t})=>{let r=getExample(t);return r?{content:[{type:"text",text:`\`\`\`typescript
10
+ `)}`}]}}),e.registerTool("get_example",{title:"Get a Directive code example",description:"Fetch the source of one Directive code example by name. Use list_examples first to discover available names. Returns raw TypeScript.",inputSchema:{name:z.string().min(1).describe("The example file name (no .ts suffix). Example: 'basic-module', 'ai-orchestrator'.")}},async({name:t})=>{let r=getExample(t);return r?{content:[{type:"text",text:`\`\`\`typescript
11
11
  ${r}
12
- \`\`\``}]}:{isError:true,content:[{type:"text",text:`Example not found: '${t}'. Call list_examples to see available names.`}]}}),e.registerTool("search_knowledge",{title:"Search Directive knowledge files",description:"Case-insensitive substring search across every knowledge file. Returns existing reference material; does NOT generate code. Use this to find which knowledge file covers a topic before calling get_knowledge for the full document.",inputSchema:{query:z$1.string().min(1).max(ue).describe("The search string. Matched case-insensitively against every line of every knowledge file.")}},async({query:t})=>{let r=pe(t,getAllKnowledge(),".md");return {content:[{type:"text",text:ge(t,r)}]}}),e.registerTool("search_examples",{title:"Search Directive code examples",description:"Case-insensitive substring search across every bundled code example (.ts files in @directive-run/knowledge). Returns existing reference material; does NOT generate code. Use this to find which example demonstrates a concept before calling get_example for the full source.",inputSchema:{query:z$1.string().min(1).max(ue).describe("The search string. Matched case-insensitively against every line of every example file.")}},async({query:t})=>{let r=pe(t,getAllExamples(),".ts");return {content:[{type:"text",text:ge(t,r)}]}}),e.registerTool("list_packages",{title:"List @directive-run/* packages",description:"Enumerate every @directive-run/* package known to this MCP server. Returns name + one-line description. Use this to answer 'what should I install for X?' and to discover names to pass to get_package_info or get_composable_packages. Returns existing reference material; does NOT generate code.",inputSchema:{}},async()=>{let t=U(),r=t.map(n=>`${n.name}${n.published?"":" (private)"} \u2014 ${n.summary}`);return {content:[{type:"text",text:`${t.length} packages:
12
+ \`\`\``}]}:{isError:true,content:[{type:"text",text:`Example not found: '${t}'. Call list_examples to see available names.`}]}}),e.registerTool("search_knowledge",{title:"Search Directive knowledge files",description:"Case-insensitive substring search across every knowledge file. Returns existing reference material; does NOT generate code. Use this to find which knowledge file covers a topic before calling get_knowledge for the full document.",inputSchema:{query:z.string().min(1).max(fe).describe("The search string. Matched case-insensitively against every line of every knowledge file.")}},async({query:t})=>{let r=he(t,getAllKnowledge(),".md");return {content:[{type:"text",text:ve(t,r)}]}}),e.registerTool("search_examples",{title:"Search Directive code examples",description:"Case-insensitive substring search across every bundled code example (.ts files in @directive-run/knowledge). Returns existing reference material; does NOT generate code. Use this to find which example demonstrates a concept before calling get_example for the full source.",inputSchema:{query:z.string().min(1).max(fe).describe("The search string. Matched case-insensitively against every line of every example file.")}},async({query:t})=>{let r=he(t,getAllExamples(),".ts");return {content:[{type:"text",text:ve(t,r)}]}}),e.registerTool("list_packages",{title:"List @directive-run/* packages",description:"Enumerate every @directive-run/* package known to this MCP server. Returns name + one-line description. Use this to answer 'what should I install for X?' and to discover names to pass to get_package_info or get_composable_packages. Returns existing reference material; does NOT generate code.",inputSchema:{}},async()=>{let t=F(),r=t.map(n=>`${n.name}${n.published?"":" (private)"} \u2014 ${n.summary}`);return {content:[{type:"text",text:`${t.length} packages:
13
13
  ${r.join(`
14
- `)}`}]}}),e.registerTool("get_package_info",{title:"Get @directive-run/* package detail",description:"Fetch detailed info for one @directive-run/* package: description, dependencies, peerDependencies, exports, npm URL. Returns the version baked into this MCP build AND the live-from-npm version when available (1-hour cache, 3-second timeout, falls back to baked version on network failure). Returns existing reference material; does NOT generate code.",inputSchema:{name:z$1.string().min(1).max(128).describe("Package name (e.g. '@directive-run/core'). Call list_packages first to discover valid names.")}},async({name:t})=>{let r=await re(t);return r?{content:[{type:"text",text:ct(r)}]}:{isError:true,content:[{type:"text",text:`Package not found: '${t}'. Call list_packages to see available names.`}]}}),e.registerTool("get_composable_packages",{title:"Get composition siblings for a package",description:"Given a @directive-run/* package name, return the sibling packages it composes with (outgoing edges) AND the packages that compose with IT (incoming edges). Each edge carries a one-line reason. Returns existing reference material; does NOT generate code. Use this to answer 'what should I pair @directive-run/X with?' or 'who else uses @directive-run/Y?'.",inputSchema:{name:z$1.string().min(1).max(128).describe("Package name (e.g. '@directive-run/query'). Call list_packages first to discover valid names.")}},async({name:t})=>{let r=getCompositionsFor(t),n=getReverseCompositionsFor(t);if(r.length===0&&n.length===0)return {isError:true,content:[{type:"text",text:U().some(i=>i.name===t)?`NO_COMPOSITIONS: '${t}' is a known package but has no composition edges yet. This is a coverage gap in compositions.json.`:`NOT_FOUND: '${t}' is not a known @directive-run/* package. Call list_packages to see available names.`}]};let o=[`# ${t}`,""];if(r.length>0){o.push("## Composes with:");for(let a of r)o.push(`- ${a.to} \u2014 ${a.reason}`);o.push("");}if(n.length>0){o.push("## Composed by:");for(let a of n)o.push(`- ${a.from} \u2014 ${a.reason}`);}return {content:[{type:"text",text:`<directive-data>
15
- ${o.join(`
14
+ `)}`}]}}),e.registerTool("get_package_info",{title:"Get @directive-run/* package detail",description:"Fetch detailed info for one @directive-run/* package: description, dependencies, peerDependencies, exports, npm URL. Returns the version baked into this MCP build AND the live-from-npm version when available (1-hour cache, 3-second timeout, falls back to baked version on network failure). Returns existing reference material; does NOT generate code.",inputSchema:{name:z.string().min(1).max(128).describe("Package name (e.g. '@directive-run/core'). Call list_packages first to discover valid names.")}},async({name:t})=>{let r=await oe(t);return r?{content:[{type:"text",text:ft(r)}]}:{isError:true,content:[{type:"text",text:`Package not found: '${t}'. Call list_packages to see available names.`}]}}),e.registerTool("get_composable_packages",{title:"Get composition siblings for a package",description:"Given a @directive-run/* package name, return the sibling packages it composes with (outgoing edges) AND the packages that compose with IT (incoming edges). Each edge carries a one-line reason. Returns existing reference material; does NOT generate code. Use this to answer 'what should I pair @directive-run/X with?' or 'who else uses @directive-run/Y?'.",inputSchema:{name:z.string().min(1).max(128).describe("Package name (e.g. '@directive-run/query'). Call list_packages first to discover valid names.")}},async({name:t})=>{let r=getCompositionsFor(t),n=getReverseCompositionsFor(t);if(r.length===0&&n.length===0)return {isError:true,content:[{type:"text",text:F().some(o=>o.name===t)?`NO_COMPOSITIONS: '${t}' is a known package but has no composition edges yet. This is a coverage gap in compositions.json.`:`NOT_FOUND: '${t}' is not a known @directive-run/* package. Call list_packages to see available names.`}]};let i=[`# ${t}`,""];if(r.length>0){i.push("## Composes with:");for(let a of r)i.push(`- ${a.to} \u2014 ${a.reason}`);i.push("");}if(n.length>0){i.push("## Composed by:");for(let a of n)i.push(`- ${a.from} \u2014 ${a.reason}`);}return {content:[{type:"text",text:`<directive-data>
15
+ ${i.join(`
16
16
  `)}
17
- </directive-data>`}]}}),e.registerTool("get_server_info",{title:"Get directive MCP server info",description:"Return version manifest for this MCP server build \u2014 package version, transport (stdio or SSE), whether auth is enabled, bundled-knowledge hash, package-registry build timestamp, and (for SSE) the current session count. Returns existing reference material; does NOT generate code. Use this to verify the client is talking to the expected build.",inputSchema:{}},async()=>{let t=[`# @directive-run/mcp@${le}`,`**Transport:** ${$.transport}`,`**Auth enabled:** ${$.authEnabled?"yes":"no"}`,`**Bundled knowledge hash:** ${at()}`,`**Package registry built at:** ${W}`];return $.sessionCount!==void 0&&t.push(`**Active SSE sessions:** ${$.sessionCount}`),{content:[{type:"text",text:t.join(`
17
+ </directive-data>`}]}}),e.registerTool("get_server_info",{title:"Get directive MCP server info",description:"Return version manifest for this MCP server build \u2014 package version, transport (stdio or SSE), whether auth is enabled, bundled-knowledge hash, package-registry build timestamp, and (for SSE) the current session count. Returns existing reference material; does NOT generate code. Use this to verify the client is talking to the expected build.",inputSchema:{}},async()=>{let t=[`# @directive-run/mcp@${ge}`,`**Transport:** ${I.transport}`,`**Auth enabled:** ${I.authEnabled?"yes":"no"}`,`**Bundled knowledge hash:** ${mt()}`,`**Package registry built at:** ${J}`];return I.sessionCount!==void 0&&t.push(`**Active SSE sessions:** ${I.sessionCount}`),{content:[{type:"text",text:t.join(`
18
18
  `)}]}}),e.registerTool("list_module_sections",{title:"List valid module sections for generate_module",description:"Enumerate the valid `sections` values that `generate_module` accepts: derive, events, constraints, resolvers, effects. Call this before generate_module so the section list comes from the server (no hallucination risk). Returns existing reference material; does NOT generate code.",inputSchema:{}},async()=>({content:[{type:"text",text:`${MODULE_SECTIONS.length} module sections:
19
19
  ${MODULE_SECTIONS.join(`
20
- `)}`}]})),e.registerTool("generate_module",{title:"Generate NEW Directive module source code (paired with a runnable driver)",description:'Generate a new Directive module or AI orchestrator as a paired source bundle: a library `moduleSource` (the `createModule(...)` definition) AND a `runnerSource` that wraps it in `createSystem` + `start()` + dispatch + settle + log so the playground boots a project that actually demonstrates behavior. Pipe BOTH into `playground_link` as a `files` array for a clickable runnable URL. Never writes to disk \u2014 the caller decides. Strict regex on `name` (kebab-case, \u226464 chars). For `kind: "module"`, optionally pass `sections` to pick which blocks to include. Discover valid section values via list_module_sections.',inputSchema:{name:z$1.string().min(1).max(64).describe("Kebab-case identifier (e.g. 'traffic-light'). Must start with a lowercase letter and contain only lowercase letters, digits, and hyphens."),kind:z$1.enum(["module","orchestrator"]).default("module").describe("What to generate. 'module' for a plain Directive module; 'orchestrator' for an AI agent orchestrator module with memory + guardrails scaffolding."),sections:z$1.array(z$1.enum(MODULE_SECTIONS)).optional().describe("Which module sections to include. Defaults to every section. Only honored when kind === 'module'. Discover valid values via list_module_sections.")}},async({name:t,kind:r,sections:n})=>{let o=validateModuleName(t);if(o!==true)return {isError:true,content:[{type:"text",text:`Invalid name '${t}': ${o}`}]};try{let a=r==="orchestrator"?generateOrchestrator(t):generateModule(t,n??MODULE_SECTIONS),{testFileName:i}=suggestFileNames(t,r),s=requiredPackages(r),u={moduleSource:a.moduleSource,runnerSource:a.runnerSource,suggestedFilenames:{module:`src/${a.suggestedFilenames.module}`,runner:`src/${a.suggestedFilenames.runner}`,test:`src/${i}`},runnable:a.runnable,requiredPackages:s,installCommand:`pnpm add ${s.join(" ")}`,nextStep:"Pipe `moduleSource` AND `runnerSource` into `playground_link` as a `files` array to give the user a runnable URL."};return {content:[{type:"text",text:`<directive-data>
20
+ `)}`}]})),e.registerTool("generate_module",{title:"Generate NEW Directive module source code (paired with a runnable driver)",description:'Generate a new Directive module or AI orchestrator as a paired source bundle: a library `moduleSource` (the `createModule(...)` definition) AND a `runnerSource` that wraps it in `createSystem` + `start()` + dispatch + settle + log so the playground boots a project that actually demonstrates behavior. Pipe BOTH into `playground_link` as a `files` array for a clickable runnable URL. Never writes to disk \u2014 the caller decides. Strict regex on `name` (kebab-case, \u226464 chars). For `kind: "module"`, optionally pass `sections` to pick which blocks to include. Discover valid section values via list_module_sections.',inputSchema:{name:z.string().min(1).max(64).describe("Kebab-case identifier (e.g. 'traffic-light'). Must start with a lowercase letter and contain only lowercase letters, digits, and hyphens."),kind:z.enum(["module","orchestrator"]).default("module").describe("What to generate. 'module' for a plain Directive module; 'orchestrator' for an AI agent orchestrator module with memory + guardrails scaffolding."),sections:z.array(z.enum(MODULE_SECTIONS)).optional().describe("Which module sections to include. Defaults to every section. Only honored when kind === 'module'. Discover valid values via list_module_sections.")}},async({name:t,kind:r,sections:n})=>{let i=validateModuleName(t);if(i!==true)return {isError:true,content:[{type:"text",text:`Invalid name '${t}': ${i}`}]};try{let a=r==="orchestrator"?generateOrchestrator(t):generateModule(t,n??MODULE_SECTIONS),{testFileName:o}=suggestFileNames(t,r),s=requiredPackages(r),u={moduleSource:a.moduleSource,runnerSource:a.runnerSource,suggestedFilenames:{module:`src/${a.suggestedFilenames.module}`,runner:`src/${a.suggestedFilenames.runner}`,test:`src/${o}`},runnable:a.runnable,requiredPackages:s,installCommand:`pnpm add ${s.join(" ")}`,nextStep:"Pipe `moduleSource` AND `runnerSource` into `playground_link` as a `files` array to give the user a runnable URL."};return {content:[{type:"text",text:`<directive-data>
21
21
  ${JSON.stringify(u,null,2)}
22
22
  </directive-data>`}]}}catch(a){return {isError:true,content:[{type:"text",text:a.message}]}}}),e.registerTool("list_review_rules",{title:"List Directive code-review rules",description:"Enumerate every anti-pattern Directive code can violate, parsed from @directive-run/knowledge. Each entry carries an id, severity, category, title, badExample, goodExample, and explanation. Use this to discover rule ids before calling get_review_rule or before passing ruleFilter to review_source. Returns existing reference material; does NOT generate code.",inputSchema:{}},async()=>{let t=getAntiPatterns(),r=t.map(n=>({id:n.id,severity:n.severity,category:n.category,title:n.title}));return {content:[{type:"text",text:`<directive-data>
23
23
  ${t.length} review rules:
24
24
  ${JSON.stringify(r,null,2)}
25
- </directive-data>`}]}}),e.registerTool("get_review_rule",{title:"Get a Directive code-review rule",description:"Fetch one anti-pattern's full detail: title, severity, category, explanation, and the WRONG/CORRECT code-example pair. Use list_review_rules first to discover valid ids. Returns existing reference material; does NOT generate code.",inputSchema:{id:z$1.string().min(1).max(128).describe("Rule id (a kebab-case slug \u2014 e.g. 'flat-schema-missing-facts-wrapper'). Call list_review_rules first to discover valid ids.")}},async({id:t})=>{let r=getAntiPatternById(t);if(!r)return {isError:true,content:[{type:"text",text:`Rule not found: '${t}'. Call list_review_rules to see available ids.`}]};let n=[`# ${r.title}`,`**id:** ${r.id}`,`**severity:** ${r.severity}`,`**category:** ${r.category}`];return r.explanation&&n.push("",r.explanation),r.badExample&&n.push("","## Wrong","```typescript",r.badExample,"```"),r.goodExample&&n.push("","## Correct","```typescript",r.goodExample,"```"),{content:[{type:"text",text:`<directive-data>
25
+ </directive-data>`}]}}),e.registerTool("get_review_rule",{title:"Get a Directive code-review rule",description:"Fetch one anti-pattern's full detail: title, severity, category, explanation, and the WRONG/CORRECT code-example pair. Use list_review_rules first to discover valid ids. Returns existing reference material; does NOT generate code.",inputSchema:{id:z.string().min(1).max(128).describe("Rule id (a kebab-case slug \u2014 e.g. 'flat-schema-missing-facts-wrapper'). Call list_review_rules first to discover valid ids.")}},async({id:t})=>{let r=getAntiPatternById(t);if(!r)return {isError:true,content:[{type:"text",text:`Rule not found: '${t}'. Call list_review_rules to see available ids.`}]};let n=[`# ${r.title}`,`**id:** ${r.id}`,`**severity:** ${r.severity}`,`**category:** ${r.category}`];return r.explanation&&n.push("",r.explanation),r.badExample&&n.push("","## Wrong","```typescript",r.badExample,"```"),r.goodExample&&n.push("","## Correct","```typescript",r.goodExample,"```"),{content:[{type:"text",text:`<directive-data>
26
26
  ${n.join(`
27
27
  `)}
28
28
  </directive-data>`}]}}),e.registerTool("list_migration_sources",{title:"List supported migration source libraries",description:"Enumerate the source libraries get_migration_pattern accepts: redux, zustand, xstate, mobx, jotai, recoil. Call this before get_migration_pattern so the source list comes from the server (no hallucination risk). Returns existing reference material; does NOT generate code.",inputSchema:{}},async()=>({content:[{type:"text",text:`${MIGRATION_SOURCES.length} sources:
29
29
  ${MIGRATION_SOURCES.join(`
30
- `)}`}]})),e.registerTool("get_migration_pattern",{title:"Get migration pattern from a state-management library",description:"Fetch the concept-mapping table + step list + before/after exemplars for migrating from a popular state-management library to Directive. Use this when a user asks 'how do I migrate from Redux / Zustand / XState / MobX / Jotai / Recoil'. Returns existing reference material; does NOT generate code.",inputSchema:{source:z$1.enum(MIGRATION_SOURCES).describe("Source library. Discover valid values via list_migration_sources.")}},async({source:t})=>{let r=getMigrationPattern(t);return r?{content:[{type:"text",text:`<directive-data>
31
- ${[`# Migrating from ${r.name} to Directive`,"","## Concept map","","| From | To | Note |","|---|---|---|",...r.conceptMap.map(o=>`| ${o.from} | ${o.to} | ${o.note} |`),"","## Steps",...r.steps.map((o,a)=>`${a+1}. ${o}`),"","## Before","```typescript",r.before,"```","","## After","```typescript",r.after,"```"].join(`
30
+ `)}`}]})),e.registerTool("get_migration_pattern",{title:"Get migration pattern from a state-management library",description:"Fetch the concept-mapping table + step list + before/after exemplars for migrating from a popular state-management library to Directive. Use this when a user asks 'how do I migrate from Redux / Zustand / XState / MobX / Jotai / Recoil'. Returns existing reference material; does NOT generate code.",inputSchema:{source:z.enum(MIGRATION_SOURCES).describe("Source library. Discover valid values via list_migration_sources.")}},async({source:t})=>{let r=getMigrationPattern(t);return r?{content:[{type:"text",text:`<directive-data>
31
+ ${[`# Migrating from ${r.name} to Directive`,"","## Concept map","","| From | To | Note |","|---|---|---|",...r.conceptMap.map(i=>`| ${i.from} | ${i.to} | ${i.note} |`),"","## Steps",...r.steps.map((i,a)=>`${a+1}. ${i}`),"","## Before","```typescript",r.before,"```","","## After","```typescript",r.after,"```"].join(`
32
32
  `)}
33
- </directive-data>`}]}:{isError:true,content:[{type:"text",text:`Migration pattern not found: '${t}'. Call list_migration_sources to see valid values.`}]}}),e.registerTool("review_source",{title:"Review Directive code with ts-morph rules",description:"Run the @directive-run/lint rule registry against a TypeScript source string. Returns structured findings (line, column, severity, message, fixable) for every match. Use this when the user asks 'review this Directive code' or 'lint this'. Source is parsed in a worker thread with a 5-second budget and 200 KB cap.",inputSchema:{source:z$1.string().min(1).max(2e5).describe("TypeScript source to review. Max 200,000 bytes; longer inputs are rejected pre-parse."),fileName:z$1.string().regex(/^[\w./-]{1,128}$/).optional().describe("Optional file name shown in findings. Must match /^[\\w./-]{1,128}$/."),ruleFilter:z$1.array(z$1.string().max(64)).max(32).optional().describe("Optional whitelist of rule ids to run. Discover valid ids via list_review_rules.")}},async({source:t,fileName:r,ruleFilter:n})=>{try{let o=await Q({source:t,fileName:r,ruleFilter:n});return {content:[{type:"text",text:`<directive-data>
34
- ${JSON.stringify(o,null,2)}
35
- </directive-data>`}]}}catch(o){return {isError:true,content:[{type:"text",text:`review_source failed \u2014 ${o instanceof S?`${o.code}: ${o.message}`:o.message}`}]}}}),e.registerTool("fix_code",{title:"Apply a mechanical fix for a Directive review finding",description:"Given a source string and a Finding returned by review_source, run the rule's mechanical fix and return { ok, diff, fixedSource, explanation } \u2014 or { ok: false, reason } when the rule has no fix. Useful for closing the loop: review_source \u2192 user picks \u2192 fix_code. The fixed source is NOT written to disk \u2014 the caller decides.",inputSchema:{source:z$1.string().min(1).max(2e5).describe("The same source you passed to review_source."),finding:z$1.object({ruleId:z$1.string().min(1).max(64),severity:z$1.enum(["error","warning","info"]),line:z$1.number().int().nonnegative(),column:z$1.number().int().nonnegative(),message:z$1.string(),findingId:z$1.string(),suggestion:z$1.string().optional()}).describe("The Finding returned by review_source. Pass the WHOLE object \u2014 the worker uses ruleId + line + column to locate the AST node.")}},async({source:t,finding:r})=>{try{let n=await ee({source:t,finding:r});return {content:[{type:"text",text:`<directive-data>
33
+ </directive-data>`}]}:{isError:true,content:[{type:"text",text:`Migration pattern not found: '${t}'. Call list_migration_sources to see valid values.`}]}}),e.registerTool("review_source",{title:"Review Directive code with ts-morph rules",description:"Run the @directive-run/lint rule registry against a TypeScript source string. Returns structured findings (line, column, severity, message, fixable) for every match. Use this when the user asks 'review this Directive code' or 'lint this'. Source is parsed in a worker thread with a 5-second budget and 200 KB cap.",inputSchema:{source:z.string().min(1).max(2e5).describe("TypeScript source to review. Max 200,000 bytes; longer inputs are rejected pre-parse."),fileName:z.string().regex(/^[\w./-]{1,128}$/).optional().describe("Optional file name shown in findings. Must match /^[\\w./-]{1,128}$/."),ruleFilter:z.array(z.string().max(64)).max(32).optional().describe("Optional whitelist of rule ids to run. Discover valid ids via list_review_rules.")}},async({source:t,fileName:r,ruleFilter:n})=>{try{let i=await re({source:t,fileName:r,ruleFilter:n});return {content:[{type:"text",text:`<directive-data>
34
+ ${JSON.stringify(i,null,2)}
35
+ </directive-data>`}]}}catch(i){return {isError:true,content:[{type:"text",text:`review_source failed \u2014 ${i instanceof S?`${i.code}: ${i.message}`:i.message}`}]}}}),e.registerTool("fix_code",{title:"Apply a mechanical fix for a Directive review finding",description:"Given a source string and a Finding returned by review_source, run the rule's mechanical fix and return { ok, diff, fixedSource, explanation } \u2014 or { ok: false, reason } when the rule has no fix. Useful for closing the loop: review_source \u2192 user picks \u2192 fix_code. The fixed source is NOT written to disk \u2014 the caller decides.",inputSchema:{source:z.string().min(1).max(2e5).describe("The same source you passed to review_source."),finding:z.object({ruleId:z.string().min(1).max(64),severity:z.enum(["error","warning","info"]),line:z.number().int().nonnegative(),column:z.number().int().nonnegative(),message:z.string(),findingId:z.string(),suggestion:z.string().optional()}).describe("The Finding returned by review_source. Pass the WHOLE object \u2014 the worker uses ruleId + line + column to locate the AST node.")}},async({source:t,finding:r})=>{try{let n=await ne({source:t,finding:r});return {content:[{type:"text",text:`<directive-data>
36
36
  ${JSON.stringify(n,null,2)}
37
37
  </directive-data>`}]}}catch(n){return {isError:true,content:[{type:"text",text:`fix_code failed \u2014 ${n instanceof S?`${n.code}: ${n.message}`:n.message}`}]}}}),e.registerTool("list_skills",{title:"List Directive Claude Code skills",description:"List every skill bundled in @directive-run/claude-plugin. Each skill is a gerund-named bundle of one SKILL.md plus supporting knowledge files. Pass a returned name to get_skill.",inputSchema:{}},async()=>{let t=getAllSkills(),r=Array.from(t.keys()).sort();return {content:[{type:"text",text:`${r.length} skills:
38
38
  ${r.join(`
39
- `)}`}]}}),e.registerTool("get_skill",{title:"Get a Directive Claude Code skill",description:"Fetch one skill bundle: the SKILL.md manifest plus every supporting knowledge file concatenated into a single document. Use list_skills to discover names.",inputSchema:{name:z$1.string().min(1).describe("The skill name (e.g. 'building-ai-orchestrators', 'writing-directive-constraints').")}},async({name:t})=>{let r=getSkill(t);if(!r)return {isError:true,content:[{type:"text",text:`Skill not found: '${t}'. Call list_skills to see available names.`}]};let n=[`# Skill: ${r.name}
39
+ `)}`}]}}),e.registerTool("get_skill",{title:"Get a Directive Claude Code skill",description:"Fetch one skill bundle: the SKILL.md manifest plus every supporting knowledge file concatenated into a single document. Use list_skills to discover names.",inputSchema:{name:z.string().min(1).describe("The skill name (e.g. 'building-ai-orchestrators', 'writing-directive-constraints').")}},async({name:t})=>{let r=getSkill(t);if(!r)return {isError:true,content:[{type:"text",text:`Skill not found: '${t}'. Call list_skills to see available names.`}]};let n=[`# Skill: ${r.name}
40
40
 
41
- ${r.manifest}`];for(let[o,a]of r.files)n.push(`---
41
+ ${r.manifest}`];for(let[i,a]of r.files)n.push(`---
42
42
 
43
- ## ${o}.md
43
+ ## ${i}.md
44
44
 
45
45
  ${a}`);return {content:[{type:"text",text:n.join(`
46
46
 
47
- `)}]}}),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:z$1.string().min(1).max(R).optional().describe(`Single-file source (mutually exclusive with \`files\`). Use for already-runnable code from \`get_example\` / \`fix_code\`. Max ${R} bytes.`),files:z$1.array(z$1.object({path:z$1.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:z$1.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 ${R} bytes.`),title:z$1.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:z$1.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:o})=>{try{let a=ae({source:t,files:r,title:n,mode:o}),i={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>
48
- ${JSON.stringify(i,null,2)}
49
- </directive-data>`}]}}catch(a){return {isError:true,content:[{type:"text",text:`playground_link failed \u2014 ${a instanceof _?`${a.code}: ${a.message}`:a.message}`}]}}}),e}var fe="/messages",he="/sse",ut="/healthz",pt=1e6,gt=64,mt=300*1e3,ft=3e4,ht=new Set(["127.0.0.1","localhost","::1","0:0:0:0:0:0:0:1"]),H=class extends Error{};function vt(e){return ht.has(e.toLowerCase())}function yt(e){let t=e.port??3e3,r=e.host??"127.0.0.1",n=e.logger??console,o=e.token??process.env.DIRECTIVE_MCP_TOKEN??void 0;if(!vt(r)&&!o)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:o,allowOrigins:e.allowOrigins??[],bodyLimitBytes:e.bodyLimitBytes??pt,maxSessions:e.maxSessions??gt,idleTimeoutMs:e.idleTimeoutMs??mt}}function ve(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 ye(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 z(e,t){C({transport:"sse",authEnabled:t,sessionCount:e.size});}var G=0;async function wt(e,t,r,n){if(!ve(e,n.token)){E(t,401,"unauthorized");return}if(!ye(e,n.allowOrigins)){E(t,403,"origin not allowed");return}if(r.size+G>=n.maxSessions){E(t,429,"session cap reached",{"Retry-After":"60"});return}G+=1;let o=false;try{let a=new SSEServerTransport(fe,t),i=L();r.set(a.sessionId,{transport:a,lastActivity:Date.now()}),o=!0,z(r,!!n.token);let s=()=>{r.delete(a.sessionId),z(r,!!n.token);};t.on("close",s),a.onclose=s,await i.connect(a),n.logger.log(`[directive-mcp] sse session opened: ${a.sessionId}`);}finally{G-=1;}}async function kt(e,t,r,n,o){if(!ve(e,o.token)){E(t,401,"unauthorized");return}if(!ye(e,o.allowOrigins)){E(t,403,"origin not allowed");return}let a=Number(e.headers["content-length"]??"0");if(Number.isFinite(a)&&a>o.bodyLimitBytes){E(t,413,`body exceeds ${o.bodyLimitBytes} bytes`);return}let i=r.searchParams.get("sessionId");if(!i){E(t,400,"missing sessionId query parameter");return}let s=n.get(i);if(!s){E(t,404,`unknown session: ${i}`);return}s.lastActivity=Date.now();let u=0,d=false;e.on("data",p=>{u+=Buffer.byteLength(p),u>o.bodyLimitBytes&&!d&&(d=true,E(t,413,`body exceeds ${o.bodyLimitBytes} bytes`),e.destroy());}),!d&&await s.transport.handlePostMessage(e,t);}async function xt(e,t,r,n){let o=new URL(e.url??"/",`http://${e.headers.host??n.host}`);if(e.method==="GET"&&o.pathname===ut){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}if(e.method==="GET"&&o.pathname===he){await wt(e,t,r,n);return}if(e.method==="POST"&&o.pathname===fe){await kt(e,t,o,r,n);return}E(t,404,"not found");}function bt(e,t){return setInterval(()=>{let r=Date.now();for(let[n,o]of e)r-o.lastActivity>t.idleTimeoutMs&&(e.delete(n),o.transport.close().catch(()=>{}),z(e,!!t.token),t.logger.log(`[directive-mcp] pruned idle session: ${n}`));},ft).unref()}async function we(e={}){let t=yt(e),r=new Map,n=createServer(async(a,i)=>{try{await xt(a,i,r,t);}catch(s){t.logger.error("[directive-mcp] request error:",s),i.headersSent||i.writeHead(500,{"Content-Type":"text/plain"}),i.end("internal server error");}}),o=bt(r,t);return n.on("close",()=>{clearInterval(o);}),await new Promise(a=>{n.listen(t.port,t.host,()=>{t.logger.log(`[directive-mcp] sse server listening at http://${t.host}:${t.port}${he}${t.token?" (auth: bearer-token)":" (auth: none, loopback only)"}`),a();});}),n}var _t="0.4.0",ke=`directive-mcp \u2014 MCP server exposing Directive to AI clients
47
+ `)}]}}),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: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:z.array(z.object({path: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: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: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: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=G({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>
48
+ ${JSON.stringify(o,null,2)}
49
+ </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:z.string().min(1).max(D).optional().describe(`Single-file source (mutually exclusive with \`files\`). Use for already-runnable code. Max ${D} bytes.`),files:z.array(z.object({path: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: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: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 ue({source:t,files:r,timeoutMs:n}),a=null;try{a=G({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>
50
+ ${JSON.stringify(o,null,2)}
51
+ </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 we="/messages",be="/sse",yt="/healthz",wt=1e6,bt=64,xt=300*1e3,kt=3e4,St=new Set(["127.0.0.1","localhost","::1","0:0:0:0:0:0:0:1"]),W=class extends Error{};function _t(e){return St.has(e.toLowerCase())}function Tt(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(!_t(r)&&!i)throw new W("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??wt,maxSessions:e.maxSessions??bt,idleTimeoutMs:e.idleTimeoutMs??xt}}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 ke(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 Y(e,t){L({transport:"sse",authEnabled:t,sessionCount:e.size});}var K=0;async function Et(e,t,r,n){if(!xe(e,n.token)){E(t,401,"unauthorized");return}if(!ke(e,n.allowOrigins)){E(t,403,"origin not allowed");return}if(r.size+K>=n.maxSessions){E(t,429,"session cap reached",{"Retry-After":"60"});return}K+=1;let i=false;try{let a=new SSEServerTransport(we,t),o=U();r.set(a.sessionId,{transport:a,lastActivity:Date.now()}),i=!0,Y(r,!!n.token);let s=()=>{r.delete(a.sessionId),Y(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{K-=1;}}async function Dt(e,t,r,n,i){if(!xe(e,i.token)){E(t,401,"unauthorized");return}if(!ke(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 Rt(e,t,r,n){let i=new URL(e.url??"/",`http://${e.headers.host??n.host}`);if(e.method==="GET"&&i.pathname===yt){t.writeHead(200,{"Content-Type":"text/plain"}),t.end("ok");return}if(e.method==="GET"&&i.pathname===be){await Et(e,t,r,n);return}if(e.method==="POST"&&i.pathname===we){await Dt(e,t,i,r,n);return}E(t,404,"not found");}function $t(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(()=>{}),Y(e,!!t.token),t.logger.log(`[directive-mcp] pruned idle session: ${n}`));},kt).unref()}async function Se(e={}){let t=Tt(e),r=new Map,n=createServer(async(a,o)=>{try{await Rt(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=$t(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}${be}${t.token?" (auth: bearer-token)":" (auth: none, loopback only)"}`),a();});}),n}var At="0.5.1",_e=`directive-mcp \u2014 MCP server exposing Directive to AI clients
50
52
 
51
53
  Usage:
52
54
  directive-mcp Run stdio transport (default)
@@ -67,9 +69,9 @@ Options:
67
69
  --version, -v Show package version
68
70
 
69
71
  Docs: https://directive.run/docs/ide-integration
70
- `;function M(e,t,r){let n=e[t];if(!n)throw new Error(`${r} requires a value`);return n}function Tt(e){let t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`invalid --port: ${e}`);return t}function Et(e){let t={sse:false,port:3e3,host:"127.0.0.1",help:false,version:false,allowOrigins:[]};for(let r=0;r<e.length;r++){let n=e[r];switch(n){case "--sse":t.sse=true;break;case "--port":t.port=Tt(M(e,++r,"--port"));break;case "--host":t.host=M(e,++r,"--host");break;case "--token":t.token=M(e,++r,"--token");break;case "--allow-origin":t.allowOrigins.push(M(e,++r,"--allow-origin"));break;case "--help":case "-h":t.help=true;break;case "--version":case "-v":t.version=true;break;default:throw new Error(`unknown argument: ${n}`)}}return t}async function Dt(){let e;try{e=Et(process.argv.slice(2));}catch(n){process.stderr.write(`${n.message}
72
+ `;function B(e,t,r){let n=e[t];if(!n)throw new Error(`${r} requires a value`);return n}function Pt(e){let t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error(`invalid --port: ${e}`);return t}function Ot(e){let t={sse:false,port:3e3,host:"127.0.0.1",help:false,version:false,allowOrigins:[]};for(let r=0;r<e.length;r++){let n=e[r];switch(n){case "--sse":t.sse=true;break;case "--port":t.port=Pt(B(e,++r,"--port"));break;case "--host":t.host=B(e,++r,"--host");break;case "--token":t.token=B(e,++r,"--token");break;case "--allow-origin":t.allowOrigins.push(B(e,++r,"--allow-origin"));break;case "--help":case "-h":t.help=true;break;case "--version":case "-v":t.version=true;break;default:throw new Error(`unknown argument: ${n}`)}}return t}async function Mt(){let e;try{e=Ot(process.argv.slice(2));}catch(n){process.stderr.write(`${n.message}
71
73
 
72
- ${ke}`),process.exit(2);}if(e.help){process.stdout.write(ke);return}if(e.version){process.stdout.write(`${_t}
73
- `);return}if(e.sse){let n=await we({port:e.port,host:e.host,token:e.token,allowOrigins:e.allowOrigins}),o=()=>{n.close(()=>process.exit(0));};process.on("SIGINT",o),process.on("SIGTERM",o);return}C({transport:"stdio",authEnabled:false});let t=L(),r=new StdioServerTransport;await t.connect(r);}Dt().catch(e=>{process.stderr.write(`[directive-mcp] fatal: ${e.stack??String(e)}
74
+ ${_e}`),process.exit(2);}if(e.help){process.stdout.write(_e);return}if(e.version){process.stdout.write(`${At}
75
+ `);return}if(e.sse){let n=await Se({port:e.port,host:e.host,token:e.token,allowOrigins:e.allowOrigins}),i=()=>{n.close(()=>process.exit(0));};process.on("SIGINT",i),process.on("SIGTERM",i);return}L({transport:"stdio",authEnabled:false});let t=U(),r=new StdioServerTransport;await t.connect(r);}Mt().catch(e=>{process.stderr.write(`[directive-mcp] fatal: ${e.stack??String(e)}
74
76
  `),process.exit(1);});//# sourceMappingURL=cli.js.map
75
77
  //# sourceMappingURL=cli.js.map