@mcp-use/cli 4.0.0-beta.8 → 4.0.0

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.
@@ -1,2 +1,2 @@
1
- import{a as Y,b as Q}from"../chunk-N7BU45K6.js";import{b as te}from"../chunk-OVFUQAEG.js";import{b as z,c as K}from"../chunk-USIKTT3N.js";import{a as ne,b as re,c as oe,d as T,f as x,g as se,i as ie}from"../chunk-ALPMVGHI.js";import{b as Z,c as ee,d as A}from"../chunk-7G4TXPP4.js";import{a as L,b as X}from"../chunk-DB3E6LBX.js";import{spawn as je}from"child_process";import{createServer as ke}from"http";import{networkInterfaces as Ce}from"os";import{join as $e,resolve as Ee}from"path";import Le from"@tailwindcss/vite";import Ae from"@vitejs/plugin-react";import{createServer as Te,createServerModuleRunner as xe}from"vite";import{InMemoryServerEventBus as Ve,localhostAllowedHostnames as Fe,localhostAllowedOrigins as Be,validateHostHeader as Ne,validateOriginHeader as We}from"@modelcontextprotocol/server";import{connect as Re,createServer as be}from"net";var ae=100,Me=300,Ie=new Set(["127.0.0.1","localhost","::1"]);function Se(e,r){return new Promise(o=>{let n=be();n.unref(),n.once("error",()=>o(!1)),n.listen({port:e,host:r},()=>{n.close(()=>o(!0))})})}function ce(e,r){return new Promise(o=>{let n=Re({port:e,host:r});n.setTimeout(Me),n.once("connect",()=>{n.destroy(),o(!0)}),n.once("timeout",()=>{n.destroy(),o(!1)}),n.once("error",()=>{n.destroy(),o(!1)})})}async function _e(e){return await ce(e,"127.0.0.1")||await ce(e,"::1")}async function le(e,r){for(let o=e;o<e+ae;o++)if(await Se(o,r)&&!(Ie.has(r)&&await _e(o)))return{port:o,requested:e};throw new Error(`No free port found between ${e} and ${e+ae-1} on ${r}.`)}function de(e,r){let o=()=>{let n=e.getBasePath(),{url:c}=e.tunnel.status();return{mcpUrl:c!==null?`${c.replace(/\/+$/,"")}${n}`:null,port:e.port,fromCli:!0,tunnelUrl:c}};return async n=>{let c=e.getBasePath(),l=`${c}/inspector/api/dev/info`,d=`${c}/inspector/api/dev/start-tunnel`,u=`${c}/inspector/api/dev/stop-tunnel`,w=new URL(n.url).pathname;if(n.method==="GET"&&w===l)return Response.json(o());if(n.method==="POST"&&w===d)try{return await e.tunnel.start(e.port),Response.json({ok:!0,restarting:!1})}catch(g){let _=g instanceof Error?g.message:"Failed to start tunnel";return Response.json({error:_},{status:500})}return n.method==="POST"&&w===u?(await e.tunnel.stop(),Response.json({ok:!0})):r(n)}}import{readFileSync as He}from"fs";import{createRequire as De}from"module";import{join as Oe}from"path";import{pathToFileURL as Ue}from"url";async function fe(e){let r=Oe(e,"package.json"),o=JSON.parse(He(r,"utf8"));if([o.dependencies,o.devDependencies,o.optionalDependencies].some(l=>l!==null&&typeof l=="object"&&"@mcp-use/inspector"in l)){let l=De(r);try{let d=l.resolve("@mcp-use/inspector");return ue(await import(Ue(d).href))}catch(d){if(!pe(d))throw d}}try{return ue(await import("@mcp-use/inspector"))}catch(l){if(pe(l))return{installed:!1};throw l}}function ue(e){if(typeof e.mountInspector!="function")throw new Error("The installed @mcp-use/inspector is incompatible: its package entry does not export mountInspector(). Update the development dependency.");return{installed:!0,module:e}}function pe(e){let r=e!==null&&typeof e=="object"&&"code"in e?String(e.code):void 0;return r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND"}function Ge(e){let[r,o]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["cmd",["/c","start","",e]]:["xdg-open",[e]];try{let n=je(r,o,{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}function qe(){for(let e of Object.values(Ce()))for(let r of e??[])if(!r.internal&&r.family==="IPv4")return r.address}function Je(e){if(e!==void 0)try{return new URL(`http://${e}`).hostname.replace(/^\[|\]$/g,"")}catch{return}}function ze(e){let r=e.getHeader("Vary"),o=typeof r=="string"?r:Array.isArray(r)?r.join(", "):r!==void 0?String(r):"";o.split(",").map(n=>n.trim().toLowerCase()).includes("origin")||e.setHeader("Vary",o===""?"Origin":`${o}, Origin`)}function Ke(e,r,o){if(o.tunnelActive){r.setHeader("Access-Control-Allow-Origin","*");return}if(!o.localhostBind)return;let n=e.headers.origin;if(n==="null"){r.setHeader("Access-Control-Allow-Origin","null");return}if(typeof n!="string"||n==="")return;let c=We(n,Be());!c.ok||c.origin===void 0||(r.setHeader("Access-Control-Allow-Origin",c.origin),ze(r))}function Xe(e){let r=e.default;if(r===null||typeof r!="object")throw new Error("The server entry must default-export the MCPServer instance (`export default server`) and never call listen() itself \u2014 `mcp-use dev` owns the socket.");let o=r;if(typeof o.fetch!="function")throw new Error("The entry's default export has no fetch() \u2014 it must be the MCPServer instance (`export default server`).");return o}async function Ye(e){process.env.MCP_USE_DEV_CLI="1";let r=oe(e.cwd),o=new Ve(t=>{console.error("[mcp-use] notification delivery failed:",t)});ee(e.cwd,"development");let n=K(e.host),c=["127.0.0.1","localhost","::1"].includes(n),l=n==="0.0.0.0"||n==="::",d=ke(),{port:u,requested:w}=await le(z(e.port),n);u!==w&&console.log(`[mcp-use] port ${w} is taken, using ${u}`),process.env.PORT=String(u);let g=process.env.MCP_URL===void 0&&(n==="127.0.0.1"||n==="localhost"||n==="::1")?`http://localhost:${u}`:void 0,_=e.mcpDir===void 0?e.cwd:Ee(e.cwd,e.mcpDir),V=e.entry===void 0?L(_):L(e.cwd,e.entry),H=await X(e.cwd,V);(H==="created"||H==="updated")&&console.log(`[mcp-use] ${H} mcp-env.d.ts`);let I=e.viewsDir??(e.mcpDir===void 0?void 0:$e(e.mcpDir,"views")),p=T(e.cwd,I),P=p.length>0,me=ne(e.cwd),D=["127.0.0.1","localhost","0.0.0.0","::","::1"].includes(n)?"localhost":n,y=`http://${D.includes(":")?`[${D}]`:D}:${u}`,f=await Te({root:e.cwd,configFile:P?me:!1,envDir:!1,logLevel:"warn",cacheDir:r.cache,resolve:{tsconfigPaths:!0,alias:{tailwindcss:re()}},plugins:P?[A(e.cwd),Le(),ie({getViews:()=>p,dev:{reactRefresh:!0}}),Ae()]:[A(e.cwd)],server:{middlewareMode:!0,...P&&{origin:y},cors:!1,hmr:P?{server:d}:!1},ssr:{...Z(e.cwd)}}),O=f.environments.ssr,R=xe(O,{hmr:!1,sourcemapInterceptor:"node"}),F=async()=>{let t=async()=>{let i=await R.import(V),a=Xe(i);if(p.length>0){let v=se(p);if(typeof a.__primeViews!="function")throw new Error("Loaded MCPServer instance does not support __primeViews.");a.__primeViews(v,{dev:!0,projectRoot:e.cwd})}return a};if(g===void 0)return t();let s=process.env.MCP_URL;try{return process.env.MCP_URL=g,await t()}finally{s===void 0?delete process.env.MCP_URL:process.env.MCP_URL=s}},U,m;try{let t=await F();t.__setEventBus(o),t.__mount(),U=async s=>t.fetch(s),m=t.basePath??"/mcp"}catch(t){throw await R.close(),await f.close(),t}let j,b,B,N=t=>{if(j===void 0||B===t)return;let s=j.mountInspector({basePath:t,autoConnectUrl:`${y}${t}`,oauthProxyAllowLoopback:c||l,devMode:!0,manufactChatUrl:process.env.MANUFACT_CHAT_URL});if(typeof s!="function")throw new Error("The installed @mcp-use/inspector is incompatible: mountInspector() did not return a Fetch handler.");b=s,B=t};try{if(e.inspector!==!1){let t=await fe(e.cwd);t.installed&&(j=t.module,N(m))}}catch(t){throw await R.close(),await f.close(),t}let k=!1,C=!1,W=()=>{if(k){C=!0;return}k=!0,(async()=>{do{C=!1;try{R.evaluatedModules.clear();let t=await F();t.__setEventBus(o),t.__mount();let s=async a=>t.fetch(a),i=t.basePath??"/mcp";N(i),U=s,m=i,o.publish({kind:"tools_list_changed"}),o.publish({kind:"prompts_list_changed"}),o.publish({kind:"resources_list_changed"}),console.log("[mcp-use] reloaded server entry")}catch(t){console.error(`[mcp-use] reload failed \u2014 keeping the previous server:
2
- `,t)}}while(C);k=!1})()},$=t=>{if(x(t,e.cwd,I))return;let s=O.moduleGraph.getModulesByFile(t);if(!(s===void 0||s.size===0)){for(let i of s)O.moduleGraph.invalidateModule(i);W()}},ve=t=>{if(!x(t,e.cwd,I))return;let s=p;p=T(e.cwd,I),(s.length!==p.length||s.some((a,v)=>a.name!==p[v]?.name||a.entryPath!==p[v]?.entryPath))&&W()},S=t=>{ve(t),$(t)};f.watcher.on("change",$),f.watcher.on("add",S),f.watcher.on("unlink",S);let h=te(r.tunnel);d.prependListener("upgrade",t=>{let s=h.status().url;if(s===null)return;let i=new URL(s).hostname;t.headers.host?.split(":")[0]===i&&(t.headers.host=`localhost:${u}`)});let he=(t,s)=>{let i=h.status().url,a=i!==null?new URL(i).hostname:null,v=a!==null?[a]:[],M=Ne(t.headers.host,[...Fe(),...v]);return M.ok?!1:(s.writeHead(403,{"content-type":"application/json"}),s.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:M.message},id:null})),!0)},G=async()=>{f.watcher.off("change",$),f.watcher.off("add",S),f.watcher.off("unlink",S),await h.stop(),await new Promise(t=>d.close(()=>t())),await R.close(),await f.close()},we=de({getBasePath:()=>m,port:u,tunnel:h},t=>b!==void 0&&Y(t,m)?b(t):U(t)),{toNodeHandler:ge}=await import("../node-bridge-JJIA6K5P.js"),q=ge({fetch:we}),Pe=(t,s)=>{if(c&&he(t,s))return;let i=t.url??"/",a=new URL(i,"http://127.0.0.1").pathname,v=h.status().url,M=v===null?null:new URL(v).hostname,E=Je(t.headers.host);if((M!==null&&E===M||l&&E!==void 0&&!["localhost","127.0.0.1","::1"].includes(E))&&Q(a,m)){s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end("Not Found");return}let J=P&&p.length>0,ye=t.method==="GET"&&(a.startsWith("/@")||a.startsWith("/node_modules/")||a.startsWith("/.mcp-use/")||J&&a.startsWith("/views/"));J&&ye?(Ke(t,s,{tunnelActive:h.status().url!==null,localhostBind:c}),f.middlewares(t,s,()=>{q(t,s)})):q(t,s)};if(d.on("request",Pe),await new Promise((t,s)=>{d.once("error",s),d.listen(u,n,()=>t())}),console.log("[mcp-use] dev server ready"),p.length>0&&console.log(` \u279C Views: ${p.map(t=>t.name).join(", ")}`),console.log(` \u279C MCP endpoint: ${y}${m}`),b!==void 0?console.log(` \u279C Inspector: ${y}${m}/inspector`):e.inspector!==!1&&console.warn("[mcp-use] Built-in Inspector is unavailable; reinstall mcp-use to restore visual testing."),n==="0.0.0.0"||n==="::"){let t=qe();t!==void 0&&console.log(` \u279C Network: http://${t}:${u}${m}`)}if(c||console.warn(`[mcp-use] --host ${n} serves beyond this machine without Host validation or authentication \u2014 anyone with network access can call the MCP endpoint and dev routes.`),e.tunnel===!0)try{let{url:t}=await h.start(u);console.log(` \u279C Tunnel: ${t}${m}`)}catch(t){throw await G(),t}b!==void 0&&e.open!==!1&&process.stdout.isTTY===!0&&Ge(`${y}${m}/inspector`),await new Promise(t=>{let s=!1,i=()=>{s||(s=!0,process.off("SIGINT",i),process.off("SIGTERM",i),(async()=>(await G(),t()))())};process.on("SIGINT",i),process.on("SIGTERM",i),e.signal!==void 0&&(e.signal.aborted?i():e.signal.addEventListener("abort",i,{once:!0}))})}export{Ye as runDev};
1
+ import{b as ne}from"../chunk-F5XPOFT7.js";import{a as Z,b as Q}from"../chunk-N7BU45K6.js";import{b as J,c as K}from"../chunk-USIKTT3N.js";import{a as re,b as oe,c as se,d as ie,e as T,g as x,h as ae,j as ce,k as le,l as de}from"../chunk-ICHICRCP.js";import{b as ee,c as te,d as A}from"../chunk-7G4TXPP4.js";import{a as L,b as Y}from"../chunk-FLGSKQGU.js";import{a as X}from"../chunk-LNASFQWW.js";import{existsSync as $e}from"fs";import{createServer as Le}from"http";import{networkInterfaces as Ae}from"os";import{join as Te,resolve as xe}from"path";import Ve from"@tailwindcss/vite";import Fe from"@vitejs/plugin-react";import{createServer as Be,createServerModuleRunner as Ne}from"vite";import{InMemoryServerEventBus as We,localhostAllowedHostnames as Ge,localhostAllowedOrigins as qe,validateHostHeader as ze,validateOriginHeader as Je}from"@modelcontextprotocol/server";import{connect as Se,createServer as _e}from"net";var ue=100,De=300,He=new Set(["127.0.0.1","localhost","::1"]);function Ee(e,r){return new Promise(s=>{let n=_e();n.unref(),n.once("error",()=>s(!1)),n.listen({port:e,host:r},()=>{n.close(()=>s(!0))})})}function pe(e,r){return new Promise(s=>{let n=Se({port:e,host:r});n.setTimeout(De),n.once("connect",()=>{n.destroy(),s(!0)}),n.once("timeout",()=>{n.destroy(),s(!1)}),n.once("error",()=>{n.destroy(),s(!1)})})}async function Ce(e){return await pe(e,"127.0.0.1")||await pe(e,"::1")}async function fe(e,r){for(let s=e;s<e+ue;s++)if(await Ee(s,r)&&!(He.has(r)&&await Ce(s)))return{port:s,requested:e};throw new Error(`No free port found between ${e} and ${e+ue-1} on ${r}.`)}function me(e,r){let s=()=>{let n=e.getBasePath(),{url:c}=e.tunnel.status();return{mcpUrl:c!==null?`${c.replace(/\/+$/,"")}${n}`:null,port:e.port,fromCli:!0,tunnelUrl:c}};return async n=>{let c=e.getBasePath(),d=`${c}/inspector/api/dev/info`,l=`${c}/inspector/api/dev/start-tunnel`,u=`${c}/inspector/api/dev/stop-tunnel`,g=new URL(n.url).pathname;if(n.method==="GET"&&g===d)return Response.json(s());if(n.method==="POST"&&g===l)try{return await e.tunnel.start(e.port),Response.json({ok:!0,restarting:!1})}catch(y){let D=y instanceof Error?y.message:"Failed to start tunnel";return Response.json({error:D},{status:500})}return n.method==="POST"&&g===u?(await e.tunnel.stop(),Response.json({ok:!0})):r(n)}}import{readFileSync as Oe}from"fs";import{createRequire as Ue}from"module";import{join as je}from"path";import{pathToFileURL as ke}from"url";async function we(e){let r=je(e,"package.json"),s=JSON.parse(Oe(r,"utf8"));if([s.dependencies,s.devDependencies,s.optionalDependencies].some(d=>d!==null&&typeof d=="object"&&"@mcp-use/inspector"in d)){let d=Ue(r);try{let l=d.resolve("@mcp-use/inspector");return ve(await import(ke(l).href))}catch(l){if(!he(l))throw l}}try{return ve(await import("@mcp-use/inspector"))}catch(d){if(he(d))return{installed:!1};throw d}}function ve(e){if(typeof e.mountInspector!="function")throw new Error("The installed @mcp-use/inspector is incompatible: its package entry does not export mountInspector(). Update the development dependency.");return{installed:!0,module:e}}function he(e){let r=e!==null&&typeof e=="object"&&"code"in e?String(e.code):void 0;return r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND"}function Ke(e){X(e)}function Xe(){for(let e of Object.values(Ae()))for(let r of e??[])if(!r.internal&&r.family==="IPv4")return r.address}function Ye(e){if(e!==void 0)try{return new URL(`http://${e}`).hostname.replace(/^\[|\]$/g,"")}catch{return}}function Ze(e){let r=e.getHeader("Vary"),s=typeof r=="string"?r:Array.isArray(r)?r.join(", "):r!==void 0?String(r):"";s.split(",").map(n=>n.trim().toLowerCase()).includes("origin")||e.setHeader("Vary",s===""?"Origin":`${s}, Origin`)}function Qe(e,r,s){if(s.tunnelActive){r.setHeader("Access-Control-Allow-Origin","*");return}if(!s.localhostBind)return;let n=e.headers.origin;if(n==="null"){r.setHeader("Access-Control-Allow-Origin","null");return}if(typeof n!="string"||n==="")return;let c=Je(n,qe());!c.ok||c.origin===void 0||(r.setHeader("Access-Control-Allow-Origin",c.origin),Ze(r))}function et(e){let r=e.default;if(r===null||typeof r!="object")throw new Error("The server entry must default-export the MCPServer instance (`export default server`) and never call listen() itself \u2014 `mcp-use dev` owns the socket.");let s=r;if(typeof s.fetch!="function")throw new Error("The entry's default export has no fetch() \u2014 it must be the MCPServer instance (`export default server`).");return s}async function tt(e){process.env.MCP_USE_DEV_CLI="1";let r=se(e.cwd),s=new We(t=>{console.error("[mcp-use] notification delivery failed:",t)});te(e.cwd,"development");let n=K(e.host),c=["127.0.0.1","localhost","::1"].includes(n),d=n==="0.0.0.0"||n==="::",l=Le(),{port:u,requested:g}=await fe(J(e.port),n);u!==g&&console.log(`[mcp-use] port ${g} is taken, using ${u}`),process.env.PORT=String(u);let y=process.env.MCP_URL===void 0&&(n==="127.0.0.1"||n==="localhost"||n==="::1")?`http://localhost:${u}`:void 0,D=e.mcpDir===void 0?e.cwd:xe(e.cwd,e.mcpDir),V=e.entry===void 0?L(D):L(e.cwd,e.entry),H=await Y(e.cwd,V);(H==="created"||H==="updated")&&console.log(`[mcp-use] ${H} mcp-env.d.ts`);let R=e.viewsDir??(e.mcpDir===void 0?void 0:Te(e.mcpDir,"views"));$e(ie(e.cwd,R))||console.log("[mcp-use] views directory not configured.");let p=T(e.cwd,R),P=p.length>0,ge=re(e.cwd),E=["127.0.0.1","localhost","0.0.0.0","::","::1"].includes(n)?"localhost":n,b=`http://${E.includes(":")?`[${E}]`:E}:${u}`,f=await Be({root:e.cwd,configFile:P?ge:!1,envDir:!1,logLevel:"warn",cacheDir:r.cache,resolve:{tsconfigPaths:!0,alias:{tailwindcss:oe()},dedupe:ce},optimizeDeps:le,oxc:{jsx:{runtime:"automatic"}},plugins:P?[A(e.cwd),Ve(),de({getViews:()=>p,dev:{reactRefresh:!0}}),Fe()]:[A(e.cwd)],server:{middlewareMode:!0,...P&&{origin:b},cors:!1,hmr:P?{server:l}:!1,...!P&&{ws:!1}},ssr:{...ee(e.cwd)}}),C=f.environments.ssr,I=Ne(C,{hmr:!1,sourcemapInterceptor:"node"}),F=async()=>{let t=async()=>{let a=await I.import(V),i=et(a),v=ae(p);if(typeof i.__primeViews!="function")throw new Error("Loaded MCPServer instance does not support __primeViews.");return i.__primeViews(v,{dev:!0,projectRoot:e.cwd}),i};if(y===void 0)return t();let o=process.env.MCP_URL;try{return process.env.MCP_URL=y,await t()}finally{o===void 0?delete process.env.MCP_URL:process.env.MCP_URL=o}},O,m;try{let t=await F();t.__setEventBus(s),t.__mount(),O=async o=>t.fetch(o),m=t.basePath??"/mcp"}catch(t){throw await I.close(),await f.close(),t}let U,M,B,N=t=>{if(U===void 0||B===t)return;let o=U.mountInspector({basePath:t,autoConnectUrl:`${b}${t}`,oauthProxyAllowLoopback:c||d,devMode:!0,manufactChatUrl:process.env.MANUFACT_CHAT_URL});if(typeof o!="function")throw new Error("The installed @mcp-use/inspector is incompatible: mountInspector() did not return a Fetch handler.");M=o,B=t};try{if(e.inspector!==!1){let t=await we(e.cwd);t.installed&&(U=t.module,N(m))}}catch(t){throw await I.close(),await f.close(),t}let j=!1,k=!1,W=()=>{if(j){k=!0;return}j=!0,(async()=>{do{k=!1;try{I.evaluatedModules.clear();let t=await F();t.__setEventBus(s),t.__mount();let o=async i=>t.fetch(i),a=t.basePath??"/mcp";N(a),O=o,m=a,s.publish({kind:"tools_list_changed"}),s.publish({kind:"prompts_list_changed"}),s.publish({kind:"resources_list_changed"}),console.log("[mcp-use] reloaded server entry")}catch(t){console.error(`[mcp-use] reload failed \u2014 keeping the previous server:
2
+ `,t)}}while(k);j=!1})()},$=t=>{if(x(t,e.cwd,R))return;let o=C.moduleGraph.getModulesByFile(t);if(!(o===void 0||o.size===0)){for(let a of o)C.moduleGraph.invalidateModule(a);W()}},Pe=t=>{if(!x(t,e.cwd,R))return;let o=p;p=T(e.cwd,R),(o.length!==p.length||o.some((i,v)=>i.name!==p[v]?.name||i.entryPath!==p[v]?.entryPath))&&W()},S=t=>{Pe(t),$(t)};f.watcher.on("change",$),f.watcher.on("add",S),f.watcher.on("unlink",S);let h=ne(r.tunnel);l.prependListener("upgrade",t=>{let o=h.status().url;if(o===null)return;let a=new URL(o).hostname;t.headers.host?.split(":")[0]===a&&(t.headers.host=`localhost:${u}`)});let ye=(t,o)=>{let a=h.status().url,i=a!==null?new URL(a).hostname:null,v=i!==null?[i]:[],w=ze(t.headers.host,[...Ge(),...v]);return w.ok?!1:(o.writeHead(403,{"content-type":"application/json"}),o.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:w.message},id:null})),!0)},G=async()=>{f.watcher.off("change",$),f.watcher.off("add",S),f.watcher.off("unlink",S),await h.stop();let t=new Promise((o,a)=>{l.close(i=>{i!==void 0?a(i):o()})});l.closeAllConnections(),await I.close(),await f.close(),await t},Re=me({getBasePath:()=>m,port:u,tunnel:h},t=>M!==void 0&&Z(t,m)?M(t):O(t)),{toNodeHandler:be}=await import("../node-bridge-WOT2W5YZ.js"),q=be({fetch:Re}),Ie=(t,o)=>{if(c&&ye(t,o))return;let a=t.url??"/",i=new URL(a,"http://127.0.0.1").pathname,v=h.status().url,w=v===null?null:new URL(v).hostname,_=Ye(t.headers.host);if((w!==null&&_===w||d&&_!==void 0&&!["localhost","127.0.0.1","::1"].includes(_))&&Q(i,m)){o.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),o.end("Not Found");return}let z=P&&p.length>0,Me=t.method==="GET"&&(i.startsWith("/@")||i.startsWith("/node_modules/")||i.startsWith("/.mcp-use/")||z&&i.startsWith("/views/"));z&&Me?(Qe(t,o,{tunnelActive:h.status().url!==null,localhostBind:c}),w!==null&&_===w&&(t.headers.host=`localhost:${u}`),f.middlewares(t,o,()=>{q(t,o)})):q(t,o)};if(l.on("request",Ie),await new Promise((t,o)=>{l.once("error",o),l.listen(u,n,()=>t())}),console.log("[mcp-use] dev server ready"),p.length>0&&console.log(` \u279C Views: ${p.map(t=>t.name).join(", ")}`),console.log(` \u279C MCP endpoint: ${b}${m}`),M!==void 0?console.log(` \u279C Inspector: ${b}${m}/inspector`):e.inspector!==!1&&console.warn("[mcp-use] Built-in Inspector is unavailable; reinstall mcp-use to restore visual testing."),n==="0.0.0.0"||n==="::"){let t=Xe();t!==void 0&&console.log(` \u279C Network: http://${t}:${u}${m}`)}if(c||console.warn(`[mcp-use] --host ${n} serves beyond this machine without Host validation or authentication \u2014 anyone with network access can call the MCP endpoint and dev routes.`),e.tunnel===!0)try{let{url:t}=await h.start(u);console.log(` \u279C Tunnel: ${t}${m}`)}catch(t){throw await G(),t}M!==void 0&&e.open!==!1&&process.stdout.isTTY===!0&&Ke(`${b}${m}/inspector`),await new Promise((t,o)=>{let a=!1,i=()=>{a||(a=!0,(async()=>{try{await G(),t()}catch(v){o(v)}finally{process.off("SIGINT",i),process.off("SIGTERM",i)}})())};process.on("SIGINT",i),process.on("SIGTERM",i),e.signal!==void 0&&(e.signal.aborted?i():e.signal.addEventListener("abort",i,{once:!0}))})}export{tt as runDev};
@@ -1,2 +1,38 @@
1
- import{a as h,b as v,c as b,d as C,e as k,f as d}from"../chunk-ZELLSKD2.js";import{a as f,b as l,c as y,d as c,e as m,f as w,g as _}from"../chunk-LHNHT6HO.js";import{parseArgs as u}from"util";async function S(i,n){let o=y(n);try{return i==="login"?await P(n,o):i==="logout"?await $(n,o):await T(n,o)}catch(e){return m(e instanceof TypeError?new f(e.message):e,o)}}async function P(i,n){let{values:o}=u({args:[...i],allowPositionals:!1,strict:!0,options:{"api-key":{type:"string"},org:{type:"string"},"no-open":{type:"boolean"},json:{type:"boolean"}}}),e=o["api-key"]??process.env.MCP_USE_API_KEY;e===void 0&&(e=await I(o["no-open"]===!0||!process.stdout.isTTY));let t=await d.withApiKey(e).identity(),r=o.org!==void 0?k(t.organizations,o.org):t.organizations.find(a=>a.id===t.defaultOrganizationId);return await b({apiKey:e,...r!==void 0?{orgId:r.id,orgName:r.name,...r.slug!==null?{orgSlug:r.slug}:{}}:{}}),c({email:t.email,organization:r??null},n,`Logged in as ${t.email}${r!==void 0?` (${r.name})`:""}.`),0}async function $(i,n){let{values:o}=u({args:[...i],allowPositionals:!1,strict:!0,options:{yes:{type:"boolean"},json:{type:"boolean"}}});return await w("Delete local cloud credentials?",{yes:o.yes===!0,json:n})&&(await C(),c({loggedOut:!0},n,"Logged out.")),0}async function T(i,n){u({args:[...i],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"}}});let o=await v(),e=await(await d.create()).identity(),t=e.organizations.find(a=>a.id===o.orgId)??null,r={userId:e.userId,email:e.email,organization:t};return c(r,n,`${e.email}${t!==null?` \u2014 ${t.name}`:""}`),0}async function I(i){let n=h(),o=await fetch(`${n}/api/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"mcp-use-cli",scope:"openid profile email"})});if(!o.ok)throw new l("login_failed",`Could not start device login (${o.status}).`);let e=await o.json(),t=e.verification_uri_complete??e.verification_uri;process.stderr.write(`Open ${t} and enter code ${e.user_code}.
2
- `),i||_(t);let r=Date.now()+e.expires_in*1e3,a=Math.max(e.interval,1);for(;Date.now()<r;){await O(a*1e3);let s=await(await fetch(`${n}/api/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e.device_code,client_id:"mcp-use-cli"})})).json();if(s.access_token!==void 0){let p=await fetch(`${n}/api/auth/api-key/create`,{method:"POST",headers:{Authorization:`Bearer ${s.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({name:"CLI",prefix:"mcp_"})});if(!p.ok)throw new l("login_failed","Could not create a CLI API key.");let g=await p.json();if(typeof g.key!="string")throw new l("login_failed","Cloud returned an invalid API key.");return g.key}if(s.error!=="authorization_pending"){if(s.error==="slow_down"){a+=5;continue}throw new l("login_failed",s.error_description??s.error??"Device login failed.")}}throw new l("login_timeout","Device login expired.")}function O(i){return new Promise(n=>setTimeout(n,i))}export{S as runIdentity};
1
+ import{b as u,c as b,d as g,e as z,f as P,g as p}from"../chunk-3XW44DRS.js";import{a as d,b as s,c as w,d as y,e as l,f as v,g as _,h as C}from"../chunk-VUVLJMYY.js";import"../chunk-LNASFQWW.js";import{parseArgs as f}from"util";import{createInterface as E}from"readline/promises";var O="mcp-use-cli",I=1800*1e3,T=`Usage: mcp-use login [options]
2
+
3
+ Authenticate the cloud CLI.
4
+
5
+ Options:
6
+ --api-key <key> Authenticate with an API key
7
+ --device-code <code> Redeem a pre-approved device code
8
+ --org <id-or-slug> Select the active organization (required for headless
9
+ login when the account has no default)
10
+ --no-open Do not open the verification URL
11
+ --json Emit machine-readable output
12
+ -h, --help Show this help`,L=`Usage: mcp-use logout [options]
13
+
14
+ Log out of the cloud CLI and delete local cloud credentials.
15
+
16
+ Options:
17
+ --yes Confirm without prompting
18
+ --json Emit {"loggedOut":true}; never prompt
19
+ -h, --help Show this help
20
+
21
+ Exit codes:
22
+ 0 Logged out, cancelled interactively, or help
23
+ 2 Confirmation is required in a non-interactive run
24
+ 1 Local credential removal failed`,S=`Usage: mcp-use whoami [options]
25
+
26
+ Show the authenticated cloud identity and active organization.
27
+
28
+ Options:
29
+ --json Emit a machine-readable identity object
30
+ -h, --help Show this help
31
+
32
+ Exit codes:
33
+ 0 Success or help
34
+ 1 Authentication or API failure`;async function Y(o,i){if(i.some(e=>e==="--help"||e==="-h"))return process.stdout.write(`${o==="login"?T:o==="logout"?L:S}
35
+ `),0;let n=y(i);try{return o==="login"?await D(i,n):o==="logout"?await x(i,n):await j(i,n)}catch(e){return v(e instanceof TypeError?new d(e.message):e,n)}}async function D(o,i){let{values:n}=f({args:[...o],allowPositionals:!1,strict:!0,options:{"api-key":{type:"string"},"device-code":{type:"string"},org:{type:"string"},"no-open":{type:"boolean"},json:{type:"boolean"}}});if(n["api-key"]!==void 0&&n["device-code"]!==void 0)throw new d("--api-key and --device-code cannot be used together.");let e=n["device-code"]?.trim();if(n["device-code"]!==void 0&&e==="")throw new d("--device-code must not be empty.");let t=e===void 0?n["api-key"]??process.env.MCP_USE_API_KEY:void 0;t===void 0&&(t=e===void 0?await U(n["no-open"]===!0||!process.stdout.isTTY):await N(e));let r=await p.withApiKey(t).identity(),a=n.org!==void 0?P(r.organizations,n.org):r.organizations.find(c=>c.id===r.defaultOrganizationId);if(a??=r.organizations.length===1?r.organizations[0]:void 0,a===void 0){if(await g({apiKey:t}),r.organizations.length===0)throw new s("organization_required","The account does not belong to an organization.",{nextSteps:[{description:"Create or join an organization, then log in again",command:"mcp-use login"}]});if(i||!process.stdin.isTTY)throw $(r.organizations);a=await A(r.organizations)}return await g({apiKey:t,...a!==void 0?{orgId:a.id,orgName:a.name,...a.slug!==null?{orgSlug:a.slug}:{}}:{}}),l({email:r.email,organization:a??null},i,`Logged in as ${r.email}${a!==void 0?` (${a.name})`:""}.`),0}function $(o){return new w("organization_required","Choose an active organization for this login.",{organizations:o.map(({id:i,name:n,slug:e})=>({id:i,name:n,slug:e})),nextSteps:[{description:"Select an organization with this saved login",command:"mcp-use org use <id-or-slug>"},{description:"Select it during a future headless login",command:"mcp-use login --org <id-or-slug>"}]})}async function A(o){process.stdout.write(`Choose an active organization:
36
+ `),o.forEach((n,e)=>{let t=n.slug===null?n.id:n.slug;process.stdout.write(` ${e+1}. ${n.name} (${t})
37
+ `)});let i=E({input:process.stdin,output:process.stdout});try{let n=await i.question("Organization [1]: "),e=n.trim()===""?0:Number(n)-1;if(!Number.isInteger(e)||e<0||e>=o.length)throw new d("Invalid organization selection.");return o[e]}finally{i.close()}}async function x(o,i){let{values:n}=f({args:[...o],allowPositionals:!1,strict:!0,options:{yes:{type:"boolean"},json:{type:"boolean"}}});return await _("Log out?",{yes:n.yes===!0,json:i})&&(await z(),l({loggedOut:!0},i,"Logged out.")),0}async function j(o,i){f({args:[...o],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"}}});let n=await b(),e=await(await p.create()).identity(),t=e.organizations.find(a=>a.id===n.orgId)??null,r={userId:e.userId,email:e.email,organization:t};return l(r,i,`${e.email}${t!==null?` \u2014 ${t.name}`:""}`),0}async function U(o){let i=u(),n=await fetch(`${i}/api/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:O,scope:"openid profile email"})});if(!n.ok)throw new s("login_failed",`Could not start device login (${n.status}).`);let e=await n.json(),t=e.verification_uri_complete??e.verification_uri;return process.stderr.write(`Open ${t} and enter code ${e.user_code}.
38
+ `),o||C(t),k(i,e.device_code,Math.max(e.interval,1),Date.now()+e.expires_in*1e3)}async function N(o){return k(u(),o,2,Date.now()+I)}async function k(o,i,n,e){let t=n,r=!0;for(;Date.now()<e;){r||await R(t*1e3),r=!1;let c=await(await fetch(`${o}/api/auth/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:i,client_id:O})})).json();if(c.access_token!==void 0){let m=await fetch(`${o}/api/auth/api-key/create`,{method:"POST",headers:{Authorization:`Bearer ${c.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({name:"CLI",prefix:"mcp_"})});if(!m.ok)throw new s("login_failed","Could not create a CLI API key.");let h=await m.json();if(typeof h.key!="string")throw new s("login_failed","Cloud returned an invalid API key.");return h.key}if(c.error!=="authorization_pending"){if(c.error==="slow_down"){t+=5;continue}throw q(c)}}throw new s("login_timeout","Device login expired.")}function q(o){return o.error==="access_denied"?new s("login_failed","Device login was denied."):o.error==="expired_token"?new s("login_failed","Device code has expired."):new s("login_failed","Device code is invalid, expired, or has already been redeemed.")}function R(o){return new Promise(i=>setTimeout(i,o))}export{Y as runIdentity};
@@ -1,2 +1,43 @@
1
- import{b as m,c as p,e as w,f as y}from"../chunk-ZELLSKD2.js";import{a as s,c as g,d as l,e as f}from"../chunk-LHNHT6HO.js";import{parseArgs as $}from"util";async function I(o){let a=g(o);try{let r=o[0];if(!["list","current","use"].includes(r??""))throw new s("Usage: mcp-use org <list|current|use>");let c=await y.create(),t=await c.identity(),u=await m();if(r==="list"){z(o.slice(1));let e=t.organizations.map(n=>({...n,active:n.id===(u.orgId??t.defaultOrganizationId??void 0)}));return l(e,a,e.map(n=>`${n.active?"* ":" "}${n.name} (${n.slug??n.id}) [${n.role}]`).join(`
2
- `)||"No organizations."),0}if(r==="current"){z(o.slice(1));let e=t.organizations.find(n=>n.id===(u.orgId??t.defaultOrganizationId))??null;if(e===null)throw new s("No active organization. Run `mcp-use org use <id-or-slug>`.");return l(e,a,`${e.name} (${e.slug??e.id})`),0}let d=o[1];if(d===void 0||o.length!==2)throw new s("Usage: mcp-use org use <id-or-slug>");let i=w(t.organizations,d);await p({...u.apiKey!==void 0?{apiKey:u.apiKey}:{},orgId:i.id,orgName:i.name,...i.slug!==null?{orgSlug:i.slug}:{}});try{await c.setDefaultOrganization(i.id)}catch{}return l(i,a,`Using ${i.name} (${i.slug??i.id}).`),0}catch(r){return f(r instanceof TypeError?new s(r.message):r,a)}}function z(o){$({args:[...o],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"}}})}export{I as runOrganizations};
1
+ import{c as h,d as f,f as w,g as z}from"../chunk-3XW44DRS.js";import{a as r,d as m,e as u,f as p}from"../chunk-VUVLJMYY.js";import"../chunk-LNASFQWW.js";import{parseArgs as j}from"util";var E=`Usage: mcp-use org <command> [options]
2
+
3
+ Manage the active cloud organization.
4
+
5
+ Commands:
6
+ list List memberships and mark the active organization
7
+ current Show the active organization
8
+ use <id-or-slug> Save an active organization locally and best-effort
9
+ update the account default
10
+
11
+ Options:
12
+ --json Emit one machine-readable result or error
13
+ -h, --help Show help for this command or subcommand
14
+
15
+ Examples:
16
+ mcp-use org list
17
+ mcp-use org current --json
18
+ mcp-use org use acme --json
19
+
20
+ Exit codes:
21
+ 0 Success or help
22
+ 2 Invalid arguments or no active organization
23
+ 1 Authentication or API failure`,O={list:`Usage: mcp-use org list [--json]
24
+
25
+ List organization memberships. The active entry is marked with * in human output.
26
+
27
+ Options:
28
+ --json Emit an array
29
+ -h, --help Show this help`,current:`Usage: mcp-use org current [--json]
30
+
31
+ Show the active organization.
32
+
33
+ Options:
34
+ --json Emit an organization object
35
+ -h, --help Show this help`,use:`Usage: mcp-use org use <id-or-slug> [--json]
36
+
37
+ Select and persist the active organization.
38
+
39
+ Options:
40
+ --json Emit the selected organization
41
+ -h, --help Show this help`};async function U(t){if(t.findIndex(n=>n==="--help"||n==="-h")!==-1)return process.stdout.write(`${O[t[0]??""]??E}
42
+ `),0;let a=m(t);try{let n=t[0];if(!["list","current","use"].includes(n??""))throw new r("Usage: mcp-use org <list|current|use>");let l=await z.create(),s=await l.identity(),c=await h();if(n==="list"){y(t.slice(1));let e=s.organizations.map(o=>({...o,active:o.id===(c.orgId??s.defaultOrganizationId??void 0)}));return u(e,a,e.map(o=>`${o.active?"* ":" "}${o.name} (${o.slug??o.id}) [${o.role}]`).join(`
43
+ `)||"No organizations."),0}if(n==="current"){y(t.slice(1));let e=s.organizations.find(o=>o.id===(c.orgId??s.defaultOrganizationId))??null;if(e===null)throw new r("No active organization. Run `mcp-use org use <id-or-slug>`.");return u(e,a,`${e.name} (${e.slug??e.id})`),0}let d=t.filter(e=>e!=="--json"),g=d[1];if(g===void 0||d.length!==2)throw new r("Usage: mcp-use org use <id-or-slug>");let i=w(s.organizations,g);await f({...c.apiKey!==void 0?{apiKey:c.apiKey}:{},orgId:i.id,orgName:i.name,...i.slug!==null?{orgSlug:i.slug}:{}});try{await l.setDefaultOrganization(i.id)}catch{}return u(i,a,`Using ${i.name} (${i.slug??i.id}).`),0}catch(n){return p(n instanceof TypeError?new r(n.message):n,a)}}function y(t){j({args:[...t],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"}}})}export{U as runOrganizations};
@@ -1,5 +1,50 @@
1
- import{b as M,c as $,d as x}from"../chunk-N6R74JIF.js";import{a as c,b as s,c as _,d as k,e as R}from"../chunk-LHNHT6HO.js";import{spawn as H}from"child_process";import{access as N,mkdtemp as j,rm as A,writeFile as F}from"fs/promises";import{createServer as G}from"net";import{tmpdir as J}from"os";import{basename as V,join as q,resolve as W}from"path";import{parseArgs as z}from"util";import{fileURLToPath as K}from"url";async function Pe(r){let n=_(r),e,t,i;try{let{values:o,positionals:a}=z({args:[...r],allowPositionals:!0,strict:!0,options:{server:{type:"string"},mcp:{type:"string"},tool:{type:"string"},header:{type:"string",short:"H",multiple:!0},output:{type:"string"},width:{type:"string",default:"1280"},height:{type:"string",default:"720"},"device-scale-factor":{type:"string",default:"1"},theme:{type:"string",default:"light"},inspector:{type:"string"},"cdp-url":{type:"string"},"wait-for":{type:"string"},delay:{type:"string",default:"0"},timeout:{type:"string",default:"30000"},json:{type:"boolean"}}});if(o.server===void 0==(o.mcp===void 0))throw new c("Exactly one of --server or --mcp is required.");if(o.tool===void 0)throw new c("--tool is required.");if(o.server!==void 0&&o.header!==void 0)throw new c("--header is valid only with --mcp.");if(o.theme!=="light"&&o.theme!=="dark")throw new c("--theme must be light or dark.");let w=h(o.width,"--width"),y=h(o.height,"--height"),u=Number(o["device-scale-factor"]);if(!Number.isFinite(u)||u<=0||u>4)throw new c("--device-scale-factor must be greater than 0 and at most 4.");let l=h(o.timeout,"--timeout"),b=de(o.delay,"--delay"),U=ce(o.header??[]);e=o.server!==void 0?await M(o.server):await $(new URL(o.mcp).href,U);let P=(await e.listTools()).find(O=>O.name===o.tool);if(P===void 0)throw new s("tool_not_found",`Tool not found: ${o.tool}`);let m=Z(P),C=x(a),f=await e.callTool(o.tool,C,{timeout:l});if(f.isError===!0)throw new s("tool_failed",`Tool ${o.tool} returned an error.`,f);let I=await e.readResource(m);ee(I),i=o.inspector===void 0?await X(l):void 0;let E=(o.inspector??i.origin).replace(/\/+$/,"");await B(E,l);let S=te(m),p=new URL(`${E}/inspector/preview/${encodeURIComponent(S)}`);p.searchParams.set("protocol","1"),p.searchParams.set("theme",o.theme),p.searchParams.set("width",String(w)),t=o["cdp-url"]!==void 0?await re(o["cdp-url"]):await ne(),await t.cdp.send("Emulation.setDeviceMetricsOverride",{width:w,height:y,deviceScaleFactor:u,mobile:!1},t.sessionId),await t.cdp.send("Page.enable",{},t.sessionId),await t.cdp.send("Runtime.enable",{},t.sessionId),await t.cdp.send("Page.addScriptToEvaluateOnNewDocument",{source:`globalThis.__mcpUsePreviewBundle = ${ue({resourceUri:m,resourceContents:I,toolInput:C,toolOutput:f})};`},t.sessionId),await t.cdp.send("Page.navigate",{url:p.href},t.sessionId),await oe(t,l),await ie(t,o["wait-for"],l),b>0&&await d(b);let T=await t.cdp.send("Page.captureScreenshot",{format:"png",captureBeyondViewport:!1},t.sessionId);if(typeof T.data!="string")throw new s("capture_failed","Chrome returned no screenshot data.");let g=W(o.output??`${S}-${new Date().toISOString().replace(/[:.]/g,"-")}.png`);return await F(g,Buffer.from(T.data,"base64")),k({path:g,width:w,height:y,deviceScaleFactor:u},n,g),0}catch(o){return R(o instanceof TypeError?new c(o.message):o,n)}finally{await t?.close().catch(()=>{}),await i?.close().catch(()=>{}),await e?.disconnect().catch(()=>{})}}async function X(r){let n=await D(),e=import.meta.resolve("@mcp-use/inspector"),t=K(new URL("../cli.js",e)),i=H(process.execPath,[t,"--port",String(n),"--no-open"],{stdio:"ignore"}),o=`http://127.0.0.1:${n}`;try{await Q(o,i,Math.min(r,1e4))}catch(a){throw i.kill("SIGTERM"),a}return{origin:o,async close(){await Y(i)}}}async function Q(r,n,e){let t=Date.now()+e;for(;Date.now()<t;){if(n.exitCode!==null)throw new s("inspector_start_failed",`Packaged Inspector exited before becoming ready (code ${n.exitCode}).`);try{await B(r,Math.min(1e3,e));return}catch{await d(100)}}throw new s("inspector_start_failed","Packaged Inspector did not start in time.")}async function Y(r){r.exitCode===null&&(r.kill("SIGTERM"),await Promise.race([new Promise(n=>r.once("exit",()=>n())),d(2e3)]),r.exitCode===null&&r.kill("SIGKILL"))}async function B(r,n){let e=await fetch(`${r}/inspector/health`,{signal:AbortSignal.timeout(n)});if(!e.ok)throw new s("incompatible_inspector",`Inspector health check failed (${e.status}).`);let t=await e.json();if(t.status!=="ok"||t.protocol!=="mcp-use-inspector-preview"||t.version!==1||!t.capabilities?.includes("view-preview"))throw new s("incompatible_inspector","Inspector does not support mcp-use-inspector-preview version 1.")}function Z(r){let n=r!==null&&typeof r=="object"?r._meta:void 0,t=(n?.ui!==null&&typeof n?.ui=="object"?n.ui.resourceUri:void 0)??n?.["ui/resourceUri"];if(typeof t!="string")throw new s("missing_view","Tool does not advertise an MCP Apps UI resource.");return t}function ee(r){let n=r!==null&&typeof r=="object"?r.contents:void 0;if(!Array.isArray(n))throw new s("invalid_view","View resource has no contents.");let e=n.find(t=>t!==null&&typeof t=="object"&&typeof t.text=="string");if(e===void 0)throw new s("invalid_view","View resource has no HTML document.");return e.text}function te(r){let n=new URL(r);return V(n.pathname).replace(/\.html$/,"")||n.hostname}async function ne(){let r=await se(),n=await D(),e=await j(q(J(),"mcp-use-chrome-")),t=H(r,[`--remote-debugging-port=${n}`,`--user-data-dir=${e}`,"--headless=new","--no-first-run","--no-default-browser-check","about:blank"],{stdio:"ignore"});try{let i=await ae(`http://127.0.0.1:${n}/json/version`,1e4),o=await L(i.webSocketDebuggerUrl);return{...o,async close(){await o.close(),t.kill("SIGTERM"),await A(e,{recursive:!0,force:!0})}}}catch(i){throw t.kill("SIGTERM"),await A(e,{recursive:!0,force:!0}),i}}async function re(r){return L(r)}async function L(r){let n=await v.connect(r),e=await n.send("Target.createTarget",{url:"about:blank"}),t=await n.send("Target.attachToTarget",{targetId:e.targetId,flatten:!0});return{cdp:n,sessionId:t.sessionId,async close(){await n.send("Target.closeTarget",{targetId:e.targetId}).catch(()=>{}),n.close()}}}async function oe(r,n){let e=Date.now()+n;for(;Date.now()<e;){if((await r.cdp.send("Runtime.evaluate",{expression:"document.readyState",returnByValue:!0},r.sessionId)).result?.value==="complete")return;await d(100)}throw new s("browser_timeout","Inspector page did not load in time.")}async function ie(r,n,e){let t=Date.now()+e;for(;Date.now()<t;){let i=`(() => ({
1
+ import{b as B,c as H,d as R}from"../chunk-ISAAAHEM.js";import{a as c,b as s,d as T,e as _,f as M}from"../chunk-VUVLJMYY.js";import"../chunk-LNASFQWW.js";import{spawn as $}from"child_process";import{access as j,mkdtemp as F,rm as A,writeFile as G}from"fs/promises";import{createServer as V}from"net";import{tmpdir as J}from"os";import{basename as q,join as W,resolve as z}from"path";import{parseArgs as K}from"util";import{fileURLToPath as X}from"url";var Q=`Usage: mcp-use screenshot (--server <name> | --mcp <url>) --tool <name> [args...] [options]
2
+
3
+ Call a view-backed MCP tool and capture its rendered MCP App as PNG.
4
+
5
+ Source options:
6
+ --server <name> Use a server saved by mcp-use client
7
+ --mcp <url> Connect directly to an HTTP(S) MCP endpoint
8
+ -H, --header <"Key: Value"> Header for --mcp; repeatable and incompatible
9
+ with --server
10
+
11
+ Capture options:
12
+ --tool <name> View-backed tool to call (required)
13
+ --output <path> Output PNG path (default: timestamped view name)
14
+ --width <px> Host/widget width (default: 768, matching an
15
+ OpenAI inline MCP App container)
16
+ --height <px> Host viewport height used for responsive layout
17
+ (default: 720); PNG is cropped to widget bounds
18
+ --device-scale-factor <n> Pixel density, greater than 0 and at most 4
19
+ (default: 1)
20
+ --theme <light|dark> Host theme (default: light)
21
+ --wait-for <selector> Wait for a selector before capture
22
+ --delay <ms> Additional delay after readiness (default: 0)
23
+ --timeout <ms> Tool/browser timeout (default: 30000)
24
+ --inspector <url> Use an existing Inspector origin
25
+ --cdp-url <url> Use an existing Chrome DevTools endpoint
26
+ --json Emit one result or error; never prompt
27
+ -h, --help Show this help
28
+
29
+ Arguments:
30
+ Pass one JSON object or key=value/key:=<json> pairs after the options.
31
+
32
+ Examples:
33
+ mcp-use screenshot --server demo --tool show-app appName=Demo
34
+ mcp-use screenshot --mcp https://example.com/mcp --tool show-app \\
35
+ '{"appName":"CI"}' --theme dark --output app.png --json
36
+
37
+ Exit codes:
38
+ 0 Capture succeeded or help
39
+ 2 Invalid arguments
40
+ 1 MCP, tool, Inspector, browser, readiness, or write failure`;async function ke(n){if(n.some(o=>o==="--help"||o==="-h"))return process.stdout.write(`${Q}
41
+ `),0;let e=T(n),r,t,i;try{let{values:o,positionals:a}=K({args:[...n],allowPositionals:!0,strict:!0,options:{server:{type:"string"},mcp:{type:"string"},tool:{type:"string"},header:{type:"string",short:"H",multiple:!0},output:{type:"string"},width:{type:"string",default:"768"},height:{type:"string",default:"720"},"device-scale-factor":{type:"string",default:"1"},theme:{type:"string",default:"light"},inspector:{type:"string"},"cdp-url":{type:"string"},"wait-for":{type:"string"},delay:{type:"string",default:"0"},timeout:{type:"string",default:"30000"},json:{type:"boolean"}}});if(o.server===void 0==(o.mcp===void 0))throw new c("Exactly one of --server or --mcp is required.");if(o.tool===void 0)throw new c("--tool is required.");if(o.server!==void 0&&o.header!==void 0)throw new c("--header is valid only with --mcp.");if(o.theme!=="light"&&o.theme!=="dark")throw new c("--theme must be light or dark.");let m=v(o.width,"--width"),b=v(o.height,"--height"),u=Number(o["device-scale-factor"]);if(!Number.isFinite(u)||u<=0||u>4)throw new c("--device-scale-factor must be greater than 0 and at most 4.");let l=v(o.timeout,"--timeout"),P=me(o.delay,"--delay"),N=pe(o.header??[]);r=o.server!==void 0?await B(o.server,3e5,e):await H(new URL(o.mcp).href,N,e);let C=(await r.listTools()).find(O=>O.name===o.tool);if(C===void 0)throw new s("tool_not_found",`Tool not found: ${o.tool}`);let w=te(C),I=R(a),h=await r.callTool(o.tool,I,{timeout:l});if(h.isError===!0)throw new s("tool_failed",`Tool ${o.tool} returned an error.`,h);let S=await r.readResource(w);re(S),i=o.inspector===void 0?await Y(l):void 0;let k=(o.inspector??i.origin).replace(/\/+$/,"");await U(k,l);let E=ne(w),p=new URL(`${k}/inspector/preview/${encodeURIComponent(E)}`);p.searchParams.set("protocol","1"),p.searchParams.set("theme",o.theme),p.searchParams.set("width",String(m)),t=o["cdp-url"]!==void 0?await ie(o["cdp-url"]):await oe(),await t.cdp.send("Emulation.setDeviceMetricsOverride",{width:m,height:b,deviceScaleFactor:u,mobile:!1},t.sessionId),await t.cdp.send("Page.enable",{},t.sessionId),await t.cdp.send("Runtime.enable",{},t.sessionId),await t.cdp.send("Page.addScriptToEvaluateOnNewDocument",{source:`globalThis.__mcpUsePreviewBundle = ${we({resourceUri:w,resourceContents:S,toolInput:I,toolOutput:h})};`},t.sessionId),await t.cdp.send("Page.navigate",{url:p.href},t.sessionId),await se(t,l),await ae(t,o["wait-for"],l),P>0&&await d(P);let f=await ce(t),x=await t.cdp.send("Page.captureScreenshot",{format:"png",captureBeyondViewport:!0,fromSurface:!0,clip:{...f,scale:1}},t.sessionId);if(typeof x.data!="string")throw new s("capture_failed","Chrome returned no screenshot data.");let g=z(o.output??`${E}-${new Date().toISOString().replace(/[:.]/g,"-")}.png`);return await G(g,Buffer.from(x.data,"base64")),_({path:g,width:f.width,height:f.height,viewport:{width:m,height:b},deviceScaleFactor:u,theme:o.theme},e,g),0}catch(o){return M(o instanceof TypeError?new c(o.message):o,e)}finally{await t?.close().catch(()=>{}),await i?.close().catch(()=>{}),await r?.disconnect().catch(()=>{})}}async function Y(n){let e=await L(),r=import.meta.resolve("@mcp-use/inspector"),t=X(new URL("../cli.js",r)),i=$(process.execPath,[t,"--port",String(e),"--no-open"],{stdio:"ignore"}),o=`http://127.0.0.1:${e}`;try{await Z(o,i,Math.min(n,1e4))}catch(a){throw i.kill("SIGTERM"),a}return{origin:o,async close(){await ee(i)}}}async function Z(n,e,r){let t=Date.now()+r;for(;Date.now()<t;){if(e.exitCode!==null)throw new s("inspector_start_failed",`Packaged Inspector exited before becoming ready (code ${e.exitCode}).`);try{await U(n,Math.min(1e3,r));return}catch{await d(100)}}throw new s("inspector_start_failed","Packaged Inspector did not start in time.")}async function ee(n){n.exitCode===null&&(n.kill("SIGTERM"),await Promise.race([new Promise(e=>n.once("exit",()=>e())),d(2e3)]),n.exitCode===null&&n.kill("SIGKILL"))}async function U(n,e){let r=await fetch(`${n}/inspector/health`,{signal:AbortSignal.timeout(e)});if(!r.ok)throw new s("incompatible_inspector",`Inspector health check failed (${r.status}).`);let t=await r.json();if(t.status!=="ok"||t.protocol!=="mcp-use-inspector-preview"||t.version!==1||!t.capabilities?.includes("view-preview"))throw new s("incompatible_inspector","Inspector does not support mcp-use-inspector-preview version 1.")}function te(n){let e=n!==null&&typeof n=="object"?n._meta:void 0,t=(e?.ui!==null&&typeof e?.ui=="object"?e.ui.resourceUri:void 0)??e?.["ui/resourceUri"];if(typeof t!="string")throw new s("missing_view","Tool does not advertise an MCP Apps UI resource.");return t}function re(n){let e=n!==null&&typeof n=="object"?n.contents:void 0;if(!Array.isArray(e))throw new s("invalid_view","View resource has no contents.");let r=e.find(t=>t!==null&&typeof t=="object"&&typeof t.text=="string");if(r===void 0)throw new s("invalid_view","View resource has no HTML document.");return r.text}function ne(n){let e=new URL(n);return q(e.pathname).replace(/\.html$/,"")||e.hostname}async function oe(){let n=await ue(),e=await L(),r=await F(W(J(),"mcp-use-chrome-")),t=$(n,[`--remote-debugging-port=${e}`,`--user-data-dir=${r}`,"--headless=new","--no-first-run","--no-default-browser-check","about:blank"],{stdio:"ignore"});try{let i=await le(`http://127.0.0.1:${e}/json/version`,1e4),o=await D(i.webSocketDebuggerUrl);return{...o,async close(){await o.close(),t.kill("SIGTERM"),await A(r,{recursive:!0,force:!0})}}}catch(i){throw t.kill("SIGTERM"),await A(r,{recursive:!0,force:!0}),i}}async function ie(n){return D(n)}async function D(n){let e=await y.connect(n),r=await e.send("Target.createTarget",{url:"about:blank"}),t=await e.send("Target.attachToTarget",{targetId:r.targetId,flatten:!0});return{cdp:e,sessionId:t.sessionId,async close(){await e.send("Target.closeTarget",{targetId:r.targetId}).catch(()=>{}),e.close()}}}async function se(n,e){let r=Date.now()+e;for(;Date.now()<r;){if((await n.cdp.send("Runtime.evaluate",{expression:"document.readyState",returnByValue:!0},n.sessionId)).result?.value==="complete")return;await d(100)}throw new s("browser_timeout","Inspector page did not load in time.")}async function ae(n,e,r){let t=Date.now()+r;for(;Date.now()<t;){let i=`(() => ({
2
42
  ready: document.body?.dataset.viewReady === "true",
3
43
  error: document.body?.dataset.viewError || null,
4
- selector: ${JSON.stringify(n)} === undefined || !!document.querySelector(${JSON.stringify(n??"")})
5
- }))()`,a=(await r.cdp.send("Runtime.evaluate",{expression:i,returnByValue:!0},r.sessionId)).result?.value;if(a?.error)throw new s("preview_failed",`Inspector preview failed: ${a.error}`);if(a?.ready===!0&&a.selector===!0)return;await d(100)}throw new s("browser_timeout","View did not become ready in time.")}var v=class r{#t;#n=1;#e=new Map;constructor(n){this.#t=n,n.addEventListener("message",e=>{let t=JSON.parse(String(e.data));if(t.id===void 0)return;let i=this.#e.get(t.id);i!==void 0&&(this.#e.delete(t.id),t.error!==void 0?i.reject(new Error(t.error.message??"CDP command failed.")):i.resolve(t.result))}),n.addEventListener("close",()=>{for(let e of this.#e.values())e.reject(new Error("Chrome DevTools connection closed."));this.#e.clear()})}static async connect(n){let e=new WebSocket(n);return await new Promise((t,i)=>{e.addEventListener("open",()=>t(),{once:!0}),e.addEventListener("error",()=>i(new Error("Could not connect to Chrome DevTools.")),{once:!0})}),new r(e)}send(n,e={},t){let i=this.#n++;return new Promise((o,a)=>{this.#e.set(i,{resolve:o,reject:a}),this.#t.send(JSON.stringify({id:i,method:n,params:e,...t!==void 0?{sessionId:t}:{}}))})}close(){this.#t.close()}};async function se(){let n=[process.env.MCP_USE_CHROME_PATH??process.env.PUPPETEER_EXECUTABLE_PATH??process.env.CHROME_PATH,...process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"]:process.platform==="win32"?[`${process.env.PROGRAMFILES??""}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`]:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser"]].filter(e=>e!==void 0&&e!=="");for(let e of n)try{return await N(e),e}catch{}throw new s("chrome_not_found","Chrome, Chromium, Edge, or Brave was not found. Set MCP_USE_CHROME_PATH.")}function D(){return new Promise((r,n)=>{let e=G();e.once("error",n),e.listen(0,"127.0.0.1",()=>{let t=e.address(),i=typeof t=="object"&&t!==null?t.port:0;e.close(o=>o?n(o):r(i))})})}async function ae(r,n){let e=Date.now()+n;for(;Date.now()<e;){try{let t=await fetch(r);if(t.ok)return await t.json()}catch{}await d(100)}throw new s("chrome_start_failed","Chrome DevTools did not start.")}function ce(r){let n={};for(let e of r){let t=e.indexOf(":");if(t<=0)throw new c(`Invalid header: ${e}`);n[e.slice(0,t).trim()]=e.slice(t+1).trim()}return n}function h(r,n){let e=Number(r);if(!Number.isFinite(e)||e<=0)throw new c(`${n} must be positive.`);return e}function de(r,n){let e=Number(r);if(!Number.isFinite(e)||e<0)throw new c(`${n} must be non-negative.`);return e}function ue(r){return JSON.stringify(r).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function d(r){return new Promise(n=>setTimeout(n,r))}export{Pe as runScreenshot};
44
+ selector: ${JSON.stringify(e)} === undefined || !!document.querySelector(${JSON.stringify(e??"")})
45
+ }))()`,a=(await n.cdp.send("Runtime.evaluate",{expression:i,returnByValue:!0},n.sessionId)).result?.value;if(a?.error)throw new s("preview_failed",`Inspector preview failed: ${a.error}`);if(a?.ready===!0&&a.selector===!0)return;await d(100)}throw new s("browser_timeout","View did not become ready in time.")}async function ce(n){let e=await n.cdp.send("Runtime.evaluate",{expression:`(() => {
46
+ const frame = document.querySelector("iframe");
47
+ if (!frame) return null;
48
+ const rect = frame.getBoundingClientRect();
49
+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
50
+ })()`,returnByValue:!0},n.sessionId);return de(e.result?.value)}function de(n){if(n===null||typeof n!="object")throw new s("capture_failed","Inspector preview did not expose rendered widget bounds.");let e=n;if([e.x,e.y,e.width,e.height].some(o=>typeof o!="number"||!Number.isFinite(o))||e.width<=0||e.height<=0)throw new s("capture_failed","Inspector preview returned invalid widget bounds.");let t=Math.floor(e.x),i=Math.floor(e.y);return{x:t,y:i,width:Math.ceil(e.x+e.width)-t,height:Math.ceil(e.y+e.height)-i}}var y=class n{#t;#r=1;#e=new Map;constructor(e){this.#t=e,e.addEventListener("message",r=>{let t=JSON.parse(String(r.data));if(t.id===void 0)return;let i=this.#e.get(t.id);i!==void 0&&(this.#e.delete(t.id),t.error!==void 0?i.reject(new Error(t.error.message??"CDP command failed.")):i.resolve(t.result))}),e.addEventListener("close",()=>{for(let r of this.#e.values())r.reject(new Error("Chrome DevTools connection closed."));this.#e.clear()})}static async connect(e){let r=new WebSocket(e);return await new Promise((t,i)=>{r.addEventListener("open",()=>t(),{once:!0}),r.addEventListener("error",()=>i(new Error("Could not connect to Chrome DevTools.")),{once:!0})}),new n(r)}send(e,r={},t){let i=this.#r++;return new Promise((o,a)=>{this.#e.set(i,{resolve:o,reject:a}),this.#t.send(JSON.stringify({id:i,method:e,params:r,...t!==void 0?{sessionId:t}:{}}))})}close(){this.#t.close()}};async function ue(){let e=[process.env.MCP_USE_CHROME_PATH??process.env.PUPPETEER_EXECUTABLE_PATH??process.env.CHROME_PATH,...process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"]:process.platform==="win32"?[`${process.env.PROGRAMFILES??""}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`]:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser"]].filter(r=>r!==void 0&&r!=="");for(let r of e)try{return await j(r),r}catch{}throw new s("chrome_not_found","Chrome, Chromium, Edge, or Brave was not found. Set MCP_USE_CHROME_PATH.")}function L(){return new Promise((n,e)=>{let r=V();r.once("error",e),r.listen(0,"127.0.0.1",()=>{let t=r.address(),i=typeof t=="object"&&t!==null?t.port:0;r.close(o=>o?e(o):n(i))})})}async function le(n,e){let r=Date.now()+e;for(;Date.now()<r;){try{let t=await fetch(n);if(t.ok)return await t.json()}catch{}await d(100)}throw new s("chrome_start_failed","Chrome DevTools did not start.")}function pe(n){let e={};for(let r of n){let t=r.indexOf(":");if(t<=0)throw new c(`Invalid header: ${r}`);e[r.slice(0,t).trim()]=r.slice(t+1).trim()}return e}function v(n,e){let r=Number(n);if(!Number.isFinite(r)||r<=0)throw new c(`${e} must be positive.`);return r}function me(n,e){let r=Number(n);if(!Number.isFinite(r)||r<0)throw new c(`${e} must be non-negative.`);return r}function we(n){return JSON.stringify(n).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function d(n){return new Promise(e=>setTimeout(e,n))}export{de as normalizeCaptureBounds,ke as runScreenshot};
@@ -1,2 +1,90 @@
1
- import{g as d}from"../chunk-ZELLSKD2.js";import{a as u,c as k,d as l,e as P,f as y}from"../chunk-LHNHT6HO.js";import{parseArgs as m}from"util";async function x(n){let t=k(n);try{let e=n[0];if(e==="list")return await $(n.slice(1),t);if(e==="get")return await E(n.slice(1),t);if(e==="update")return await C(n.slice(1),t);if(e==="delete")return await A(n.slice(1),t);if(e==="env")return await I(n.slice(1),t);throw new u("Usage: mcp-use servers <list|get|update|delete|env>")}catch(e){return P(e instanceof TypeError?new u(e.message):e,t)}}async function $(n,t){let{values:e}=m({args:[...n],allowPositionals:!1,strict:!0,options:S()}),{api:s,organizationId:r}=await d(e.org),{limit:i,skip:a}=N(e.limit,e.skip),c=new URLSearchParams({organizationId:r,limit:String(i),skip:String(a)}),o=await s.request(`/servers?${c}`);return l(o,t),0}async function E(n,t){let{values:e,positionals:s}=m({args:[...n],allowPositionals:!0,strict:!0,options:p()}),r=b(s,"mcp-use servers get <id-or-slug>"),{api:i}=await d(e.org),a=await i.request(`/servers/${encodeURIComponent(r)}`);return l(a,t),0}async function C(n,t){let{values:e,positionals:s}=m({args:[...n],allowPositionals:!0,strict:!0,options:{...p(),name:{type:"string"},description:{type:"string"},branch:{type:"string"},"root-dir":{type:"string"},"build-command":{type:"string"},"start-command":{type:"string"}}}),r=b(s,"mcp-use servers update <id-or-slug>"),i={...e["root-dir"]!==void 0?{rootDir:e["root-dir"]||null}:{},...e["build-command"]!==void 0?{buildCommand:e["build-command"]||null}:{},...e["start-command"]!==void 0?{startCommand:e["start-command"]||null}:{}},a={...e.name!==void 0?{name:e.name}:{},...e.description!==void 0?{description:e.description}:{},...e.branch!==void 0?{productionBranch:e.branch}:{},...Object.keys(i).length>0?{config:i}:{}};if(Object.keys(a).length===0)throw new u("servers update requires at least one mutation option.");let{api:c}=await d(e.org),o=await c.request(`/servers/${encodeURIComponent(r)}`,{method:"PATCH",body:JSON.stringify(a)});return l(o,t,`Updated ${r}.`),0}async function A(n,t){let{values:e,positionals:s}=m({args:[...n],allowPositionals:!0,strict:!0,options:{...p(),yes:{type:"boolean"}}}),r=b(s,"mcp-use servers delete <id-or-slug>");if(!await y(`Delete server ${r}?`,{yes:e.yes===!0,json:t}))return 0;let{api:i}=await d(e.org);return await i.request(`/servers/${encodeURIComponent(r)}`,{method:"DELETE"}),l({deleted:r},t,`Deleted ${r}.`),0}async function I(n,t){let e=n[0];if(e==="list")return O(n.slice(1),t);if(e==="set")return R(n.slice(1),t);if(e==="unset")return q(n.slice(1),t);throw new u("Usage: mcp-use servers env <list|set|unset>")}async function O(n,t){let{values:e,positionals:s}=m({args:[...n],allowPositionals:!0,strict:!0,options:{...p(),branch:{type:"string"}}}),r=b(s,"mcp-use servers env list <server>"),{api:i}=await d(e.org),c=(await f(i,r,e.branch)).map(o=>({id:o.id,key:o.key,branch:o.branch??null,environments:o.environments??[],sensitive:o.sensitive===!0,createdAt:o.createdAt,updatedAt:o.updatedAt}));return l(c,t,c.map(o=>o.key).join(`
2
- `)||"No environment variables."),0}async function R(n,t){let{values:e,positionals:s}=m({args:[...n],allowPositionals:!0,strict:!0,options:{...p(),branch:{type:"string"},secret:{type:"boolean"}}});if(s.length!==2)throw new u("Usage: mcp-use servers env set <server> <KEY=VALUE>");let[r,i]=s,a=i.indexOf("=");if(a<=0)throw new u("Environment value must be KEY=VALUE.");let c=i.slice(0,a),o=i.slice(a+1),{api:g}=await d(e.org),v=(await f(g,r,e.branch)).find(h=>h.key===c&&(h.branch??void 0)===e.branch),w={key:c,value:o,branch:e.branch??null,environments:e.branch===void 0?["production"]:["preview"],sensitive:e.secret===!0},U=v===void 0?await g.request(`/servers/${encodeURIComponent(r)}/env-variables`,{method:"POST",body:JSON.stringify(w)}):await g.request(`/servers/${encodeURIComponent(r)}/env-variables/${encodeURIComponent(v.id)}`,{method:"PATCH",body:JSON.stringify(w)});return l(U,t,`Set ${c}.`),0}async function q(n,t){let{values:e,positionals:s}=m({args:[...n],allowPositionals:!0,strict:!0,options:{...p(),branch:{type:"string"},yes:{type:"boolean"}}});if(s.length!==2)throw new u("Usage: mcp-use servers env unset <server> <key>");let[r,i]=s;if(!await y(`Delete environment variable ${i}?`,{yes:e.yes===!0,json:t}))return 0;let{api:a}=await d(e.org),o=(await f(a,r,e.branch)).find(g=>g.key===i&&(g.branch??void 0)===e.branch);return o!==void 0&&await a.request(`/servers/${encodeURIComponent(r)}/env-variables/${encodeURIComponent(o.id)}`,{method:"DELETE"}),l({deleted:i},t,`Deleted ${i}.`),0}async function f(n,t,e){let s=e===void 0?"":`?branch=${encodeURIComponent(e)}`;return n.request(`/servers/${encodeURIComponent(t)}/env-variables${s}`)}function p(){return{org:{type:"string"},json:{type:"boolean"}}}function S(){return{...p(),limit:{type:"string",default:"30"},skip:{type:"string",default:"0"}}}function b(n,t){if(n.length!==1)throw new u(`Usage: ${t}`);return n[0]}function N(n,t){let e=Number(n??"30"),s=Number(t??"0");if(!Number.isInteger(e)||e<1||e>100)throw new u("--limit must be an integer from 1 to 100.");if(!Number.isInteger(s)||s<0)throw new u("--skip must be a non-negative integer.");return{limit:e,skip:s}}export{x as runServers};
1
+ import{h as p}from"../chunk-3XW44DRS.js";import{a as u,d as E,e as d,f as $,g as w}from"../chunk-VUVLJMYY.js";import"../chunk-LNASFQWW.js";import{parseArgs as g}from"util";var R=`Usage: mcp-use servers <command> [options]
2
+
3
+ Manage cloud servers and environment variables.
4
+
5
+ Commands:
6
+ list List servers
7
+ get <id-or-slug> Show one server
8
+ update <id-or-slug> Update server metadata or build configuration
9
+ delete <id-or-slug> Delete a server
10
+ env list <server> List environment variable metadata
11
+ env set <server> <KEY=VALUE> Create or update an environment variable
12
+ env unset <server> <key> Delete an environment variable
13
+
14
+ Run mcp-use servers <command> --help for all options.
15
+
16
+ Global options:
17
+ --org <id-or-slug> Override the active organization
18
+ --json Emit one machine-readable result or error
19
+ -h, --help Show help
20
+
21
+ Exit codes:
22
+ 0 Success or help
23
+ 2 Invalid arguments or confirmation required
24
+ 1 API or operational failure`,I={list:`Usage: mcp-use servers list [options]
25
+
26
+ Options:
27
+ --org <id-or-slug> Override the active organization
28
+ --limit <n> Results per page (default: 30; range: 1-100)
29
+ --skip <n> Results to skip (default: 0)
30
+ --json Emit the complete API page
31
+ -h, --help Show this help`,get:`Usage: mcp-use servers get <id-or-slug> [options]
32
+
33
+ Options:
34
+ --org <id-or-slug> Override the active organization
35
+ --json Emit the complete server object
36
+ -h, --help Show this help`,update:`Usage: mcp-use servers update <id-or-slug> [options]
37
+
38
+ Options:
39
+ --org <id-or-slug> Override the active organization
40
+ --name <name> Set the display name
41
+ --description <text> Set the description
42
+ --branch <name> Set the production branch
43
+ --root-dir <path> Set the repository root; pass an empty value to clear
44
+ --build-command <cmd> Set the build command; pass an empty value to clear
45
+ --start-command <cmd> Set the start command; pass an empty value to clear
46
+ --watch-paths <glob> Set GitHub path filters; repeatable, empty clears
47
+ --deploy-branches <glob> Set branch filters; repeatable, empty clears
48
+ --wait-for-ci Wait for other GitHub checks before auto-deploy
49
+ --no-wait-for-ci Disable waiting for other GitHub checks
50
+ --json Emit the updated server
51
+ -h, --help Show this help
52
+
53
+ --wait-for-ci and --no-wait-for-ci are mutually exclusive.`,delete:`Usage: mcp-use servers delete <id-or-slug> [options]
54
+
55
+ Options:
56
+ --org <id-or-slug> Override the active organization
57
+ --yes Confirm deletion without prompting
58
+ --json Emit the deletion result; never prompt
59
+ -h, --help Show this help`,env:`Usage: mcp-use servers env <list|set|unset> [options]
60
+
61
+ Commands:
62
+ list <server> List keys and metadata; values are never returned
63
+ set <server> <KEY=VALUE> Create or update a value
64
+ unset <server> <key> Delete a value
65
+
66
+ Run mcp-use servers env <command> --help for all options.`,"env list":`Usage: mcp-use servers env list <server> [options]
67
+
68
+ Options:
69
+ --org <id-or-slug> Override the active organization
70
+ --branch <name> Select preview variables for a branch
71
+ --json Emit metadata only; never values
72
+ -h, --help Show this help`,"env set":`Usage: mcp-use servers env set <server> <KEY=VALUE> [options]
73
+
74
+ Options:
75
+ --org <id-or-slug> Override the active organization
76
+ --branch <name> Set a preview value for a branch (default: production)
77
+ --secret Mark the value sensitive
78
+ --json Emit mutation metadata only; never the value
79
+ -h, --help Show this help`,"env unset":`Usage: mcp-use servers env unset <server> <key> [options]
80
+
81
+ Options:
82
+ --org <id-or-slug> Override the active organization
83
+ --branch <name> Delete a preview value for a branch
84
+ --yes Confirm deletion without prompting
85
+ --json Emit the deletion result; never prompt
86
+ -h, --help Show this help`};async function W(n){if(n.some(e=>e==="--help"||e==="-h")){let e=n[0]==="env"&&n[1]!==void 0?`env ${n[1]}`:n[0]??"";return process.stdout.write(`${I[e]??R}
87
+ `),0}let t=E(n);try{let e=n[0];if(e==="list")return await D(n.slice(1),t);if(e==="get")return await j(n.slice(1),t);if(e==="update")return await L(n.slice(1),t);if(e==="delete")return await N(n.slice(1),t);if(e==="env")return await q(n.slice(1),t);throw new u("Usage: mcp-use servers <list|get|update|delete|env>")}catch(e){return $(e instanceof TypeError?new u(e.message):e,t)}}async function D(n,t){let{values:e}=g({args:[...n],allowPositionals:!1,strict:!0,options:H()}),{api:r,organizationId:s}=await p(e.org),{limit:o,skip:c}=G(e.limit,e.skip),l=new URLSearchParams({organizationId:s,limit:String(o),skip:String(c)}),i=await r.request(`/servers?${l}`);return d(i,t,F(i)),0}async function j(n,t){let{values:e,positionals:r}=g({args:[...n],allowPositionals:!0,strict:!0,options:h()}),s=v(r,"mcp-use servers get <id-or-slug>"),{api:o}=await p(e.org),c=await o.request(`/servers/${encodeURIComponent(s)}`);return d(c,t,V(c)),0}async function L(n,t){let{values:e,positionals:r}=g({args:[...n],allowPositionals:!0,strict:!0,options:{...h(),name:{type:"string"},description:{type:"string"},branch:{type:"string"},"root-dir":{type:"string"},"build-command":{type:"string"},"start-command":{type:"string"},"watch-paths":{type:"string",multiple:!0},"deploy-branches":{type:"string",multiple:!0},"wait-for-ci":{type:"boolean"},"no-wait-for-ci":{type:"boolean"}}}),s=v(r,"mcp-use servers update <id-or-slug>"),o={...e["root-dir"]!==void 0?{rootDir:e["root-dir"]||null}:{},...e["build-command"]!==void 0?{buildCommand:e["build-command"]||null}:{},...e["start-command"]!==void 0?{startCommand:e["start-command"]||null}:{}};if(e["wait-for-ci"]===!0&&e["no-wait-for-ci"]===!0)throw new u("--wait-for-ci and --no-wait-for-ci cannot be used together.");let c={...e.name!==void 0?{name:e.name}:{},...e.description!==void 0?{description:e.description}:{},...e.branch!==void 0?{productionBranch:e.branch}:{},...e["watch-paths"]!==void 0?{watchPaths:P(e["watch-paths"],"--watch-paths",512)}:{},...e["deploy-branches"]!==void 0?{deployBranchPatterns:P(e["deploy-branches"],"--deploy-branches",255)}:{},...e["wait-for-ci"]===!0?{waitForCi:!0}:{},...e["no-wait-for-ci"]===!0?{waitForCi:!1}:{},...Object.keys(o).length>0?{config:o}:{}};if(Object.keys(c).length===0)throw new u("servers update requires at least one mutation option.");let{api:l}=await p(e.org),i=await l.request(`/servers/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(c)});return d(i,t,`Updated ${s}.`),0}async function N(n,t){let{values:e,positionals:r}=g({args:[...n],allowPositionals:!0,strict:!0,options:{...h(),yes:{type:"boolean"}}}),s=v(r,"mcp-use servers delete <id-or-slug>");if(!await w(`Delete server ${s}?`,{yes:e.yes===!0,json:t}))return 0;let{api:o}=await p(e.org);return await o.request(`/servers/${encodeURIComponent(s)}`,{method:"DELETE"}),d({deleted:s},t,`Deleted ${s}.`),0}async function q(n,t){let e=n[0];if(e==="list")return x(n.slice(1),t);if(e==="set")return z(n.slice(1),t);if(e==="unset")return T(n.slice(1),t);throw new u("Usage: mcp-use servers env <list|set|unset>")}async function x(n,t){let{values:e,positionals:r}=g({args:[...n],allowPositionals:!0,strict:!0,options:{...h(),branch:{type:"string"}}}),s=v(r,"mcp-use servers env list <server>"),{api:o}=await p(e.org),l=(await U(o,s,e.branch)).map(i=>({id:i.id,key:i.key,branch:i.branch??null,environments:i.environments??[],sensitive:i.sensitive===!0,createdAt:i.createdAt,updatedAt:i.updatedAt}));return d(l,t,l.map(i=>i.key).join(`
88
+ `)||"No environment variables."),0}async function z(n,t){let{values:e,positionals:r}=g({args:[...n],allowPositionals:!0,strict:!0,options:{...h(),branch:{type:"string"},secret:{type:"boolean"}}});if(r.length!==2)throw new u("Usage: mcp-use servers env set <server> <KEY=VALUE>");let[s,o]=r,c=o.indexOf("=");if(c<=0)throw new u("Environment value must be KEY=VALUE.");let l=o.slice(0,c),i=o.slice(c+1),{api:f}=await p(e.org),b=(await U(f,s,e.branch)).find(S=>S.key===l&&(S.branch??void 0)===e.branch),k={key:l,value:i,branch:e.branch??null,environments:e.branch===void 0?["production"]:["preview"],sensitive:e.secret===!0};b===void 0?await f.request(`/servers/${encodeURIComponent(s)}/env-variables`,{method:"POST",body:JSON.stringify(k)}):await f.request(`/servers/${encodeURIComponent(s)}/env-variables/${encodeURIComponent(b.id)}`,{method:"PATCH",body:JSON.stringify(k)});let C={serverId:s,key:l,scope:e.branch===void 0?"production":"preview",branch:e.branch??null,secret:e.secret===!0,updated:b!==void 0};return d(C,t,`Set ${l}.`),0}async function T(n,t){let{values:e,positionals:r}=g({args:[...n],allowPositionals:!0,strict:!0,options:{...h(),branch:{type:"string"},yes:{type:"boolean"}}});if(r.length!==2)throw new u("Usage: mcp-use servers env unset <server> <key>");let[s,o]=r;if(!await w(`Delete environment variable ${o}?`,{yes:e.yes===!0,json:t}))return 0;let{api:c}=await p(e.org),i=(await U(c,s,e.branch)).find(f=>f.key===o&&(f.branch??void 0)===e.branch);return i!==void 0&&await c.request(`/servers/${encodeURIComponent(s)}/env-variables/${encodeURIComponent(i.id)}`,{method:"DELETE"}),d({deleted:o},t,`Deleted ${o}.`),0}async function U(n,t,e){let r=e===void 0?"":`?branch=${encodeURIComponent(e)}`;return n.request(`/servers/${encodeURIComponent(t)}/env-variables${r}`)}function h(){return{org:{type:"string"},json:{type:"boolean"}}}function F(n){let t=M(n,"items");return t.length===0?"No servers.":["NAME STATUS SOURCE REGION UPDATED",...t.map(r=>{let s=O(r,"connectedRepository"),o=y(s,"isManaged")===!0?"managed":s!==void 0?"github":a(r,"externalUrl")!==void 0?"external":"-";return[a(r,"name")??a(r,"slug")??"-",a(r,"status")??a(r,"latestDeploymentStatus")??"-",o,a(r,"region")??"AUTO",a(r,"updatedAt")??"-"].join(" ")})].join(`
89
+ `)}function V(n){if(!m(n))return String(n);let t=O(n,"connectedRepository"),e=y(t,"isManaged")===!0?"managed":t!==void 0?"github":a(n,"externalUrl")!==void 0?"external":"-",r=A(t,"watchPaths"),s=A(t,"deployBranchPatterns"),o=y(t,"waitForCi");return[`Name: ${a(n,"name")??"-"}`,`ID: ${a(n,"id")??"-"}`,`Slug: ${a(n,"slug")??"-"}`,`Status: ${a(n,"status")??a(n,"latestDeploymentStatus")??"-"}`,`Source: ${e}`,`Region: ${a(n,"region")??"AUTO"}`,`MCP URL: ${a(n,"mcpUrl")??"-"}`,...t!==void 0?[`Watch paths: ${r.length>0?r.join(", "):"all changes"}`,`Deploy branches: ${s.length>0?s.join(", "):"all branches"}`,`Wait for CI: ${o===!0?"yes":"no"}`]:[],`Updated: ${a(n,"updatedAt")??"-"}`].join(`
90
+ `)}function M(n,t){if(!m(n))return[];let e=n[t];return Array.isArray(e)?e.filter(m):[]}function O(n,t){if(!m(n))return;let e=n[t];return m(e)?e:void 0}function a(n,t){if(!m(n))return;let e=n[t];return typeof e=="string"&&e!==""?e:void 0}function y(n,t){if(!m(n))return;let e=n[t];return typeof e=="boolean"?e:void 0}function A(n,t){if(!m(n))return[];let e=n[t];return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function P(n,t,e){if(n.length===1&&n[0]==="")return[];if(n.length>32)throw new u(`${t} accepts at most 32 patterns.`);if(n.some(r=>r===""))throw new u(`${t} accepts an empty value only by itself to clear all patterns.`);if(n.some(r=>r.length>e))throw new u(`${t} patterns may not exceed ${e} characters.`);return n}function m(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function H(){return{...h(),limit:{type:"string",default:"30"},skip:{type:"string",default:"0"}}}function v(n,t){if(n.length!==1)throw new u(`Usage: ${t}`);return n[0]}function G(n,t){let e=Number(n??"30"),r=Number(t??"0");if(!Number.isInteger(e)||e<1||e>100)throw new u("--limit must be an integer from 1 to 100.");if(!Number.isInteger(r)||r<0)throw new u("--skip must be a non-negative integer.");return{limit:e,skip:r}}export{W as runServers};
@@ -1 +1 @@
1
- async function e(t){return(await import("../start-CGEGBZOH.js")).runStart(t)}export{e as runStart};
1
+ async function e(t){return(await import("../start-PCNMGPDW.js")).runStart(t)}export{e as runStart};
@@ -1 +1 @@
1
- import{a as i,b as o}from"../chunk-DB3E6LBX.js";import{spawn as d}from"child_process";import{createRequire as l}from"module";import{dirname as u,join as p,resolve as y}from"path";async function f(e){let c=e.mcpDir===void 0?e.cwd:y(e.cwd,e.mcpDir),n=e.entry===void 0?i(c):i(e.cwd,e.entry),r=await o(e.cwd,n);r==="created"||r==="updated"?console.log(`[mcp-use] ${r} mcp-env.d.ts`):r==="user-owned"&&console.warn("[mcp-use] mcp-env.d.ts is user-owned; leaving it unchanged");let t=g(e.cwd);return w(t,e.cwd,e.tscArgs??[])}function g(e){let c=l(p(e,"package.json"));try{let n=c.resolve("typescript/package.json");return p(u(n),"bin","tsc")}catch{throw new Error(`TypeScript is not installed in ${e}. Install it with npm install --save-dev typescript.`)}}function w(e,c,n){return new Promise((r,t)=>{let s=d(process.execPath,[e,...n,"--noEmit"],{cwd:c,stdio:"inherit"});s.once("error",t),s.once("close",(a,m)=>{r(a??(m==="SIGINT"?130:1))})})}export{f as runTypecheck};
1
+ import{a as i,b as o}from"../chunk-FLGSKQGU.js";import{spawn as d}from"child_process";import{createRequire as l}from"module";import{dirname as u,join as p,resolve as y}from"path";async function f(e){let c=e.mcpDir===void 0?e.cwd:y(e.cwd,e.mcpDir),n=e.entry===void 0?i(c):i(e.cwd,e.entry),r=await o(e.cwd,n);r==="created"||r==="updated"?console.log(`[mcp-use] ${r} mcp-env.d.ts`):r==="user-owned"&&console.warn("[mcp-use] mcp-env.d.ts is user-owned; leaving it unchanged");let t=g(e.cwd);return w(t,e.cwd,e.tscArgs??[])}function g(e){let c=l(p(e,"package.json"));try{let n=c.resolve("typescript/package.json");return p(u(n),"bin","tsc")}catch{throw new Error(`TypeScript is not installed in ${e}. Install it with npm install --save-dev typescript.`)}}function w(e,c,n){return new Promise((r,t)=>{let s=d(process.execPath,[e,...n,"--noEmit"],{cwd:c,stdio:"inherit"});s.once("error",t),s.once("close",(a,m)=>{r(a??(m==="SIGINT"?130:1))})})}export{f as runTypecheck};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-YVHLRRIT.js";import"./chunk-USIKTT3N.js";export{a as main};
1
+ import{a}from"./chunk-HQYBGY3V.js";import"./chunk-USIKTT3N.js";export{a as main};
@@ -0,0 +1 @@
1
+ var w=new WeakSet,b=new WeakMap;function p(e,d){if(e.body===null)return!1;if(w.has(e))return!0;let r=d===void 0?void 0:b.get(d);return r!==void 0&&r.body!==null&&r.body===e.body}function H(e,d){return async(r,o,f)=>{typeof f=="function"&&(f=void 0);let c=!1,s=new AbortController;o.on("close",()=>{c||s.abort()}),o.destroyed===!0&&s.abort();let u,n;try{u=await m(r,f,{signal:s.signal}),n=await e.fetch(u,{...r.auth!==void 0&&{authInfo:r.auth},...f!==void 0&&{parsedBody:f}})}catch(t){try{d?.onerror?.(t instanceof Error?t:new Error(String(t)))}catch{}n=A(k(f))}let i={};for(let[t,l]of n.headers)i[t]=l;if(o.writeHead(n.status,i),n.body===null){c=!0,o.end();return}if(p(n,u)){try{let t=new Uint8Array(await n.arrayBuffer());c=!0,o.end(t)}catch{c=!0,o.end()}return}let a,h=()=>{a?.(),a=void 0},R=()=>new Promise(t=>{a=t});o.on("drain",h);let y=new Promise(t=>{s.signal.addEventListener("abort",()=>t(),{once:!0})});try{for await(let t of n.body){if(s.signal.aborted)break;let l=t instanceof Uint8Array?t:new Uint8Array(t);o.write(l)===!1&&await Promise.race([R(),y])}}catch{}c=!0,o.end()}}async function m(e,d,r){let o=(e.method??"GET").toUpperCase(),c=`http://${g(e.headers.host)??g(e.headers[":authority"])??"localhost"}${e.url??"/"}`,s=new Headers;for(let[n,i]of Object.entries(e.headers))if(!(i===void 0||n.startsWith(":")))if(Array.isArray(i))for(let a of i)s.append(n,a);else s.set(n,i);let u;if(o!=="GET"&&o!=="HEAD")if(d===void 0){let n=new TextDecoder,i="";for await(let a of e)i+=typeof a=="string"?a:n.decode(a,{stream:!0});i+=n.decode(),i.length>0&&(u=i)}else{let n=JSON.stringify(d);s.delete("content-encoding"),s.delete("transfer-encoding"),n===void 0?s.delete("content-length"):(u=n,s.set("content-length",String(new TextEncoder().encode(n).byteLength)))}return new Request(c,{method:o,headers:s,...r?.signal!==void 0&&{signal:r.signal},...u!==void 0&&{body:u}})}function g(e){return Array.isArray(e)?e[0]:e}function k(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let{method:d,id:r}=e;return typeof d!="string"?null:typeof r=="string"||typeof r=="number"?r:null}function A(e){return Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:e},{status:500})}export{H as toNodeHandler,m as toWebRequest};
@@ -1,4 +1,4 @@
1
1
  import{a as E}from"./chunk-N7BU45K6.js";import{b as g,c as v}from"./chunk-USIKTT3N.js";import{c as I}from"./chunk-7G4TXPP4.js";import{readFile as M}from"fs/promises";import{join as d}from"path";import{pathToFileURL as R}from"url";var k=".mcp-use",L="build",N="manifest.json";async function H(t){let o=d(t.cwd,k,L),s=d(o,N),c;try{c=await M(s,"utf8")}catch{throw new Error(`No production build found (missing ${s}).
2
2
  Run \`mcp-use build\` first, then \`mcp-use start\`.`)}let a;try{let n=JSON.parse(c);if(typeof n.entryPoint!="string"||n.entryPoint==="")throw new Error("missing entryPoint");a=n.entryPoint}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`Invalid build manifest at ${s} (${r}).
3
3
  Re-run \`mcp-use build\`.`)}process.env.NODE_ENV??="production",I(t.cwd,"production");let i=d(o,a),u=await import(R(i).href);if(!("default"in u)||u.default===void 0)throw new Error(`The built entry (${i}) has no default export.
4
- The server entry must \`export default\` its MCPServer instance (see the mcp-use entry contract).`);let e=u.default;if(!A(e))throw new Error(`The default export of ${i} is not an MCPServer: it has no listen() method. Export the MCPServer instance as the default export.`);let S=typeof e.port=="number"?e.port:void 0,U=typeof e.host=="string"?e.host:void 0,h=g(t.port,process.env,S),y=v(t.host,process.env,U),l=await(t.withInspector===!0?_(e,h,y):e.listen(h,{host:y})),m=typeof l?.port=="number"?l.port:h,b=typeof l?.url=="string"?l.url:`http://localhost:${m}`,p,w;if(t.tunnel===!0)try{let{createTunnelManager:n}=await import("./tunnel-AQ2WE7EL.js");p=n(d(t.cwd,k,"state","tunnel.json"));let r=await p.start(m),P=new URL(b);w=new URL(`${P.pathname}${P.search}`,`${r.url}/`).toString()}catch(n){try{await p?.stop()}catch{}try{await e.close?.()}catch{}throw n}return{port:m,url:b,...w!==void 0&&{tunnelUrl:w},close:async()=>{let n;try{await p?.stop()}catch(r){n=r}try{await e.close?.()}catch(r){n??=r}if(n!==void 0)throw n}}}async function _(t,o,s){let{mountInspector:c}=await x(),a=typeof t.basePath=="string"?t.basePath:"/mcp",i=c({basePath:a,devMode:!1,oauthProxyAllowLoopback:!1,manufactChatUrl:process.env.MANUFACT_CHAT_URL});return t.app.use("*",async(f,u)=>{if(E(f.req.raw,a))return i(f.req.raw);await u()}),t.listen(o,{host:s})}async function x(){let t;try{t=await import("@mcp-use/inspector")}catch(o){throw O(o)?new Error("Built-in Inspector is unavailable; reinstall mcp-use to restore it."):o}if(typeof t.mountInspector!="function")throw new Error("The installed @mcp-use/inspector is incompatible: its package entry does not export mountInspector(). Reinstall mcp-use.");return{mountInspector:t.mountInspector}}function A(t){return typeof t=="object"&&t!==null&&typeof t.listen=="function"}function O(t){return t!==null&&typeof t=="object"&&"code"in t&&(t.code==="ERR_MODULE_NOT_FOUND"||t.code==="MODULE_NOT_FOUND")}export{H as runStart};
4
+ The server entry must \`export default\` its MCPServer instance (see the mcp-use entry contract).`);let e=u.default;if(!A(e))throw new Error(`The default export of ${i} is not an MCPServer: it has no listen() method. Export the MCPServer instance as the default export.`);let S=typeof e.port=="number"?e.port:void 0,U=typeof e.host=="string"?e.host:void 0,h=g(t.port,process.env,S),y=v(t.host,process.env,U),l=await(t.withInspector===!0?_(e,h,y):e.listen(h,{host:y})),m=typeof l?.port=="number"?l.port:h,b=typeof l?.url=="string"?l.url:`http://localhost:${m}`,p,w;if(t.tunnel===!0)try{let{createTunnelManager:n}=await import("./tunnel-FOJUZGIJ.js");p=n(d(t.cwd,k,"state","tunnel.json"));let r=await p.start(m),P=new URL(b);w=new URL(`${P.pathname}${P.search}`,`${r.url}/`).toString()}catch(n){try{await p?.stop()}catch{}try{await e.close?.()}catch{}throw n}return{port:m,url:b,...w!==void 0&&{tunnelUrl:w},close:async()=>{let n;try{await p?.stop()}catch(r){n=r}try{await e.close?.()}catch(r){n??=r}if(n!==void 0)throw n}}}async function _(t,o,s){let{mountInspector:c}=await x(),a=typeof t.basePath=="string"?t.basePath:"/mcp",i=c({basePath:a,devMode:!1,oauthProxyAllowLoopback:!1,manufactChatUrl:process.env.MANUFACT_CHAT_URL});return t.app.use("*",async(f,u)=>{if(E(f.req.raw,a))return i(f.req.raw);await u()}),t.listen(o,{host:s})}async function x(){let t;try{t=await import("@mcp-use/inspector")}catch(o){throw O(o)?new Error("Built-in Inspector is unavailable; reinstall mcp-use to restore it."):o}if(typeof t.mountInspector!="function")throw new Error("The installed @mcp-use/inspector is incompatible: its package entry does not export mountInspector(). Reinstall mcp-use.");return{mountInspector:t.mountInspector}}function A(t){return typeof t=="object"&&t!==null&&typeof t.listen=="function"}function O(t){return t!==null&&typeof t=="object"&&"code"in t&&(t.code==="ERR_MODULE_NOT_FOUND"||t.code==="MODULE_NOT_FOUND")}export{H as runStart};
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-F5XPOFT7.js";export{b as createTunnelManager,a as tunnelApiBase};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcp-use/cli",
3
3
  "type": "module",
4
- "version": "4.0.0-beta.8",
4
+ "version": "4.0.0",
5
5
  "description": "Prebuilt CLI, development server, and build pipeline for mcp-use",
6
6
  "author": "mcp-use, Inc.",
7
7
  "license": "MIT",
@@ -26,6 +26,9 @@
26
26
  ".": {
27
27
  "types": "./types/index.d.ts",
28
28
  "import": "./dist/index.js"
29
+ },
30
+ "./vite-client": {
31
+ "types": "./types/vite-client.d.ts"
29
32
  }
30
33
  },
31
34
  "files": [
@@ -42,8 +45,8 @@
42
45
  "vite": "^8.0.16"
43
46
  },
44
47
  "peerDependencies": {
45
- "@mcp-use/client": "^2.0.0-alpha.0",
46
- "@mcp-use/inspector": "^20.0.0-beta.0"
48
+ "@mcp-use/client": "^2.0.0",
49
+ "@mcp-use/inspector": "^20.0.0"
47
50
  },
48
51
  "peerDependenciesMeta": {
49
52
  "@mcp-use/client": {
@@ -54,7 +57,7 @@
54
57
  }
55
58
  },
56
59
  "devDependencies": {
57
- "@modelcontextprotocol/server": "2.0.0-beta.5",
60
+ "@modelcontextprotocol/server": "2.0.0",
58
61
  "rimraf": "^6.1.3",
59
62
  "tsup": "^8.5.1",
60
63
  "typescript": "^5.9.3"
@@ -0,0 +1,3 @@
1
+ import "vite/client";
2
+
3
+ export {};
@@ -1,3 +0,0 @@
1
- import{a as p,b as f,d as l}from"./chunk-7G4TXPP4.js";import{existsSync as v}from"fs";import{join as w}from"path";import{fileURLToPath as V}from"url";var h=["vite.config.ts","vite.config.js","vite.config.mts","vite.config.cjs"];function W(t){for(let e of h){let r=w(t,e);if(v(r))return r}return!1}function b(){return V(import.meta.resolve("tailwindcss/index.css"))}import{join as s}from"path";var I=".mcp-use",x="manifest.json";function U(t){let e=s(t,I),r=s(e,"build");return{projectRoot:t,workspace:e,build:r,generated:s(e,"generated"),cache:s(e,"cache"),state:s(e,"state"),cloud:s(e,"cloud"),buildManifest:s(r,x),tunnel:s(e,"state","tunnel.json")}}import{existsSync as m,readdirSync as D}from"fs";import{isAbsolute as _,join as y,resolve as E}from"path";var P="views",a="virtual:mcp-use/views/",c=`\0${a}`;function d(t,e){let r=e??P;return _(r)?r:E(t,r)}function C(t,e){let r=d(t,e);if(!m(r))return[];let n=[];for(let i of D(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let o=y(r,i.name,"view.tsx");m(o)&&n.push({name:i.name,entryPath:o})}return n.sort((i,o)=>i.name.localeCompare(o.name)),n}function R(t){return`${a}${t}`}function S(t){return`/@id/__x00__${a}${t}`}function F(t,e,r){let n=d(e,r);return t===n||t.startsWith(`${n}/`)}function B(t){let e={};for(let r of t)e[r.name]={kind:"external",entry:S(r.name),css:[],scripts:["/@vite/client"]};return e}async function X(t,e,r){let{createServer:n}=await import("vite");return n({root:t,configFile:r,envDir:!1,logLevel:"warn",cacheDir:e,resolve:{tsconfigPaths:!0,alias:p(t)},plugins:[l(t)],server:{middlewareMode:!0,hmr:!1},ssr:{...f(t)}})}var u="virtual:mcp-use/tailwind.css",g=`\0${u}`;function K(t){return{name:"mcp-use-views",applyToEnvironment(e){return e.name==="client"},resolveId(e){if(e===u)return g;if(e.startsWith(a))return`\0${e}`},load(e){if(e===g)return['@import "tailwindcss";',"@custom-variant dark (&:where(.dark, .dark *, [data-theme=dark], [data-theme=dark] *));"].join(`
2
- `);if(!e.startsWith(c))return;let r=e.slice(c.length),n=t.getViews().find(o=>o.name===r);if(n===void 0)return;let i=[];return t.dev?.reactRefresh===!0&&i.push('import "@vitejs/plugin-react/preamble";'),i.push(`import ${JSON.stringify(u)};`),i.push('import { bootstrapView } from "mcp-use/react";',`import * as viewModule from ${JSON.stringify(n.entryPath)};`,"bootstrapView(viewModule);"),t.dev!==void 0&&i.push("if (import.meta.hot) {"," import.meta.hot.accept();","}"),i.push(""),i.join(`
3
- `)}}}export{W as a,b,U as c,C as d,R as e,F as f,B as g,X as h,K as i};
@@ -1,8 +0,0 @@
1
- import{spawn as p}from"child_process";import{constants as u}from"fs";import{access as f,chmod as a,mkdir as m,readFile as l,rename as w,rm as g,writeFile as y}from"fs/promises";import{homedir as x}from"os";import{dirname as $,join as c}from"path";import{createInterface as E}from"readline/promises";var r=class extends Error{exitCode=2},s=class extends Error{code;details;constructor(n,e,o){super(e),this.code=n,this.details=o}};function P(t){return t.includes("--json")}function h(t,n,e){n?process.stdout.write(`${JSON.stringify(t)}
2
- `):e!==void 0?process.stdout.write(`${e}
3
- `):typeof t=="string"?process.stdout.write(`${t}
4
- `):process.stdout.write(`${JSON.stringify(t,null,2)}
5
- `)}function k(t,n){let e=t instanceof r,o=t instanceof s,d=o?t.code:e?"usage_error":"command_failed",i=t instanceof Error?t.message:String(t);return n?process.stderr.write(`${JSON.stringify({error:{code:d,message:i,...o&&t.details!==void 0?{details:t.details}:{}}})}
6
- `):process.stderr.write(`${i}
7
- `),e?2:1}async function _(t,n){if(n.yes)return!0;if(n.json||!process.stdin.isTTY)throw new r(`${t} Pass --yes to confirm.`);let e=E({input:process.stdin,output:process.stdout});try{return(await e.question(`${t} [y/N] `)).trim().toLowerCase()==="y"}finally{e.close()}}function v(t){let[n,e]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let o=p(n,e,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}catch{}}async function j(t){try{return await f(t,u.F_OK),!0}catch{return!1}}async function F(t,n){try{return JSON.parse(await l(t,"utf8"))}catch(e){if(e.code==="ENOENT")return n;throw new s("invalid_state",`Could not read ${t}.`,{cause:e instanceof Error?e.message:String(e)})}}async function I(t,n){let e=$(t);await m(e,{recursive:!0,mode:448}),await a(e,448);let o=c(e,`.${t.slice(t.lastIndexOf("/")+1)}.${process.pid}.${Date.now()}.tmp`);await y(o,`${JSON.stringify(n,null,2)}
8
- `,{mode:384}),await w(o,t),await a(t,384)}async function L(t){await g(t,{force:!0})}var A=c(x(),".mcp-use");export{r as a,s as b,P as c,h as d,k as e,_ as f,v as g,j as h,F as i,I as j,L as k,A as l};
@@ -1,33 +0,0 @@
1
- import{a,b as E,c as L,d as p,e as N,f as S,g as U,h,i as k,j as w,l as R}from"./chunk-LHNHT6HO.js";import{createHash as ie}from"crypto";import{rm as J}from"fs/promises";import{join as P}from"path";import{parseArgs as b}from"util";import{spawn as K}from"child_process";import{readFileSync as W}from"fs";import{chmod as z,mkdir as q}from"fs/promises";import{dirname as V,join as y,resolve as Y}from"path";import{pathToFileURL as M}from"url";var g=y(R,"client-sdk"),m="@mcp-use/client",Z="^2.0.0-alpha.0",Q=[`[mcp-use] ${m} is not installed.`,"The `mcp-use client` and `mcp-use screenshot` commands require it.","Install it in your project:",""," npm install @mcp-use/client",""," pnpm add @mcp-use/client",""," bun add @mcp-use/client"].join(`
2
- `);async function X(e){let n=Y(e);for(;;){if(await h(y(n,"package.json")))return n;let t=V(n);if(t===n)return;n=t}}async function D(){try{return await oe()}catch(e){if(!j(e))throw e;let n=await ee();try{return n.location==="sandbox"?await se():await re(n.projectRoot)}catch(t){throw j(t)?new a(Q):t}}}async function ee(){let e=ne(),n=`${m}@${e}`,t=await X(process.cwd());if(process.stderr.write(`[mcp-use] installing ${m}\u2026
3
- `),t!==void 0){let[s,c]=te(n);if(await I(s,c,t)!==0)throw new E("client_install_failed",`Failed to install ${m}.`);return{location:"project",projectRoot:t}}await q(g,{recursive:!0,mode:448}),await z(g,448);let r=y(g,"package.json");if(await h(r)||await w(r,{private:!0,dependencies:{[m]:e}}),await I("npm",["install",n],g)!==0)throw new E("client_install_failed",`Failed to install ${m}.`);return{location:"sandbox"}}function te(e){let n=process.env.npm_config_user_agent??"";return n.startsWith("pnpm/")?["pnpm",["add",e]]:n.startsWith("bun/")?["bun",["add",e]]:["npm",["install",e]]}function ne(){for(let e of["../package.json","../../package.json"])try{let n=W(new URL(e,import.meta.url),"utf8"),t=JSON.parse(n);if(t.name!=="mcp-use")continue;let r=t.peerDependencies?.[m];if(typeof r=="string"&&r.length>0)return r}catch{}return Z}async function oe(){return import("@mcp-use/client")}async function re(e){let n=M(y(e,"package.json")).href;return import(await import.meta.resolve(m,n))}async function se(){let e=y(g,"node_modules",m,"dist","index.js");return await import(M(e).href)}function j(e){if(!(e instanceof Error))return!1;let n=e.code;return n==="ERR_MODULE_NOT_FOUND"||n==="MODULE_NOT_FOUND"?e.message.includes(m)||e.message.includes("Cannot find package"):!1}function I(e,n,t){return new Promise((r,o)=>{let s=K(e,n,{cwd:t,stdio:"inherit",shell:process.platform==="win32"});s.once("error",o),s.once("exit",(c,u)=>{r(u==="SIGINT"?130:c??1)})})}var B=P(R,"client"),_=P(B,"servers.json"),ae=`Usage: mcp-use client <command> [options]
4
-
5
- Commands:
6
- connect <name> <url> Connect and save an HTTP(S) MCP server
7
- list List saved servers
8
- remove <name> Remove a saved server
9
- <name> Invoke tools/resources/prompts on a saved server
10
-
11
- Connect options:
12
- -H, --header <"Key: Value"> Static header (repeatable)
13
- --no-oauth Skip OAuth on authorization challenges
14
- --auth-timeout <ms> OAuth wait timeout (default: 300000)
15
- --protocol <auto|2026-07-28|2025-11-25>
16
- --open Open the OAuth URL in a browser without prompting
17
- --no-open Print the OAuth URL only
18
- --json Emit machine-readable output
19
-
20
- Saved server commands:
21
- mcp-use client <name> tools list|describe|call ...
22
- mcp-use client <name> resources list|read ...
23
- mcp-use client <name> prompts list|get ...
24
- mcp-use client <name> auth status|logout
25
-
26
- Examples:
27
- mcp-use client connect linear https://mcp.linear.app/mcp
28
- mcp-use client linear tools list
29
- mcp-use client linear tools call search_issues query="open bugs"`;async function _e(e){if(e.includes("--help")||e.includes("-h"))return console.log(ae),0;let n=L(e);try{let t=e[0];if(t==="connect")return await ce(e.slice(1),n);if(t==="list")return await le(e.slice(1),n);if(t==="remove")return await ue(e.slice(1),n);if(t===void 0)throw new a("Usage: mcp-use client <connect|list|remove|name>");return await pe(t,e.slice(1),n)}catch(t){return N(t instanceof TypeError?new a(t.message):t,n)}}async function ce(e,n){let{values:t,positionals:r}=b({args:[...e],allowPositionals:!0,strict:!0,options:{header:{type:"string",short:"H",multiple:!0},"no-oauth":{type:"boolean"},"auth-timeout":{type:"string"},protocol:{type:"string",default:"auto"},open:{type:"boolean"},"no-open":{type:"boolean"},json:{type:"boolean"}}});if(t.open===!0&&t["no-open"]===!0)throw new a("Cannot combine --open and --no-open.");if(r.length!==2)throw new a("Usage: mcp-use client connect <name> <url>");let[o,s]=r;he(o);let c=new URL(s);if(!["http:","https:"].includes(c.protocol))throw new a("Client URLs must use http or https.");let u=we(t.protocol),l=F(t["auth-timeout"]??"300000","--auth-timeout"),i=await C();if(i.servers[o]!==void 0)throw new a(`Saved server already exists: ${o}`);let d={headers:fe(t.header??[])},f={url:c.href,oauth:t["no-oauth"]!==!0,protocol:u};return await(await $(o,f,d,l,me({open:t.open===!0,noOpen:t["no-open"]===!0,json:n}))).disconnect(),i.servers[o]=f,await w(_,i),await w(x(o),d),p({name:o,url:f.url,protocol:u},n,`Connected and saved ${o}.`),0}async function le(e,n){v(e);let t=await C(),r=Object.entries(t.servers).map(([o,s])=>({name:o,...s}));return p(r,n,r.map(o=>`${o.name} ${o.url}`).join(`
30
- `)||"No saved servers."),0}async function ue(e,n){let{values:t,positionals:r}=b({args:[...e],allowPositionals:!0,strict:!0,options:{yes:{type:"boolean"},json:{type:"boolean"}}}),o=T(r,"mcp-use client remove <name>");if(!await S(`Remove saved server ${o}?`,{yes:t.yes===!0,json:n}))return 0;let s=await C();return delete s.servers[o],await w(_,s),await J(A(o),{recursive:!0,force:!0}),p({removed:o},n,`Removed ${o}.`),0}async function pe(e,n,t){let o=(await C()).servers[e];if(o===void 0)throw new a(`Unknown saved server: ${e}. Run \`mcp-use client connect ${e} <url>\`.`);let s=n[0],c=n[1];if(s==="auth"){if(c==="status"){v(n.slice(2));let i=await h(O(e));return p({name:e,oauth:o.oauth,authenticated:i},t,i?"Authenticated.":"No saved OAuth session."),0}if(c==="logout"){let{values:i,positionals:d}=b({args:[...n.slice(2)],allowPositionals:!0,strict:!0,options:{yes:{type:"boolean"},json:{type:"boolean"}}});if(d.length!==0)throw new a(`Usage: mcp-use client ${e} auth logout`);return await S(`Delete OAuth credentials for ${e}?`,{yes:i.yes===!0,json:t})&&(await J(O(e),{recursive:!0,force:!0}),p({loggedOut:e},t,`Logged out ${e}.`)),0}}let u=await k(x(e),{}),l=await $(e,o,u,3e5);try{if(s==="tools"){if(c==="list"){v(n.slice(2));let i=await l.listTools();return p(i,t,i.map(d=>`${d.name} ${d.description??""}`).join(`
31
- `)),0}if(c==="describe"){let i=T(n.slice(2),`mcp-use client ${e} tools describe <tool>`),d=(await l.listTools()).find(f=>f.name===i);if(d===void 0)throw new a(`Tool not found: ${i}`);return p(d,t),0}if(c==="call")return await de(l,e,n.slice(2),t)}if(s==="resources"){if(c==="list"){v(n.slice(2));let i=await l.listResources();return p(i,t),0}if(c==="read"){let i=T(n.slice(2),`mcp-use client ${e} resources read <uri>`);return p(await l.readResource(i),t),0}}if(s==="prompts"){if(c==="list")return v(n.slice(2)),p(await l.listPrompts(),t),0;if(c==="get"){let i=n[2];if(i===void 0)throw new a(`Usage: mcp-use client ${e} prompts get <prompt> [args]`);return p(await l.getPrompt(i,H(n.slice(3))),t),0}}throw new a(`Usage: mcp-use client ${e} <tools|resources|prompts|auth> ...`)}finally{await l.disconnect()}}async function de(e,n,t,r){let o=t[0];if(o===void 0)throw new a(`Usage: mcp-use client ${n} tools call <tool> [args]`);let{values:s,positionals:c}=b({args:[...t.slice(1)],allowPositionals:!0,strict:!0,options:{timeout:{type:"string",default:"30000"},json:{type:"boolean"}}}),u=F(s.timeout,"--timeout"),l=await e.callTool(o,H(c),{timeout:u});if(l.isError===!0)throw new Error(`Tool ${o} returned an error: ${JSON.stringify(l)}`);return p(l,r),0}async function $(e,n,t,r,o=process.stdin.isTTY?"ask":"never"){let{createOAuthProvider:s,MCPClient:c}=await D(),u=O(e),l=n.oauth?await s(n.url,{baseDir:u,authTimeoutMs:r,storageKeyPrefix:`mcp-use-cli:${e}`,openBrowser:async f=>{process.stderr.write(`Open this URL to authenticate:
32
- ${f}
33
- `),o!=="never"&&(o==="ask"&&!await S("Open in browser?",{yes:!1,json:!1})||U(f))}}):void 0,i=n.protocol==="auto"?"auto":{pin:n.protocol};return new c({mcpServers:{[e]:{url:n.url,...t.headers!==void 0?{headers:t.headers}:{},...l!==void 0?{authProvider:l}:{oauth:!1},protocolNegotiation:i}}}).connect(e)}async function Ae(e,n=3e5){let r=(await C()).servers[e];if(r===void 0)throw new a(`Unknown saved server: ${e}`);let o=await k(x(e),{});return $(e,r,o,n)}async function xe(e,n){return $("screenshot",{url:e,oauth:!1,protocol:"auto"},{headers:n},3e5)}function H(e){if(e.length===0)return{};if(e.length===1&&e[0]?.trimStart().startsWith("{")){let t=JSON.parse(e[0]);if(t===null||Array.isArray(t)||typeof t!="object")throw new a("The JSON argument must be an object.");return t}let n={};for(let t of e){let r=t.indexOf(":="),o=t.indexOf("="),s=r>=0?r:o,c=r>=0?2:1;if(s<=0)throw new a(`Expected key=value or key:=<json>, received: ${t}`);let u=t.slice(0,s).replace(/^--/,""),l=t.slice(s+c);n[u]=r>=0?JSON.parse(l):l}return n}function me(e){return e.json||e.noOpen||!process.stdin.isTTY?"never":e.open?"always":"ask"}function fe(e){let n={};for(let t of e){let r=t.indexOf(":");if(r<=0)throw new a(`Invalid header: ${t}`);n[t.slice(0,r).trim()]=t.slice(r+1).trim()}return n}function we(e){if(e!=="auto"&&e!=="2026-07-28"&&e!=="2025-11-25")throw new a(`Invalid protocol: ${e}`);return e}function F(e,n){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new a(`${n} must be a positive integer.`);return t}function he(e){if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(e))throw new a("Server names must be 1-64 filesystem-safe letters, numbers, dots, dashes, or underscores.")}async function C(){return k(_,{servers:{}})}function A(e){return P(B,"credentials",ie("sha256").update(e).digest("hex"))}function x(e){return P(A(e),"credentials.json")}function O(e){return P(A(e),"oauth")}function v(e){b({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"}}})}function T(e,n){if(e.length!==1)throw new a(`Usage: ${n}`);return e[0]}export{_e as a,Ae as b,xe as c,H as d};