@mcp-use/cli 4.0.0-beta.14 → 4.0.0-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as n}from"./chunk-5CBUF6UX.js";import"./chunk-USIKTT3N.js";n(process.argv.slice(2),{frameworkVersion:"4.0.0-beta.14"}).then(e=>{process.exitCode=e},e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
2
+ import{a as n}from"./chunk-DYXX5Q3W.js";import"./chunk-USIKTT3N.js";n(process.argv.slice(2),{frameworkVersion:"4.0.0-beta.15"}).then(e=>{process.exitCode=e},e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
@@ -0,0 +1 @@
1
+ import{b as a,j as w,k as h,l as _,m as C}from"./chunk-VUVLJMYY.js";import{join as O}from"path";var y=O(C,"config.json");function g(){return(process.env.MCP_USE_CLOUD_API_URL??process.env.MCP_API_URL??"https://cloud.manufact.com/api/v1").replace(/\/+$/,"").replace(/\/api\/v1$/,"")+"/api/v1"}function j(){return(process.env.MCP_USE_CLOUD_WEB_URL??"https://manufact.com").replace(/\/+$/,"")}function R(){return g().replace(/\/api\/v1$/,"")}async function I(){return w(y,{})}async function T(t){await h(y,t)}async function E(){await _(y)}function k(t,n){let e=t.filter(i=>i.id===n||i.slug===n);if(e.length!==1)throw new a(e.length===0?"organization_not_found":"organization_ambiguous",`Organization not found: ${n}`);return e[0]}var c=class t{#n;#e;constructor(n,e){this.#n=n,this.#e=e}static async create(n){let e=await I(),i=process.env.MCP_USE_API_KEY??e.apiKey;if(i===void 0||i==="")throw new a("not_authenticated","Not logged in. Run `mcp-use login`.");return new t(i,n??e.orgId)}static withApiKey(n){return new t(n)}async request(n,e={}){let i=b(this.#n,e),r=e.organizationId??this.#e,o=await fetch(`${g()}${n}`,{...e,headers:{Accept:"application/json","x-api-key":this.#n,...r!==void 0?{"x-profile-id":r}:{},...e.body!==void 0?{"Content-Type":"application/json"}:{},...e.headers}}),d=await o.text(),s;try{s=d===""?void 0:JSON.parse(d)}catch{s=d}if(!o.ok)throw A(n,o.status,f(s,i));return s}async multipartRequest(n,e,i={}){let r=v(this.#n,e),o=new AbortController,d=setTimeout(()=>o.abort(),i.timeoutMs??12e4);try{let s=await fetch(`${g()}${n}`,{method:i.method??"POST",headers:{Accept:"application/json","x-api-key":this.#n,...this.#e!==void 0?{"x-profile-id":this.#e}:{}},body:e,signal:o.signal}),l=await s.text(),u;try{u=l===""?void 0:JSON.parse(l)}catch{u=l}if(!s.ok)throw A(n,s.status,f(u,r));return u}catch(s){throw s instanceof Error&&s.name==="AbortError"?new a("cloud_api_timeout",`Cloud upload timed out after ${(i.timeoutMs??12e4)/1e3} seconds.`):s}finally{clearTimeout(d)}}async identity(){let n=await this.request("/test-auth");return{userId:n.user_id,email:n.email,organizations:n.profiles.map(e=>({id:e.id,name:e.profile_name,slug:e.slug,role:e.role})),defaultOrganizationId:n.default_profile_id}}async setDefaultOrganization(n){await this.request(`/organizations/${n}/set-default`,{method:"POST"})}};async function U(t){let n=await I(),e=await(await c.create()).identity(),i=t!==void 0?k(e.organizations,t):e.organizations.find(r=>r.id===(n.orgId??e.defaultOrganizationId));if(i===void 0)throw new a("organization_required","No active organization. Run `mcp-use org use <id-or-slug>`.");return{api:await c.create(i.id),organizationId:i.id}}function P(t){if(typeof t=="string"&&t!=="")return t;if(!(t===null||typeof t!="object"))for(let n of["message","error","detail"]){let e=t[n];if(typeof e=="string"&&e!=="")return e}}function A(t,n,e){let i=P(e)??`Cloud API request failed (${n}).`,r={status:n,...z(e)!==void 0?{validation:z(e)}:{}};if(n===401)return new a("not_authenticated",i,r);if(n===403)return new a("forbidden",i,r);if(n===404&&/^\/servers(?:\/|$)/.test(t))return new a("server_not_found",i,r);if(n===404&&/^\/deployments(?:\/|$)/.test(t))return new a("deployment_not_found",i,r);let o=t.match(/^\/deployments\/([^/]+)\/stop$/);if(o!==null){let d=decodeURIComponent(o[1]??"");return new a("deployment_stop_failed",i,{...r,nextSteps:[{description:"Inspect the deployment state",command:`mcp-use deployments get ${d} --json`},{description:"Delete the deployment instead",command:`mcp-use deployments delete ${d} --yes --json`}]})}return n===400||n===422?new a("validation_error",i,r):new a("cloud_api_error",i,r)}function z(t){if(t===null||typeof t!="object")return;let n=t.details;if(!(n===null||typeof n!="object"&&!Array.isArray(n)))return n}function b(t,n){let e=new Set([t]),i=new Headers(n.headers);for(let r of["authorization","x-api-key"]){let o=i.get(r);o!==null&&e.add(o)}if(typeof n.body=="string")try{p(JSON.parse(n.body),e)}catch{}return e}function v(t,n){let e=new Set([t]);for(let[i,r]of n.entries())if(typeof r=="string")if(/^(?:env|environment|environmentVariables)$/i.test(i))try{m(JSON.parse(r),e)}catch{e.add(r)}else S(i)&&e.add(r);return e}function p(t,n,e=!1){if(typeof t=="string"){e&&n.add(t);return}if(Array.isArray(t)){for(let i of t)p(i,n,e);return}if(!(t===null||typeof t!="object"))for(let[i,r]of Object.entries(t)){let o=e||S(i)||/^(?:env|environment|environmentVariables)$/i.test(i);p(r,n,o)}}function m(t,n){if(typeof t=="string")n.add(t);else if(Array.isArray(t))for(let e of t)m(e,n);else if(t!==null&&typeof t=="object")for(let e of Object.values(t))m(e,n)}function S(t){return/(?:authorization|api[-_]?key|password|secret|token|value)/i.test(t)}function f(t,n){if(typeof t=="string"){let e=t;for(let i of n)i!==""&&(e=e.replaceAll(i,"[REDACTED]"));return e}return Array.isArray(t)?t.map(e=>f(e,n)):t===null||typeof t!="object"?t:Object.fromEntries(Object.entries(t).map(([e,i])=>[e,f(i,n)]))}export{j as a,R as b,I as c,T as d,E as e,k as f,c as g,U as h};
@@ -0,0 +1,90 @@
1
+ import{a as l}from"./chunk-USIKTT3N.js";import{resolve as c}from"path";var s=Object.getOwnPropertyDescriptor(globalThis,"localStorage");s?.get!==void 0&&s.configurable&&Object.defineProperty(globalThis,"localStorage",{configurable:!0,enumerable:s.enumerable??!1,value:void 0,writable:!0});var i=`mcp-use \u2014 run MCP servers built with mcp-use
2
+
3
+ Usage: mcp-use <command> [options]
4
+
5
+ Commands:
6
+ dev Start the dev server
7
+ build Build the server into .mcp-use/build
8
+ typecheck Refresh MCP types and run the project's TypeScript compiler
9
+ start Serve the production build from .mcp-use/build
10
+ login Authenticate the cloud CLI
11
+ logout Log out of the cloud CLI
12
+ whoami Show the authenticated cloud identity
13
+ org Manage the active organization
14
+ servers Manage cloud servers and environment variables
15
+ deployments Manage cloud deployments and logs
16
+ deploy Deploy from GitHub or upload local source
17
+ client Connect to and invoke MCP servers
18
+ screenshot Capture an MCP Apps view
19
+
20
+ Options:
21
+ -p, --port <n> Port to serve on (dev/start; default: $PORT or 3000)
22
+ --host <host> Host to bind (dev/start; default: $HOST or 127.0.0.1)
23
+ --entry <path> Server entry module (dev/build/typecheck only)
24
+ --path <directory> Project root (default: current directory)
25
+ --mcp-dir <dir> Directory containing the MCP entry and views/
26
+ --views-dir <dir> Views directory (default: views/ or <mcp-dir>/views/)
27
+ --source-maps Emit source maps in build output (build only)
28
+ --inline Embed view JS and CSS in MCP resources (build only)
29
+ -- <tsc options> Forward remaining options to TypeScript (typecheck only)
30
+ --with-inspector Mount Inspector on the production listener (start only)
31
+ --tunnel Expose the server through a public tunnel (dev/start only)
32
+ --no-open Do not auto-open the inspector in a browser (dev only)
33
+ --no-inspector Start dev without loading the optional Inspector
34
+ -h, --help Show this help
35
+ -v, --version Print the version`,p={dev:`Usage: mcp-use dev [options]
36
+
37
+ Start the development MCP server with view hot reload.
38
+
39
+ Options:
40
+ -p, --port <n> Listener port (default: $PORT or 3000)
41
+ --host <host> Bind host (default: $HOST or 127.0.0.1)
42
+ --path <directory> Project root (default: current directory)
43
+ --entry <path> Server entry module
44
+ --mcp-dir <dir> Directory containing the entry and views/
45
+ --views-dir <dir> Views directory
46
+ --tunnel Start a public tunnel
47
+ --no-open Do not open Inspector
48
+ --no-inspector Do not load Inspector
49
+ -h, --help Show this help
50
+
51
+ Exit codes: 0 started/help, 2 invalid arguments, 1 startup failure`,build:`Usage: mcp-use build [options]
52
+
53
+ Build the MCP server into .mcp-use/build.
54
+
55
+ Options:
56
+ --path <directory> Project root (default: current directory)
57
+ --entry <path> Server entry module
58
+ --mcp-dir <dir> Directory containing the entry and views/
59
+ --views-dir <dir> Views directory
60
+ --source-maps Emit source maps
61
+ --inline Embed view JavaScript and CSS in MCP resources
62
+ -h, --help Show this help
63
+
64
+ Exit codes: 0 built/help, 2 invalid arguments, 1 build failure`,typecheck:`Usage: mcp-use typecheck [options] [-- <tsc options>]
65
+
66
+ Refresh MCP types and run the selected project's TypeScript compiler.
67
+
68
+ Options:
69
+ --path <directory> Project root (default: current directory)
70
+ --entry <path> Server entry module
71
+ --mcp-dir <dir> Directory containing the MCP entry
72
+ -- <tsc options> Forward remaining options to TypeScript
73
+ -h, --help Show this help
74
+
75
+ Exit codes: 0 passed/help, 2 invalid arguments, otherwise the compiler or operational exit code`,start:`Usage: mcp-use start [options]
76
+
77
+ Serve the production build from .mcp-use/build.
78
+
79
+ Options:
80
+ -p, --port <n> Listener port (default: $PORT or 3000)
81
+ --host <host> Bind host (default: $HOST or 127.0.0.1)
82
+ --path <directory> Project root (default: current directory)
83
+ --with-inspector Mount Inspector on the production listener
84
+ --tunnel Start a public tunnel
85
+ -h, --help Show this help
86
+
87
+ Exit codes: 0 started/help, 2 invalid arguments, 1 startup failure`};async function d(t,r={frameworkVersion:"unknown"}){if(t.length===1&&["--version","-v"].includes(t[0]??""))return console.log(r.frameworkVersion),0;if(t.some(e=>e==="--help"||e==="-h")){let e=t[0];if(e===void 0||e==="--help"||e==="-h")return console.log(i),0;let u=p[e];if(u!==void 0)return console.log(u),0}let o=t[0];if(o==="login"||o==="logout"||o==="whoami"){let{runIdentity:e}=await import("./commands/identity.js");return e(o,t.slice(1))}if(o==="org"){let{runOrganizations:e}=await import("./commands/organizations.js");return e(t.slice(1))}if(o==="servers"){let{runServers:e}=await import("./commands/servers.js");return e(t.slice(1))}if(o==="deployments"){let{runDeployments:e}=await import("./commands/deployments.js");return e(t.slice(1))}if(o==="deploy"){let{runDeploy:e}=await import("./commands/deploy.js");return e(t.slice(1))}if(o==="client"){let{runClient:e}=await import("./commands/client.js");return e(t.slice(1))}if(o==="screenshot"){let{runScreenshot:e}=await import("./commands/screenshot.js");return e(t.slice(1))}let n;try{n=l(t)}catch(e){return console.error(e instanceof Error?e.message:String(e)),2}if(n.version)return console.log(r.frameworkVersion),0;if(n.help)return console.log(i),0;switch(n.command){case"start":return h(n);case"dev":case"build":return f(n.command,n);case"typecheck":return m(n);case void 0:return console.error(i),2;default:return console.error(`Unknown command: ${n.command}
88
+
89
+ ${i}`),2}}async function m(t){try{let{runTypecheck:r}=await import("./commands/typecheck.js");return await r({cwd:c(process.cwd(),t.path??"."),...t.entry!==void 0&&{entry:t.entry},...t.mcpDir!==void 0&&{mcpDir:t.mcpDir},...t.passthrough.length>0&&{tscArgs:t.passthrough}})}catch(r){return console.error(a(r)),1}}async function h(t){let r;try{let{runStart:e}=await import("./commands/start.js");r=await e({cwd:c(process.cwd(),t.path??"."),port:t.port,host:t.host,...t.inspector===!0&&{withInspector:!0},tunnel:t.tunnel})}catch(e){return console.error(e instanceof Error?e.message:String(e)),1}console.log(`mcp-use server running at ${r.url}`),r.tunnelUrl!==void 0&&console.log(`mcp-use public MCP URL: ${r.tunnelUrl}`);let o=!1,n=()=>{o||(o=!0,r.close().then(()=>process.exit(0),e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)}))};return process.once("SIGINT",n),process.once("SIGTERM",n),0}async function f(t,r){let o={cwd:c(process.cwd(),r.path??"."),...r.entry!==void 0&&{entry:r.entry},...r.mcpDir!==void 0&&{mcpDir:r.mcpDir},...r.viewsDir!==void 0&&{viewsDir:r.viewsDir},...r.port!==void 0&&{port:r.port},...r.host!==void 0&&{host:r.host},...r.tunnel&&{tunnel:!0},...!r.open&&{open:!1},...r.inspector===!1&&{inspector:!1},...r.sourceMaps&&{sourceMaps:!0},...r.inline&&{inline:!0}};try{if(t==="dev"){let{runDev:n}=await import("./commands/dev.js");await n(o)}else{let{runBuild:n}=await import("./commands/build.js");await n(o)}return 0}catch(n){return console.error(a(n)),1}}function a(t){let r=t instanceof Error?t.message:String(t);return/tunnel|bore connection/i.test(r)?["[tunnel_connection_timeout] Public tunnel could not establish a connection.",`Cause: ${r}`,"","Retry:"," mcp-use dev --tunnel","","Verify outbound network access and tunnel service status:"," https://local.mcp-use.run"].join(`
90
+ `):r}export{d as a};
@@ -0,0 +1,14 @@
1
+ import{a,b as g,d as z,e as f,f as F,g as G,h as K,i as b,j as T,k as P,m as _}from"./chunk-VUVLJMYY.js";import{createHash as ke}from"crypto";import{rm as ee}from"fs/promises";import{join as A}from"path";import{createInterface as Oe}from"readline/promises";import{parseArgs as E}from"util";var d=["-h, --help","Show this help"],h=["--json","Emit machine-readable JSON (accepted anywhere after client)"],S=new Map;function m(e,t){S.set(e,t)}m("",{usage:"mcp-use client <command>",summary:"Connect to and invoke saved HTTP(S) MCP servers.",commands:[["connect <name> <url>","Connect and save a server"],["list","List saved servers"],["remove <name>","Remove a saved server"],["<name>","Invoke a saved server"]],options:[d]});m("connect",{usage:"mcp-use client connect <name> <url> [options]",summary:"Connect to and save an HTTP(S) MCP server.",options:[['-H, --header <"Key: Value">',"Static header (repeatable)"],["--no-oauth","Skip OAuth on authorization challenges"],["--auth-timeout <ms>","OAuth wait timeout (default: 300000)"],["--protocol <auto|legacy|modern>","Protocol mode (default: auto; modern is stateless/sessionless)"],["--no-open","Print the OAuth URL without opening a browser"],h,d],notes:["JSON mode never opens a browser or prints an OAuth URL/state. If new consent is required, it returns oauth_interaction_required with an interactive retry command."]});m("list",{usage:"mcp-use client list [options]",summary:"List saved MCP servers.",options:[h,d]});m("remove",{usage:"mcp-use client remove <name> [options]",summary:"Immediately remove a saved server and its credentials.",options:[h,d]});m("<name>",{usage:"mcp-use client <name> <command>",summary:"Invoke a saved MCP server.",commands:[["tools","List, describe, or call tools"],["resources","List or read resources"],["prompts","List or get prompts"],["auth","Inspect or clear saved OAuth state"]],options:[d]});m("<name> tools",{usage:"mcp-use client <name> tools <command>",summary:"Use tools on a saved MCP server.",commands:[["list","List tools"],["describe <tool>","Show a tool definition"],["call <tool> [args...]","Call a tool"]],options:[d]});m("<name> tools list",{usage:"mcp-use client <name> tools list [options]",summary:"List tools on a saved MCP server.",options:[h,d]});m("<name> tools describe",{usage:"mcp-use client <name> tools describe <tool> [options]",summary:"Show one tool definition.",options:[h,d]});m("<name> tools call",{usage:"mcp-use client <name> tools call <tool> [args...] [options]",summary:"Call a tool on a saved MCP server.",options:[["--timeout <ms>","Call timeout (default: 30000)"],h,d],notes:["Arguments are one JSON object or key=value/key:=<json> pairs; do not mix forms."]});m("<name> resources",{usage:"mcp-use client <name> resources <command>",summary:"Use resources on a saved MCP server.",commands:[["list","List resources"],["read <uri>","Read a resource"]],options:[d]});m("<name> resources list",{usage:"mcp-use client <name> resources list [options]",summary:"List resources on a saved MCP server.",options:[h,d]});m("<name> resources read",{usage:"mcp-use client <name> resources read <uri> [options]",summary:"Read one resource.",options:[h,d]});m("<name> prompts",{usage:"mcp-use client <name> prompts <command>",summary:"Use prompts on a saved MCP server.",commands:[["list","List prompts"],["get <prompt> [args...]","Get a prompt"]],options:[d]});m("<name> prompts list",{usage:"mcp-use client <name> prompts list [options]",summary:"List prompts on a saved MCP server.",options:[h,d]});m("<name> prompts get",{usage:"mcp-use client <name> prompts get <prompt> [args...] [options]",summary:"Get a prompt from a saved MCP server.",options:[h,d],notes:["Arguments are one JSON object or key=value/key:=<json> pairs; do not mix forms."]});m("<name> auth",{usage:"mcp-use client <name> auth <command>",summary:"Manage saved OAuth state.",commands:[["status","Show OAuth status"],["logout","Delete saved OAuth credentials"]],options:[d]});m("<name> auth status",{usage:"mcp-use client <name> auth status [options]",summary:"Show saved OAuth status.",options:[h,d]});m("<name> auth logout",{usage:"mcp-use client <name> auth logout [options]",summary:"Delete saved OAuth credentials but keep the server.",options:[["--yes","Skip the confirmation prompt"],h,d]});function V(e){let t=e.filter(u=>u!=="--help"&&u!=="-h"&&u!=="--json"),n=t[0];if(n===void 0)return{text:k(S.get(""))};if(n==="connect"||n==="list"||n==="remove")return{text:k(S.get(n))};let o=t[1];if(o===void 0)return{text:k(S.get("<name>"))};if(!["tools","resources","prompts","auth"].includes(o))return{error:`Unknown client command family: ${o}`};let r=t[2],s=`<name> ${o}`;if(r===void 0)return{text:k(S.get(s))};let i=`${s} ${r}`,l=S.get(i);return l===void 0?{error:`Unknown client ${o} command: ${r}`}:{text:k(l)}}function k(e){let t=[`Usage: ${e.usage}`,e.summary];return e.commands!==void 0&&t.push(W("Commands",e.commands)),e.options!==void 0&&t.push(W("Options",e.options)),e.notes!==void 0&&t.push(e.notes.join(`
2
+ `)),t.join(`
3
+
4
+ `)}function W(e,t){let n=Math.max(...t.map(([o])=>o.length));return`${e}:
5
+ ${t.map(([o,r])=>` ${o.padEnd(n)} ${r}`).join(`
6
+ `)}`}import{spawn as ue}from"child_process";import{readFileSync as le}from"fs";import{chmod as de,mkdir as me}from"fs/promises";import{dirname as pe,join as $,resolve as fe}from"path";import{pathToFileURL as Q}from"url";var O=$(_,"client-sdk"),w="@mcp-use/client",ge="^2.0.0-alpha.0",he=[`[mcp-use] ${w} 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(`
7
+ `);async function we(e){let t=fe(e);for(;;){if(await b($(t,"package.json")))return t;let n=pe(t);if(n===t)return;t=n}}async function X(e={}){try{return await Se()}catch(t){if(!Y(t))throw t;if(e.allowInstall===!1)throw new g("client_install_required",`${w} is required for this command.`,{nextSteps:[{description:"Install the optional client SDK",command:`npm install ${w}`}]});let n=await ve();try{return n.location==="sandbox"?await be():await Ce(n.projectRoot)}catch(o){throw Y(o)?new a(he):o}}}async function ve(){let e=Pe(),t=`${w}@${e}`,n=await we(process.cwd());if(process.stderr.write(`[mcp-use] installing ${w}\u2026
8
+ `),n!==void 0){let[s,i]=ye(t);if(await Z(s,i,n)!==0)throw new g("client_install_failed",`Failed to install ${w}.`);return{location:"project",projectRoot:n}}await me(O,{recursive:!0,mode:448}),await de(O,448);let o=$(O,"package.json");if(await b(o)||await P(o,{private:!0,dependencies:{[w]:e}}),await Z("npm",["install",t],O)!==0)throw new g("client_install_failed",`Failed to install ${w}.`);return{location:"sandbox"}}function ye(e){let t=process.env.npm_config_user_agent??"";return t.startsWith("pnpm/")?["pnpm",["add",e]]:t.startsWith("bun/")?["bun",["add",e]]:["npm",["install",e]]}function Pe(){for(let e of["../package.json","../../package.json"])try{let t=le(new URL(e,import.meta.url),"utf8"),n=JSON.parse(t);if(n.name!=="mcp-use")continue;let o=n.peerDependencies?.[w];if(typeof o=="string"&&o.length>0)return o}catch{}return ge}async function Se(){return I(),import("@mcp-use/client")}async function Ce(e){I();let t=Q($(e,"package.json")).href;return import(await import.meta.resolve(w,t))}async function be(){I();let e=$(O,"node_modules",w,"dist","index.js");return await import(Q(e).href)}function I(){let e=Object.getOwnPropertyDescriptor(globalThis,"localStorage");e?.get===void 0||e.configurable!==!0||Object.defineProperty(globalThis,"localStorage",{configurable:!0,enumerable:e.enumerable??!1,value:void 0,writable:!0})}function Y(e){if(!(e instanceof Error))return!1;let t=e.code;return t==="ERR_MODULE_NOT_FOUND"||t==="MODULE_NOT_FOUND"?e.message.includes(w)||e.message.includes("Cannot find package"):!1}function Z(e,t,n){return new Promise((o,r)=>{let s=ue(e,t,{cwd:n,stdio:"inherit",shell:process.platform==="win32"});s.once("error",r),s.once("exit",(i,l)=>{o(l==="SIGINT"?130:i??1)})})}var te=A(_,"client"),L=A(te,"servers.json");async function nt(e){if(e.includes("--help")||e.includes("-h")){let r=V(e);return r.text!==void 0?(process.stdout.write(`${r.text}
9
+ `),0):(process.stderr.write(`${r.error}
10
+ `),2)}let t=z(e),n=e.filter(r=>r!=="--json"),o=n[0];try{if(o==="connect")return await $e(n.slice(1),t);if(o==="list")return await Re(n.slice(1),t);if(o==="remove")return await Ae(n.slice(1),t);if(o===void 0)throw new a("Usage: mcp-use client <connect|list|remove|name>");return await Ee(o,n.slice(1),t)}catch(r){return F(r instanceof TypeError?new a(r.message):r,t)}}async function $e(e,t){let{values:n,positionals:o}=E({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"},"no-open":{type:"boolean"}}});if(o.length!==2)throw new a("Usage: mcp-use client connect <name> <url>");let[r,s]=o;je(r);let i=new URL(s);if(!["http:","https:"].includes(i.protocol))throw new a("Client URLs must use http or https.");let l=Ue(n.protocol),u=re(n["auth-timeout"]??"300000","--auth-timeout"),c=await x();if(c.servers[r]!==void 0)throw new a(`Saved server already exists: ${r}`);let p={headers:Le(n.header??[])},y={url:i.href,oauth:n["no-oauth"]!==!0,protocol:l};return await(await U(r,y,p,u,oe({noOpen:n["no-open"]===!0,json:t}),t,`mcp-use client connect ${r} <url> --no-open`)).disconnect(),c.servers[r]=y,await P(L,c),await P(J(r),p),f({name:r,url:se(y.url),protocol:l},t,`Connected and saved ${r}.`),0}async function Re(e,t){C(e);let n=await x(),o=Object.entries(n.servers).map(([r,s])=>({name:r,...s,url:se(s.url)}));return f(o,t,o.map(r=>`${r.name} ${r.url}`).join(`
11
+ `)||"No saved servers."),0}async function Ae(e,t){let{positionals:n}=E({args:[...e],allowPositionals:!0,strict:!0,options:{}}),o=R(n,"mcp-use client remove <name>"),r=await x();return delete r.servers[o],await P(L,r),await ee(H(o),{recursive:!0,force:!0}),f({removed:o},t,`Removed ${o}.`),0}async function Ee(e,t,n){let r=(await x()).servers[e];if(r===void 0)throw new a(`Unknown saved server: ${e}. Run \`mcp-use client connect ${e} <url>\`.`);let s=t[0],i=t[1];if(s==="auth"){if(i==="status"){C(t.slice(2));let c=await b(D(e));return f({name:e,oauth:r.oauth,authenticated:c},n,c?"Authenticated.":"No saved OAuth session."),0}if(i==="logout"){let{values:c,positionals:p}=E({args:[...t.slice(2)],allowPositionals:!0,strict:!0,options:{yes:{type:"boolean"}}});if(p.length!==0)throw new a(`Usage: mcp-use client ${e} auth logout`);return await G(`Delete OAuth credentials for ${e}?`,{yes:c.yes===!0,json:n})&&(await ee(D(e),{recursive:!0,force:!0}),f({loggedOut:e},n,`Logged out ${e}.`)),0}}xe(e,s,i,t.slice(2));let l=await T(J(e),{}),u=await U(e,r,l,3e5,oe({noOpen:!1,json:n}),n);try{if(s==="tools"){if(i==="list"){C(t.slice(2));let c=await u.listTools();return f(c,n,c.map(p=>p.description?`${p.name} - ${p.description}`:p.name).join(`
12
+ `)),0}if(i==="describe"){let c=R(t.slice(2),`mcp-use client ${e} tools describe <tool>`),p=(await u.listTools()).find(y=>y.name===c);if(p===void 0)throw new a(`Tool not found: ${c}`);return f(p,n),0}if(i==="call")return await Te(u,e,t.slice(2),n)}if(s==="resources"){if(i==="list"){C(t.slice(2));let c=await u.listResources();return f(c,n),0}if(i==="read"){let c=R(t.slice(2),`mcp-use client ${e} resources read <uri>`);return f(await u.readResource(c),n),0}}if(s==="prompts"){if(i==="list")return C(t.slice(2)),f(await u.listPrompts(),n),0;if(i==="get"){let c=t[2];if(c===void 0)throw new a(`Usage: mcp-use client ${e} prompts get <prompt> [args]`);return f(await u.getPrompt(c,j(t.slice(3))),n),0}}throw new a(`Usage: mcp-use client ${e} <tools|resources|prompts|auth> ...`)}finally{await u.disconnect()}}function xe(e,t,n,o){if(t==="tools"&&n==="list"||t==="resources"&&n==="list"||t==="prompts"&&n==="list"){C(o);return}if(t==="tools"&&n==="describe"){R(o,`mcp-use client ${e} tools describe <tool>`);return}if(t==="tools"&&n==="call"){ne(e,o);return}if(t==="resources"&&n==="read"){R(o,`mcp-use client ${e} resources read <uri>`);return}if(t==="prompts"&&n==="get"){if(o[0]===void 0)throw new a(`Usage: mcp-use client ${e} prompts get <prompt> [args]`);j(o.slice(1));return}throw new a(`Usage: mcp-use client ${e} <tools|resources|prompts|auth> ...`)}async function Te(e,t,n,o){let{tool:r,timeout:s,positionals:i}=ne(t,n),l=await e.callTool(r,j(i),{timeout:s});if(l.isError===!0)throw new g("tool_error",`Tool ${r} returned an error.`,l);return f(l,o),0}function ne(e,t){let n=t[0];if(n===void 0)throw new a(`Usage: mcp-use client ${e} tools call <tool> [args]`);let{values:o,positionals:r}=E({args:[...t.slice(1)],allowPositionals:!0,strict:!0,options:{timeout:{type:"string",default:"30000"}}}),s=re(o.timeout,"--timeout");return j(r),{tool:n,timeout:s,positionals:r}}async function U(e,t,n,o,r=process.stdin.isTTY?"ask":"never",s=!1,i=`mcp-use client ${e} tools list`){let{createOAuthProvider:l,MCPClient:u,logger:c}=await X({allowInstall:!s});s&&(c.level="silent");let p,y=s&&t.oauth?new Promise((v,ce)=>{p=ce}):void 0,B=D(e),M=t.oauth?await l(t.url,{baseDir:B,authTimeoutMs:o,storageKeyPrefix:`mcp-use-cli:${e}`,openBrowser:async v=>{if(s){setImmediate(()=>{p?.(new g("oauth_interaction_required","OAuth interaction is required; retry this command without --json in a terminal.",{server:e,nextSteps:[{description:"Authenticate interactively in a terminal",command:i}]}))});return}if(r==="never"){process.stderr.write(`Open this URL to authenticate:
13
+ ${v}
14
+ `);return}await _e(),K(v)}}):void 0,ae=t.protocol==="auto"?{protocolNegotiation:"auto"}:t.protocol==="modern"?{protocolNegotiation:{pin:"2026-07-28"}}:{protocolNegotiation:"legacy",clientOptions:{supportedProtocolVersions:["2025-11-25"]}},q=new u({mcpServers:{[e]:{url:t.url,...n.headers!==void 0?{headers:n.headers}:{},...M!==void 0?{authProvider:M}:{oauth:!1},...ae}}});try{let v=q.connect(e);return await(y===void 0?v:Promise.race([v,y]))}catch(v){throw v instanceof g&&v.code==="oauth_interaction_required"?(M?.dispose?.(),await q.closeSession?.(e),v):Ne(Ie(v,t.protocol),t,n)}}async function ot(e,t=3e5,n=!1){let r=(await x()).servers[e];if(r===void 0)throw new a(`Unknown saved server: ${e}`);let s=await T(J(e),{});return U(e,r,s,t,process.stdin.isTTY?"ask":"never",n)}async function rt(e,t,n=!1){return U("screenshot",{url:e,oauth:!1,protocol:"auto"},{headers:t},3e5,"never",n)}function j(e){if(e.length===0)return{};if(e.length===1&&e[0]?.trimStart().startsWith("{")){let n=JSON.parse(e[0]);if(n===null||Array.isArray(n)||typeof n!="object")throw new a("The JSON argument must be an object.");return n}let t={};for(let n of e){let o=n.indexOf(":="),r=n.indexOf("="),s=o>=0?o:r,i=o>=0?2:1;if(s<=0)throw new a(`Expected key=value or key:=<json>, received: ${n}`);let l=n.slice(0,s).replace(/^--/,""),u=n.slice(s+i);t[l]=o>=0?JSON.parse(u):u}return t}function oe(e){return e.json||e.noOpen||!process.stdin.isTTY?"never":"ask"}async function _e(){let e=Oe({input:process.stdin,output:process.stderr});try{await e.question("This server requires OAuth. Press Enter to open your browser.")}finally{e.close()}}function Le(e){let t={};for(let n of e){let o=n.indexOf(":");if(o<=0)throw new a(`Invalid header: ${n}`);t[n.slice(0,o).trim()]=n.slice(o+1).trim()}return t}function Ue(e){if(e!=="auto"&&e!=="legacy"&&e!=="modern")throw new a("Invalid protocol. Expected auto, legacy, or modern.");return e}function re(e,t){let n=Number(e);if(!Number.isInteger(n)||n<=0)throw new a(`${t} must be a positive integer.`);return n}function je(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.")}function se(e){let t=new URL(e);(t.username!==""||t.password!=="")&&(t.username="[REDACTED]",t.password="");for(let n of[...t.searchParams.keys()])t.searchParams.set(n,"[REDACTED]");return t.hash!==""&&(t.hash="[REDACTED]"),t.href}async function x(){let e=await T(L,{servers:{}}),t={servers:{}},n=!1;for(let[o,r]of Object.entries(e.servers)){let s=Me(r.protocol);t.servers[o]={...r,protocol:s},n||=s!==r.protocol}return n&&await P(L,t),t}function Me(e){if(e==="auto"||e==="legacy"||e==="modern")return e;if(e===void 0)return"auto";if(e==="2025-11-25")return"legacy";if(e==="2026-07-28")return"modern";throw new a("Saved server has an invalid protocol setting. Remove and reconnect it.")}function Ie(e,t){return t==="auto"||!(e instanceof Error)||!e.message.includes("Unsupported protocol version")&&!e.message.includes("pinned protocol version")?e:t==="legacy"?new g("protocol_mismatch","Server does not support the requested legacy protocol."):new g("protocol_mismatch","Server does not support the requested modern protocol (stateless/sessionless, no fallback).")}function Ne(e,t,n){let o=De(t.url,n.headers);if(!(e instanceof Error)||o.size===0)return e;let r=ie(e.message,o);if(e instanceof g)return new g(e.code,r,N(e.details,o));let s=new Error(r);return s.name=e.name,s}function De(e,t){let n=new Set,o=new URL(e);for(let r of[o.username,o.password,...o.searchParams.values(),o.hash.slice(1)])r!==""&&n.add(r);for(let r of Object.values(t??{}))if(r!==""){n.add(r);let s=r.match(/^Bearer\s+(.+)$/i)?.[1];s!==void 0&&n.add(s)}return n}function N(e,t){return typeof e=="string"?ie(e,t):Array.isArray(e)?e.map(n=>N(n,t)):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([n,o])=>[n,N(o,t)]))}function ie(e,t){let n=e;for(let o of t)n=n.replaceAll(o,"[REDACTED]");return n}function H(e){return A(te,"credentials",ke("sha256").update(e).digest("hex"))}function J(e){return A(H(e),"credentials.json")}function D(e){return A(H(e),"oauth")}function C(e){E({args:[...e],allowPositionals:!1,strict:!0,options:{}})}function R(e,t){if(e.length!==1)throw new a(`Usage: ${t}`);return e[0]}export{nt as a,ot as b,rt as c,j as d};
@@ -0,0 +1 @@
1
+ import{mkdir as L,readFile as R,writeFile as O}from"fs/promises";import{spawn as z}from"child_process";import{dirname as D}from"path";var W="https://local.mcp-use.run";function q(){return process.env.MCP_USE_TUNNEL_API??W}var P=1e3,J=3e4;function Q(h){let s,o=null,u,l,d=!1,c,m=P,F=e=>new Promise(n=>{setTimeout(n,e)}),I=()=>{s!==void 0&&"markShutdown"in s&&typeof s.markShutdown=="function"&&s.markShutdown()},b=async e=>{try{await fetch(`${q()}/api/tunnels/${e}`,{method:"DELETE",signal:AbortSignal.timeout(2e3)})}catch{}},_=async()=>{try{let e=await R(h,"utf8"),n=JSON.parse(e);return typeof n.subdomain=="string"?n.subdomain:void 0}catch{return}},E=async e=>{try{await L(D(h),{recursive:!0}),await O(h,JSON.stringify({subdomain:e},null,2),"utf8")}catch(n){console.warn(`[mcp-use] failed to save tunnel subdomain: ${n instanceof Error?n.message:String(n)}`)}},k=()=>{},g=(e,n)=>new Promise((i,f)=>{console.log(`[mcp-use] starting tunnel for port ${e}\u2026`);let x=process.env.npm_config_user_agent??"",[N,A]=x.startsWith("pnpm/")?["pnpm",["--silent","dlx","@mcp-use/tunnel",String(e)]]:x.startsWith("bun/")?["bunx",["@mcp-use/tunnel",String(e)]]:["npx",["--yes","--prefer-offline","@mcp-use/tunnel",String(e)]];n!==void 0&&A.push("--subdomain",n);let a=z(N,A,{stdio:["ignore","pipe","pipe"],shell:process.platform==="win32"}),p=!1,S=!1,T,C=()=>{S=!0};a.markShutdown=C,a.stdout.on("data",r=>{let t=r.toString(),U=t.includes("Shutting down")||t.includes("\u{1F6D1}"),M=t.includes("\u2716")||t.includes("Error:");M&&(T=t.replace(/[✖🛑]/gu,"").replace(/^.*?Error:\s*/s,"").trim()),!S&&!U&&!M&&process.stdout.write(t);let y=t.match(/https?:\/\/([a-z0-9-]+\.[a-z0-9.-]+)/i);if(y!==null&&!p){let B=y[0],$=y[1]??"",w=$.match(/^([a-z0-9-]+)\./i)?.[1]??$.split(".")[0]??"";/^[a-z0-9-]+$/i.test(w)||(console.warn(`[mcp-use] warning: extracted subdomain "${w}" does not match expected format`),w=""),p=!0,clearTimeout(v),i({url:B,subdomain:w,process:a})}}),a.stderr.on("data",r=>{let t=r.toString();/error|timeout|failed/i.test(t)&&(T=t.replace(/^.*?Error:\s*/is,"").trim()),!S&&!t.includes("INFO")&&!t.includes("bore_cli")&&!t.includes("Shutting down")&&!/npm warn Unknown (?:env|project|user|builtin) config/.test(t)&&process.stderr.write(r)}),a.on("error",r=>{p||(clearTimeout(v),f(new Error(`Failed to start tunnel: ${r.message}`)))}),a.on("exit",r=>{r!==0&&r!==null&&!p&&(clearTimeout(v),f(new Error(T??`Tunnel process exited before publishing a URL (code ${r})`))),s===a&&(s=void 0,o=null,d?u=void 0:k())});let v=setTimeout(()=>{p||(a.kill(),f(new Error("Tunnel setup timed out")))},3e4)});return k=()=>{d||l===void 0||o!==null||c===void 0&&(c=(async()=>{for(;!d&&l!==void 0&&o===null;){console.log("[mcp-use] tunnel disconnected, restarting\u2026");let e=u??await _();try{e!==void 0&&await b(e);let n;try{n=await g(l,e)}catch(i){if(e!==void 0)console.log(`[mcp-use] subdomain "${e}" unavailable, requesting a new one\u2026`),n=await g(l,void 0);else throw i}s=n.process,o=n.url,u=n.subdomain,await E(n.subdomain),m=P;return}catch(n){console.warn(`[mcp-use] tunnel restart failed: ${n instanceof Error?n.message:String(n)}`),await F(m),m=Math.min(m*2,J)}}})().finally(()=>{c=void 0}))},{status(){return{url:o}},async start(e){if(d=!1,l=e,o!==null)return{url:o,subdomain:u??""};let n=await _();n!==void 0&&(console.log(`[mcp-use] found existing subdomain: ${n}`),await b(n));let i;try{i=await g(e,n)}catch(f){if(n!==void 0)console.log(`[mcp-use] subdomain "${n}" unavailable, requesting a new one\u2026`),i=await g(e,void 0);else throw f}return s=i.process,o=i.url,u=i.subdomain,await E(i.subdomain),{url:i.url,subdomain:i.subdomain}},async stop(){d=!0,I(),c!==void 0&&await c,u!==void 0&&await b(u),s!==void 0&&(s.kill("SIGINT"),s=void 0),l=void 0,o=null,u=void 0,m=P}}}export{q as a,Q as b};
@@ -0,0 +1,11 @@
1
+ import{a as c}from"./chunk-LNASFQWW.js";import{constants as l}from"fs";import{access as m,chmod as d,mkdir as w,readFile as y,rename as x,rm as g,writeFile as $}from"fs/promises";import{homedir as S}from"os";import{dirname as b,join as p}from"path";import{createInterface as k}from"readline/promises";var r=class extends Error{exitCode=2},s=class extends Error{code;details;constructor(e,t,o){super(t),this.code=e,this.details=o}},u=class extends s{exitCode=2};function _(n){return n.includes("--json")}function h(n,e,t){e?process.stdout.write(`${JSON.stringify(n)}
2
+ `):t!==void 0?process.stdout.write(`${t}
3
+ `):typeof n=="string"?process.stdout.write(`${n}
4
+ `):process.stdout.write(`${JSON.stringify(n,null,2)}
5
+ `)}function v(n,e){let t=n instanceof r||n instanceof s&&"exitCode"in n&&n.exitCode===2,o=n instanceof s,f=o?n.code:t?"usage_error":"command_failed",i=n instanceof Error?n.message:String(n);if(e)process.stderr.write(`${JSON.stringify({error:{code:f,message:i,...o&&n.details!==void 0?{details:n.details}:{}}})}
6
+ `);else if(process.stderr.write(`${i}
7
+ `),o&&N(n.details))for(let a of n.details.nextSteps)process.stderr.write(`
8
+ ${a.description}:
9
+ ${a.command}
10
+ `);return t?2:1}function N(n){if(n===null||typeof n!="object")return!1;let e=n.nextSteps;return Array.isArray(e)&&e.every(t=>t!==null&&typeof t=="object"&&typeof t.description=="string"&&typeof t.command=="string")}async function A(n,e){if(e.yes)return!0;if(e.json||!process.stdin.isTTY)throw new r(`${n} Pass --yes to confirm.`);let t=k({input:process.stdin,output:process.stdout});try{return(await t.question(`${n} [y/N] `)).trim().toLowerCase()==="y"}finally{t.close()}}function B(n){c(n)}async function C(n){try{return await m(n,l.F_OK),!0}catch{return!1}}async function F(n,e){try{return JSON.parse(await y(n,"utf8"))}catch(t){if(t.code==="ENOENT")return e;throw new s("invalid_state",`Could not read ${n}.`,{cause:t instanceof Error?t.message:String(t)})}}async function I(n,e){let t=b(n);await w(t,{recursive:!0,mode:448}),await d(t,448);let o=p(t,`.${n.slice(n.lastIndexOf("/")+1)}.${process.pid}.${Date.now()}.tmp`);await $(o,`${JSON.stringify(e,null,2)}
11
+ `,{mode:384}),await x(o,n),await d(n,384)}async function L(n){await g(n,{force:!0})}var D=p(S(),".mcp-use");export{r as a,s as b,u as c,_ as d,h as e,v as f,A as g,B as h,C as i,F as j,I as k,L as l,D as m};
@@ -1,5 +1,5 @@
1
- import{a as O,b as N,c as j,d as b,e as k,f as F,g as W,h as q,k as S,n as H}from"../chunk-YMYENQ4W.js";import{a as C,b as E,c as I,d as L}from"../chunk-7G4TXPP4.js";import{a as $,b as T}from"../chunk-FLGSKQGU.js";import{randomBytes as Z}from"crypto";import{existsSync as re}from"fs";import{cp as de,mkdir as P,rm as fe,writeFile as D}from"fs/promises";import{join as w,relative as v,resolve as pe}from"path";import me from"@tailwindcss/vite";import ge from"@vitejs/plugin-react";import{build as B}from"vite";import{createServerModuleRunner as J}from"vite";var ce="/mcp",z="http://localhost:3000",h="__mcpUseV1CompatServer";function G(){return globalThis[h]}async function ue(e,t,o){let n=o.filter(r=>r.legacy===!0);if(n.length===0)return;if(typeof t.__registerLegacyViews!="function")throw new Error("Legacy resources/*/widget.tsx views require the temporary mcp-use/server compatibility entry.");let i={};for(let r of n)i[r.name]=await e.import(b(r.entryPath));t.__registerLegacyViews(i)}async function V(e,t){let o=J(e,{hmr:!1,sourcemapInterceptor:"node"}),n=process.env.MCP_URL,i=process.env.MCP_USE_CLI_IMPORT;try{process.env.MCP_USE_CLI_IMPORT="1",n===void 0&&(process.env.MCP_URL=z),delete globalThis[h];let a=(await o.import(t)).default??G();if(a===null||typeof a!="object")throw new Error("The server entry must default-export the MCPServer instance.");return{basePath:a.basePath??ce,supportsLegacyViews:typeof a.__registerLegacyViews=="function"}}finally{delete globalThis[h],n===void 0?delete process.env.MCP_URL:process.env.MCP_URL=n,i===void 0?delete process.env.MCP_USE_CLI_IMPORT:process.env.MCP_USE_CLI_IMPORT=i,await o.close()}}async function Y(e,t){return(await V(e,t)).basePath}async function A(e,t,o,n=[]){let i=J(e,{hmr:!1,sourcemapInterceptor:"node"}),r=process.env.MCP_USE_CLI_IMPORT,a=process.env.MCP_URL;try{process.env.MCP_USE_CLI_IMPORT="1",a===void 0&&(process.env.MCP_URL=z),delete globalThis[h];let s=(await i.import(t)).default??G();if(s===null||typeof s!="object")throw new Error("The server entry must default-export the MCPServer instance.");if(typeof s.__primeViews!="function")throw new Error("The entry's default export does not support __primeViews.");await ue(i,s,n),s.__primeViews(o),s.__mount()}finally{delete globalThis[h],r===void 0?delete process.env.MCP_USE_CLI_IMPORT:process.env.MCP_USE_CLI_IMPORT=r,a===void 0?delete process.env.MCP_URL:process.env.MCP_URL=a,await i.close()}}function le(e){return e.replace(/\/+$/,"")}function K(e){return le(e)}import{hostHeaderValidationResponse as $e,originValidationResponse as Ce}from"@modelcontextprotocol/server";function Q(e,t){let o=t.replace(/^\/+/,"");return e==="/"?`/${o}`:`${e}/${o}`}function X(e,t){return`${Q(e,`_mcp-use/views/${t}`)}/`}var y="index.js",we="entry-wrapper.ts",ye=100*1024*1024;async function ee(e,t){let o=w(e,"public");re(o)&&await de(o,t,{recursive:!0})}async function te(e,t,o,n){let i=w(e,we);await P(e,{recursive:!0});let r=JSON.stringify(o),a=n.filter(s=>s.legacy===!0),c=a.length>0?[`import ${JSON.stringify(t)};`,'import { registerViews } from "mcp-use";']:[`import * as serverModule from ${JSON.stringify(t)};`,'import { registerViews } from "mcp-use";'];if(a.forEach((s,f)=>{c.push(`import * as legacyWidget${f} from ${JSON.stringify(b(s.entryPath))};`)}),c.push(a.length>0?"const server = globalThis.__mcpUseV1CompatServer;":"const server = serverModule.default;",'if (!server) throw new Error("The server entry must default-export MCPServer or use the deprecated mcp-use/server compatibility entry.");'),a.length>0){let s=a.map((f,p)=>`${JSON.stringify(f.name)}: legacyWidget${p}`).join(", ");c.push(`server.__registerLegacyViews?.({ ${s} });`)}return c.push(`server[registerViews] ? server[registerViews](${r}) : server.__primeViews(${r});`,"export default server;",""),await D(i,c.join(`
2
- `)),i}function he(){let e=process.env.MCP_ASSETS_URL;if(!(e===void 0||e.trim()===""))try{return K(new URL(e).href.replace(/\/$/,""))}catch{return}}function U(e,t,o,n){let i=e.replace(/^\/+/,"");return`${o}${X(n,t)}${i}`}function ve(e,t,o,n){return e.kind!=="external"?e:{...e,entry:U(e.entry,t,o,n),css:e.css.map(i=>U(i,t,o,n)),...e.scripts!==void 0&&{scripts:e.scripts.map(i=>U(i,t,o,n))}}}async function Me(e,t){let o=w(t.viewsOutDir,e.name),n=await B({root:t.cwd,configFile:t.userViteConfig,envDir:!1,publicDir:!1,logLevel:"warn",cacheDir:t.cacheDir,resolve:{tsconfigPaths:!0,alias:{tailwindcss:N()}},oxc:{jsx:{runtime:"automatic"}},plugins:[me(),ge(),H({getViews:()=>[e]})],build:{outDir:o,emptyOutDir:!0,write:!t.inline,target:"es2022",sourcemap:t.inline?!1:t.sourceMaps,minify:!0,cssCodeSplit:!1,chunkSizeWarningLimit:1e3,assetsInlineLimit:ye,rollupOptions:{input:{[e.name]:q(e.name)},output:{format:"es",codeSplitting:!t.inline,entryFileNames:"assets/[name]-[hash].js",chunkFileNames:"assets/[name]-[hash].js",assetFileNames:"assets/[name]-[hash][extname]"}}},base:"./"}),i=Array.isArray(n)?n[0]:n;if(i===void 0||!("output"in i))throw new Error(`Client build for view "${e.name}" produced no output.`);let r=i.output,a=Array.isArray(r)?r:Object.values(r),c,s,f,p=[];for(let m of a){if(typeof m!="object"||m===null||!("fileName"in m)||typeof m.fileName!="string")continue;let u=m;u.type==="chunk"&&u.isEntry===!0?(c=u.fileName,f=u.code):u.type==="asset"&&u.fileName.endsWith(".css")&&(s=u.fileName,typeof u.source=="string"?p.push(u.source):u.source instanceof Uint8Array&&p.push(new TextDecoder().decode(u.source)))}if(c===void 0)throw new Error(`Client build produced no entry chunk for view "${e.name}".`);if(t.inline){if(f===void 0)throw new Error(`Client build produced no entry source for view "${e.name}".`);return{kind:"inline",js:f,css:p.join(`
3
- `)}}return{kind:"external",entry:c.replace(/^\/+/,""),css:s!==void 0?[s.replace(/^\/+/,"")]:[]}}async function _e(e){let t=performance.now();I(e.cwd,"production");let o=e.mcpDir===void 0?e.cwd:pe(e.cwd,e.mcpDir),n=e.entry===void 0?$(o):$(e.cwd,e.entry),i=await T(e.cwd,n);(i==="created"||i==="updated")&&console.log(`[mcp-use] ${i} mcp-env.d.ts`);let r=j(e.cwd),a=e.viewsDir??(e.mcpDir===void 0?void 0:w(e.mcpDir,"views"));re(F(e.cwd,a))||console.log("[mcp-use] views directory not configured.");let c=W(e.cwd,a,{includeLegacy:!0}),s=c,f=O(e.cwd),p=e.sourceMaps===!0,m=e.inline===!0,d,u;if(c.some(l=>l.legacy===!0)){d=await S(e.cwd,r.cache,!1);let l;try{l=await V(d.environments.ssr,n)}catch(g){throw await d.close(),g}u=l.basePath,l.supportsLegacyViews||(s=c.filter(g=>g.legacy!==!0))}if(s.length===0){d??=await S(e.cwd,r.cache,!1);try{await A(d.environments.ssr,n,{},s);let ae=await te(r.cache,n,{},s);await B({root:e.cwd,configFile:!1,envDir:!1,publicDir:!1,logLevel:"warn",cacheDir:r.cache,resolve:{tsconfigPaths:!0,alias:C(e.cwd)},plugins:[L(e.cwd)],build:{ssr:ae,outDir:r.build,emptyOutDir:!0,target:"node22",sourcemap:p,minify:!1,rollupOptions:{output:{format:"es",entryFileNames:y}}},ssr:{...E(e.cwd),target:"node"}})}finally{await d?.close()}await ee(e.cwd,w(r.build,"views/public"));let l={buildId:Z(8).toString("hex"),entryPoint:y,createdAt:new Date().toISOString(),views:{}};await P(r.build,{recursive:!0}),await D(r.buildManifest,`${JSON.stringify(l,null,2)}
4
- `);let g=Math.round(performance.now()-t);console.log(`[mcp-use] built ${v(e.cwd,n)} \u2192 ${v(e.cwd,r.build)}/${y} (${g}ms)`);return}await fe(r.build,{recursive:!0,force:!0});let M=w(r.build,"views");await P(M,{recursive:!0}),d??=await S(e.cwd,r.cache,!1);let _,R={},x=he();try{_=u??await Y(d.environments.ssr,n);for(let l of s){let g=await Me(l,{cwd:e.cwd,cacheDir:r.cache,viewsOutDir:M,userViteConfig:f,sourceMaps:p,inline:m});x!==void 0&&!m&&(g=ve(g,l.name,x,_)),R[l.name]=g}x!==void 0&&!m&&(console.log(`[mcp-use] MCP_ASSETS_URL set \u2014 manifest uses CDN URLs; upload ${v(e.cwd,M)}/ to your asset host.`),_!=="/mcp"&&console.log(`[mcp-use] CDN manifest uses basePath ${_} from server entry`)),await ee(e.cwd,w(M,"public")),await A(d.environments.ssr,n,R,s)}finally{await d.close()}let ne=await te(r.cache,n,R,s);await B({root:e.cwd,configFile:!1,envDir:!1,publicDir:!1,logLevel:"warn",cacheDir:r.cache,resolve:{tsconfigPaths:!0,alias:C(e.cwd)},oxc:{jsx:{runtime:"automatic"}},plugins:[L(e.cwd),k()],build:{ssr:ne,outDir:r.build,emptyOutDir:!1,target:"node22",sourcemap:p,minify:!1,rollupOptions:{output:{format:"es",entryFileNames:y}}},ssr:{...E(e.cwd),target:"node"}});let ie={buildId:Z(8).toString("hex"),entryPoint:y,createdAt:new Date().toISOString(),views:R};await P(r.build,{recursive:!0}),await D(r.buildManifest,`${JSON.stringify(ie,null,2)}
5
- `);let se=Math.round(performance.now()-t),oe=s.map(l=>l.name).join(", ");console.log(`[mcp-use] built ${v(e.cwd,n)} + views (${oe}) \u2192 ${v(e.cwd,r.build)}/${y} (${se}ms)`)}export{_e as runBuild};
1
+ import{a as I,b as j,c as N,d as R,e as k,f as F,g as W,h as q,k as S,n as H}from"../chunk-YMYENQ4W.js";import{a as $,b as L,c as T,d as E}from"../chunk-7G4TXPP4.js";import{a as C,b as O}from"../chunk-FLGSKQGU.js";import{randomBytes as Z}from"crypto";import{existsSync as re}from"fs";import{cp as de,mkdir as x,rm as fe,writeFile as D}from"fs/promises";import{join as w,relative as v,resolve as pe}from"path";import me from"@tailwindcss/vite";import ge from"@vitejs/plugin-react";import{build as B}from"vite";import{createServerModuleRunner as J}from"vite";var ce="/mcp",z="http://localhost:3000",h="__mcpUseV1CompatServer";function G(){return globalThis[h]}async function ue(e,t,o){let n=o.filter(r=>r.legacy===!0);if(n.length===0)return;if(typeof t.__registerLegacyViews!="function")throw new Error("Legacy resources/*/widget.tsx views require the temporary mcp-use/server compatibility entry.");let i={};for(let r of n)i[r.name]=await e.import(R(r.entryPath));t.__registerLegacyViews(i)}async function V(e,t){let o=J(e,{hmr:!1,sourcemapInterceptor:"node"}),n=process.env.MCP_URL,i=process.env.MCP_USE_CLI_IMPORT;try{process.env.MCP_USE_CLI_IMPORT="1",n===void 0&&(process.env.MCP_URL=z),delete globalThis[h];let a=(await o.import(t)).default??G();if(a===null||typeof a!="object")throw new Error("The server entry must default-export the MCPServer instance.");return{basePath:a.basePath??ce,supportsLegacyViews:typeof a.__registerLegacyViews=="function"}}finally{delete globalThis[h],n===void 0?delete process.env.MCP_URL:process.env.MCP_URL=n,i===void 0?delete process.env.MCP_USE_CLI_IMPORT:process.env.MCP_USE_CLI_IMPORT=i,await o.close()}}async function Y(e,t){return(await V(e,t)).basePath}async function U(e,t,o,n=[]){let i=J(e,{hmr:!1,sourcemapInterceptor:"node"}),r=process.env.MCP_USE_CLI_IMPORT,a=process.env.MCP_URL;try{process.env.MCP_USE_CLI_IMPORT="1",a===void 0&&(process.env.MCP_URL=z),delete globalThis[h];let s=(await i.import(t)).default??G();if(s===null||typeof s!="object")throw new Error("The server entry must default-export the MCPServer instance.");if(typeof s.__primeViews!="function")throw new Error("The entry's default export does not support __primeViews.");await ue(i,s,n),s.__primeViews(o),s.__mount()}finally{delete globalThis[h],r===void 0?delete process.env.MCP_USE_CLI_IMPORT:process.env.MCP_USE_CLI_IMPORT=r,a===void 0?delete process.env.MCP_URL:process.env.MCP_URL=a,await i.close()}}function le(e){return e.replace(/\/+$/,"")}function K(e){return le(e)}import{hostHeaderValidationResponse as Ce,originValidationResponse as $e}from"@modelcontextprotocol/server";function Q(e,t){let o=t.replace(/^\/+/,"");return e==="/"?`/${o}`:`${e}/${o}`}function X(e,t){return`${Q(e,`_mcp-use/views/${t}`)}/`}var y="index.js",we="entry-wrapper.ts",ye=100*1024*1024;async function ee(e,t){let o=w(e,"public");re(o)&&await de(o,t,{recursive:!0})}async function te(e,t,o,n){let i=w(e,we);await x(e,{recursive:!0});let r=JSON.stringify(o),a=n.filter(s=>s.legacy===!0),c=a.length>0?[`import ${JSON.stringify(t)};`,'import { registerViews } from "mcp-use";']:[`import * as serverModule from ${JSON.stringify(t)};`,'import { registerViews } from "mcp-use";'];if(a.forEach((s,f)=>{c.push(`import * as legacyWidget${f} from ${JSON.stringify(R(s.entryPath))};`)}),c.push(a.length>0?"const server = globalThis.__mcpUseV1CompatServer;":"const server = serverModule.default;",'if (!server) throw new Error("The server entry must default-export MCPServer or use the deprecated mcp-use/server compatibility entry.");'),a.length>0){let s=a.map((f,p)=>`${JSON.stringify(f.name)}: legacyWidget${p}`).join(", ");c.push(`server.__registerLegacyViews?.({ ${s} });`)}return c.push(`server[registerViews] ? server[registerViews](${r}) : server.__primeViews(${r});`,"export default server;",""),await D(i,c.join(`
2
+ `)),i}function he(){let e=process.env.MCP_ASSETS_URL;if(!(e===void 0||e.trim()===""))try{return K(new URL(e).href.replace(/\/$/,""))}catch{return}}function A(e,t,o,n){let i=e.replace(/^\/+/,"");return`${o}${X(n,t)}${i}`}function ve(e,t,o,n){return e.kind!=="external"?e:{...e,entry:A(e.entry,t,o,n),css:e.css.map(i=>A(i,t,o,n)),...e.scripts!==void 0&&{scripts:e.scripts.map(i=>A(i,t,o,n))}}}async function be(e,t){let o=w(t.viewsOutDir,e.name),n=await B({root:t.cwd,configFile:t.userViteConfig,envDir:!1,publicDir:!1,logLevel:"warn",cacheDir:t.cacheDir,resolve:{tsconfigPaths:!0,alias:{tailwindcss:j()}},oxc:{jsx:{runtime:"automatic"}},plugins:[me(),ge(),H({getViews:()=>[e]})],build:{outDir:o,emptyOutDir:!0,write:!t.inline,target:"es2022",sourcemap:t.inline?!1:t.sourceMaps,minify:!0,cssCodeSplit:!1,chunkSizeWarningLimit:1e3,assetsInlineLimit:ye,rollupOptions:{input:{[e.name]:q(e.name)},output:{format:"es",codeSplitting:!t.inline,entryFileNames:"assets/[name]-[hash].js",chunkFileNames:"assets/[name]-[hash].js",assetFileNames:"assets/[name]-[hash][extname]"}}},base:"./"}),i=Array.isArray(n)?n[0]:n;if(i===void 0||!("output"in i))throw new Error(`Client build for view "${e.name}" produced no output.`);let r=i.output,a=Array.isArray(r)?r:Object.values(r),c,s,f,p=[];for(let m of a){if(typeof m!="object"||m===null||!("fileName"in m)||typeof m.fileName!="string")continue;let u=m;u.type==="chunk"&&u.isEntry===!0?(c=u.fileName,f=u.code):u.type==="asset"&&u.fileName.endsWith(".css")&&(s=u.fileName,typeof u.source=="string"?p.push(u.source):u.source instanceof Uint8Array&&p.push(new TextDecoder().decode(u.source)))}if(c===void 0)throw new Error(`Client build produced no entry chunk for view "${e.name}".`);if(t.inline){if(f===void 0)throw new Error(`Client build produced no entry source for view "${e.name}".`);return{kind:"inline",js:f,css:p.join(`
3
+ `)}}return{kind:"external",entry:c.replace(/^\/+/,""),css:s!==void 0?[s.replace(/^\/+/,"")]:[]}}async function Me(e){let t=performance.now();T(e.cwd,"production");let o=e.mcpDir===void 0?e.cwd:pe(e.cwd,e.mcpDir),n=e.entry===void 0?C(o):C(e.cwd,e.entry),i=await O(e.cwd,n);(i==="created"||i==="updated")&&console.log(`[mcp-use] ${i} mcp-env.d.ts`);let r=N(e.cwd),a=e.viewsDir??(e.mcpDir===void 0?void 0:w(e.mcpDir,"views"));re(F(e.cwd,a))||console.log("[mcp-use] views directory not configured.");let c=W(e.cwd,a,{includeLegacy:!0}),s=c,f=I(e.cwd),p=e.sourceMaps===!0,m=e.inline===!0,d,u;if(c.some(l=>l.legacy===!0)){d=await S(e.cwd,r.cache,!1);let l;try{l=await V(d.environments.ssr,n)}catch(g){throw await d.close(),g}u=l.basePath,l.supportsLegacyViews||(s=c.filter(g=>g.legacy!==!0))}if(s.length===0){d??=await S(e.cwd,r.cache,!1);try{await U(d.environments.ssr,n,{},s);let ae=await te(r.cache,n,{},s);await B({root:e.cwd,configFile:!1,envDir:!1,publicDir:!1,logLevel:"warn",cacheDir:r.cache,resolve:{tsconfigPaths:!0,alias:$(e.cwd)},plugins:[E(e.cwd)],build:{ssr:ae,outDir:r.build,emptyOutDir:!0,target:"node22",sourcemap:p,minify:!1,rollupOptions:{output:{format:"es",entryFileNames:y}}},ssr:{...L(e.cwd),target:"node"}})}finally{await d?.close()}await ee(e.cwd,w(r.build,"views/public"));let l={buildId:Z(8).toString("hex"),entryPoint:y,createdAt:new Date().toISOString(),views:{}};await x(r.build,{recursive:!0}),await D(r.buildManifest,`${JSON.stringify(l,null,2)}
4
+ `);let g=Math.round(performance.now()-t);console.log(`[mcp-use] built ${v(e.cwd,n)} \u2192 ${v(e.cwd,r.build)}/${y} (${g}ms)`);return}await fe(r.build,{recursive:!0,force:!0});let b=w(r.build,"views");await x(b,{recursive:!0}),d??=await S(e.cwd,r.cache,!1);let M,_={},P=he();try{M=u??await Y(d.environments.ssr,n);for(let l of s){let g=await be(l,{cwd:e.cwd,cacheDir:r.cache,viewsOutDir:b,userViteConfig:f,sourceMaps:p,inline:m});P!==void 0&&!m&&(g=ve(g,l.name,P,M)),_[l.name]=g}P!==void 0&&!m&&(console.log(`[mcp-use] MCP_ASSETS_URL set \u2014 manifest uses CDN URLs; upload ${v(e.cwd,b)}/ to your asset host.`),M!=="/mcp"&&console.log(`[mcp-use] CDN manifest uses basePath ${M} from server entry`)),await ee(e.cwd,w(b,"public")),await U(d.environments.ssr,n,_,s)}finally{await d.close()}let ne=await te(r.cache,n,_,s);await B({root:e.cwd,configFile:!1,envDir:!1,publicDir:!1,logLevel:"warn",cacheDir:r.cache,resolve:{tsconfigPaths:!0,alias:$(e.cwd)},oxc:{jsx:{runtime:"automatic"}},plugins:[E(e.cwd),k()],build:{ssr:ne,outDir:r.build,emptyOutDir:!1,target:"node22",sourcemap:p,minify:!1,rollupOptions:{output:{format:"es",entryFileNames:y}}},ssr:{...L(e.cwd),target:"node"}});let ie={buildId:Z(8).toString("hex"),entryPoint:y,createdAt:new Date().toISOString(),views:_};await x(r.build,{recursive:!0}),await D(r.buildManifest,`${JSON.stringify(ie,null,2)}
5
+ `);let se=Math.round(performance.now()-t),oe=s.map(l=>l.name).join(", ");console.log(`[mcp-use] built ${v(e.cwd,n)} + views (${oe}) \u2192 ${v(e.cwd,r.build)}/${y} (${se}ms)`)}export{Me as runBuild};
@@ -1 +1 @@
1
- import{a,b,c,d}from"../chunk-KL7RFX6A.js";import"../chunk-VSIT62BK.js";import"../chunk-LNASFQWW.js";export{c as openDirectConnection,b as openSavedConnection,d as parseMcpArguments,a as runClient};
1
+ import{a,b,c,d}from"../chunk-ISAAAHEM.js";import"../chunk-VUVLJMYY.js";import"../chunk-LNASFQWW.js";export{c as openDirectConnection,b as openSavedConnection,d as parseMcpArguments,a as runClient};
@@ -1 +1,73 @@
1
- import{g as O}from"../chunk-3TSFYSEY.js";import{a as c,b as d,c as k,d as R,e as _,f as E,g as U,h as j,i as A,j as L}from"../chunk-VSIT62BK.js";import"../chunk-LNASFQWW.js";import{execFile as N}from"child_process";import{readFile as D}from"fs/promises";import{basename as J,isAbsolute as S,join as F,relative as H,resolve as v}from"path";import{promisify as G,parseArgs as M}from"util";var W=G(N);async function nt(n){let e=k(n);try{let{values:t,positionals:o}=M({args:[...n],allowPositionals:!0,strict:!0,options:{org:{type:"string"},name:{type:"string"},branch:{type:"string"},"root-dir":{type:"string"},region:{type:"string"},env:{type:"string",multiple:!0},"env-file":{type:"string"},"build-command":{type:"string"},"start-command":{type:"string"},dockerfile:{type:"string"},new:{type:"boolean"},open:{type:"boolean"},yes:{type:"boolean"},json:{type:"boolean"}}});if(o.length>1)throw new c("Usage: mcp-use deploy [path] [options]");let r=v(o[0]??process.cwd()),a=await b(r,["rev-parse","--show-toplevel"]),i=await b(a,["remote","get-url","origin"]),s=B(i),g=t.branch??await b(a,["branch","--show-current"]);if(g==="")throw new d("detached_head","Cannot infer a branch from detached HEAD; pass --branch.");z(a,t["root-dir"],"--root-dir"),z(a,t.dockerfile,"--dockerfile");let{api:l,organizationId:f}=await O(t.org),I=F(r,".mcp-use","cloud","link.json"),p=await A(I,null),q=t.new===!0||p===null;if(t.new===!0&&!await E("Create a new cloud server for this project?",{yes:t.yes===!0,json:e}))return 0;let u,w,h;if(!q&&p!==null){if(p.organizationId!==f)throw new d("organization_mismatch","The linked server belongs to another organization. Pass --new to create one.");u=p.serverId,w=p.serverSlug,h=(await l.request("/deployments",{method:"POST",body:JSON.stringify({serverId:u,branch:g,trigger:"manual"})})).id}else{let y=await l.request(`/github/installations?organizationId=${encodeURIComponent(f)}`),$=await K(l,y.installations,s);if($===void 0)throw new d("github_access_required",`The mcp-use GitHub App cannot access ${s}. Configure repository access in the cloud dashboard and retry.`);let P=await Q(r,t["env-file"],t.env??[]),m=await l.request("/servers",{method:"POST",body:JSON.stringify({type:"github",organizationId:f,installationId:$.installationId,name:t.name??J(s),repoFullName:s,branch:g,...t["root-dir"]!==void 0?{rootDir:t["root-dir"]}:{},...t.region!==void 0?{region:t.region}:{},...t["build-command"]!==void 0?{buildCommand:t["build-command"]}:{},...t["start-command"]!==void 0?{startCommand:t["start-command"]}:{},...t.dockerfile!==void 0?{dockerfilePath:t.dockerfile}:{},...Object.keys(P).length>0?{env:P}:{}})});if(m.deploymentId===null)throw new d("deployment_not_created","Server was created but no deployment was started.",{serverId:m.server.id});u=m.server.id,w=m.server.slug,h=m.deploymentId,await L(I,{organizationId:f,serverId:u,serverSlug:w,repository:s})}let C=`${process.env.MCP_USE_CLOUD_WEB_URL??"https://manufact.com"}/${encodeURIComponent(w??u)}`,x={serverId:u,deploymentId:h,status:"pending",webUrl:C};return t.open===!0&&U(C),R(x,e,`Deployment ${h} started for ${s}.`),0}catch(t){return _(t instanceof TypeError?new c(t.message):t,e)}}async function b(n,e){try{let{stdout:t}=await W("git",e,{cwd:n});return t.trim()}catch{throw new d("git_required",`Could not run git ${e.join(" ")} in ${n}.`)}}function B(n){let e=n.match(/github\.com[/:]([^/\s]+)\/([^/\s]+?)(?:\.git)?$/);if(e?.[1]===void 0||e[2]===void 0)throw new d("unsupported_remote","The origin remote must be a GitHub repository.");return`${e[1]}/${e[2]}`}async function K(n,e,t){let[o,r]=t.split("/"),a=[...e].sort((i,s)=>{let g=i.account?.login?.toLowerCase()===o.toLowerCase(),l=s.account?.login?.toLowerCase()===o.toLowerCase();return Number(l)-Number(g)});for(let i of a)try{if((await n.request(`/github/installations/${encodeURIComponent(i.installationId)}/repos/${encodeURIComponent(o)}/${encodeURIComponent(r)}/access`)).hasAccess)return i}catch{}}function z(n,e,t){if(e===void 0)return;if(S(e))throw new c(`${t} must be repository-relative.`);let o=v(n,e),r=H(n,o);if(r.startsWith("..")||S(r))throw new c(`${t} must not escape the repository.`)}async function Q(n,e,t){let o={};if(e!==void 0){let r=v(n,e);if(!await j(r))throw new c(`Environment file not found: ${e}`);for(let a of(await D(r,"utf8")).split(/\r?\n/)){let i=a.trim();i===""||i.startsWith("#")||T(o,i)}}for(let r of t)T(o,r);return o}function T(n,e){let t=e.indexOf("=");if(t<=0)throw new c(`Invalid environment value: ${e}`);n[e.slice(0,t)]=e.slice(t+1)}export{nt as runDeploy};
1
+ import{a as N,h as K}from"../chunk-3XW44DRS.js";import{a as h,b as p,c as v,d as M,e as J,f as F,g as V,h as Y,i as E,j as W,k as U}from"../chunk-VUVLJMYY.js";import"../chunk-LNASFQWW.js";import{execFile as Se}from"child_process";import{createReadStream as Ce}from"fs";import{appendFile as re,lstat as Ie,opendir as je,readFile as T,writeFile as $e}from"fs/promises";import{basename as se,isAbsolute as Z,join as k,relative as _e,resolve as ae}from"path";import{createInterface as ce}from"readline/promises";import{parseArgs as Re,promisify as Ge}from"util";import{createGzip as Ee}from"zlib";var de=Ge(Se),X=80*1024*1024,Ae=new Set([".git","node_modules","dist","build",".next",".turbo",".vercel",".cache",".parcel-cache",".pytest_cache",".ruff_cache",".mypy_cache","__pycache__",".venv","venv","coverage",".nyc_output",".output","out","target",".mcp-use"]),De=`Deploy an MCP server to Manufact Cloud.
2
+
3
+ Usage:
4
+ mcp-use deploy [path] [options]
5
+
6
+ Source modes:
7
+ GitHub (default) Deploy the current origin. If none exists, an interactive
8
+ run can create a private repository; --yes authorizes the
9
+ same flow without prompts.
10
+ Managed upload Pass --no-github on the first deploy to upload local
11
+ source. Linked managed projects auto-detect this on retry.
12
+
13
+ Options:
14
+ --org <id-or-slug> Target organization (default: active organization)
15
+ --name <name> Cloud server/repository name (default: project name)
16
+ --branch <name> Branch (default: current Git branch, or main)
17
+ --root-dir <path> Project root inside the repository/upload directory
18
+ --region <region> Cloud region identifier
19
+ --env <KEY=VALUE> Environment variable; repeatable
20
+ --env-file <path> Load environment variables from a file
21
+ --build-command <cmd> Override the build command
22
+ --start-command <cmd> Override the start command
23
+ --dockerfile <path> Dockerfile path relative to the selected source root
24
+ --watch-paths <glob> GitHub auto-deploy path filter; repeatable
25
+ --wait-for-ci Wait for other GitHub checks before auto-deploy
26
+ --no-github Upload local source to a managed private repository
27
+ --new Create a new server instead of using the local link
28
+ --open Open the server page after a successful deployment
29
+ -y, --yes Authorize confirmations and Git/repository mutations
30
+ --json Emit exactly one JSON result or error; never prompt
31
+ -h, --help Show this help without Git, auth, or network access
32
+
33
+ Automation:
34
+ --json does not authorize mutations. Use --json --yes for headless GitHub
35
+ repository creation, or --json --no-github for a managed source upload.
36
+ --new requires --yes in JSON or non-interactive environments.
37
+
38
+ Incompatible combinations:
39
+ --open cannot be combined with --json because JSON mode never opens a browser.
40
+ --no-github cannot replace a linked GitHub server in place; add --new --yes
41
+ to create a separate managed-source server.
42
+ --watch-paths and --wait-for-ci are GitHub-only.
43
+
44
+ Managed archive:
45
+ Uploads the selected project without .git, dependencies, build output,
46
+ .mcp-use, .env*, caches, coverage, OS metadata, or symbolic links.
47
+ The compressed archive limit is 80 MB.
48
+
49
+ Examples:
50
+ mcp-use deploy
51
+ mcp-use deploy --yes
52
+ mcp-use deploy --no-github
53
+ mcp-use deploy --no-github --json
54
+ mcp-use deploy --json --yes
55
+ mcp-use deploy --env-file .env.production --open
56
+
57
+ Exit codes:
58
+ 0 Success or help
59
+ 1 Git, API, upload, or deployment failure
60
+ 2 Invalid arguments or an explicit headless choice is required`;async function ut(t){let e=M(t);try{let{values:n,positionals:o}=Te(t);if(n.help===!0)return process.stdout.write(`${De}
61
+ `),0;if(n.json===!0&&n.open===!0)throw new v("invalid_argument_combination","--open cannot be combined with --json; JSON mode never opens a browser.",{nextSteps:[{description:"Deploy as JSON without opening a browser",command:"mcp-use deploy --json"},{description:"Deploy and open the server page interactively",command:"mcp-use deploy --open"}]});let r=ae(o[0]??process.cwd()),s=k(r,".mcp-use","cloud","link.json");if(n.new===!0&&!await V("Create a new cloud server for this project?",{yes:n.yes===!0,json:e}))return 0;let{api:i,organizationId:c}=await K(n.org),a=await W(s,null),u=n.new===!0||a===null;if(!u&&a!==null&&a.organizationId!==c)throw new p("organization_mismatch","The linked server belongs to another organization. Pass --new --yes to create one.",{nextSteps:[{description:"Create a server in the selected organization",command:"mcp-use deploy --new --yes"}]});let l=!u&&a!==null&&await ze(i,a);if(n["no-github"]===!0&&!u&&a!==null&&!l)throw new v("source_mode_conflict","This project is linked to a GitHub-backed server; managed upload cannot replace its source in place.",{serverId:a.serverId,nextSteps:[{description:"Redeploy the linked GitHub server",command:"mcp-use deploy"},{description:"Create a separate managed-source server",command:"mcp-use deploy --no-github --new --yes"}]});if(n["no-github"]===!0||l){if(n["watch-paths"]!==void 0||n["wait-for-ci"]===!0)throw new v("source_mode_conflict","--watch-paths and --wait-for-ci are available only for GitHub deployments.",{nextSteps:[{description:"Upload managed source without GitHub trigger options",command:"mcp-use deploy --no-github"},{description:"Deploy through GitHub with trigger options",command:"mcp-use deploy --yes --watch-paths <glob>"}]});return await Oe({api:i,organizationId:c,cwd:r,linkPath:s,existing:u?null:a,values:n,json:e})}return await Ue({api:i,organizationId:c,cwd:r,linkPath:s,existing:u?null:a,values:n,json:e})}catch(n){return F(n instanceof TypeError?new h(n.message):n,e)}}function Te(t){let{values:e,positionals:n}=Re({args:[...t],allowPositionals:!0,strict:!0,options:{org:{type:"string"},name:{type:"string"},branch:{type:"string"},"root-dir":{type:"string"},region:{type:"string"},env:{type:"string",multiple:!0},"env-file":{type:"string"},"build-command":{type:"string"},"start-command":{type:"string"},dockerfile:{type:"string"},"watch-paths":{type:"string",multiple:!0},"wait-for-ci":{type:"boolean"},"no-github":{type:"boolean"},new:{type:"boolean"},open:{type:"boolean"},yes:{type:"boolean",short:"y"},json:{type:"boolean"},help:{type:"boolean",short:"h"}}});if(n.length>1)throw new h("Usage: mcp-use deploy [path] [options]");return e["watch-paths"]!==void 0&&(e["watch-paths"]=Ne(e["watch-paths"])),{values:e,positionals:n}}function Ne(t){if(t.length===1&&t[0]==="")return[];if(t.length>32)throw new h("--watch-paths accepts at most 32 patterns.");if(t.some(e=>e===""))throw new h("--watch-paths accepts an empty value only by itself to clear all patterns.");if(t.some(e=>e.length>512))throw new h("--watch-paths patterns may not exceed 512 characters.");return t}async function Oe(t){let{api:e,organizationId:n,cwd:o,linkPath:r,existing:s,values:i,json:c}=t,a=o,u=q(o,i["root-dir"]??".","--root-dir");if(!await E(u))throw new h(`Project directory not found: ${u}`);L(u,i.dockerfile,"--dockerfile"),await et(a);let l=await he(a,i["env-file"],i.env??[]),y=await Ze(a);He(y.byteLength);let w=i.branch??"main",I=i.name??await ye(u),m,g,P;if(s!==null){m=s.serverId,g=s.serverSlug,await le(e,m,i),await ue(e,m,l,i.branch);let d=new FormData;oe(d,y),d.set("branch",w),d.set("commitMessage","Redeploy from mcp-use CLI"),await e.multipartRequest(`/servers/${encodeURIComponent(m)}/source`,d),P=(await e.request("/deployments",{method:"POST",body:JSON.stringify({serverId:m,branch:w,trigger:"redeploy"})})).id}else{let d=new FormData;oe(d,y),d.set("organizationId",n),d.set("managed","true"),d.set("name",I),d.set("repoName",we(I)),d.set("private","true"),d.set("branch",w),d.set("commitMessage","Deploy from mcp-use CLI"),i.region!==void 0&&d.set("region",i.region),i["root-dir"]!==void 0&&d.set("rootDir",i["root-dir"]),i["build-command"]!==void 0&&d.set("buildCommand",i["build-command"]),i["start-command"]!==void 0&&d.set("startCommand",i["start-command"]),i.dockerfile!==void 0&&d.set("dockerfilePath",i.dockerfile),Object.keys(l).length>0&&d.set("env",JSON.stringify(l));let f=await e.multipartRequest("/servers",d);if(f.deploymentId===null)throw ve(f.server.id);m=f.server.id,g=f.server.slug,P=f.deploymentId}return await U(r,{organizationId:n,serverId:m,...g!==void 0?{serverSlug:g}:{},sourceType:"managed"}),await pe(a),ke({sourceType:"managed",serverId:m,...g!==void 0?{serverSlug:g}:{},deploymentId:P,label:"managed source",values:i,json:c})}function He(t){if(!(t<=X))throw new p("archive_too_large",`Project archive is ${(t/1024/1024).toFixed(2)} MB; the maximum is 80 MB.`,{sizeBytes:t,maxBytes:X,nextSteps:[{description:"Exclude large generated files and retry",command:"mcp-use deploy --no-github"}]})}async function Ue(t){let{api:e,organizationId:n,cwd:o,linkPath:r,existing:s,values:i,json:c}=t,a=await ee(o),u,l;if(!a.isRepository||a.remote===void 0){if(a.unavailable===!0)throw new p("git_unavailable","Git is not installed or could not be executed.",{nextSteps:[{description:"Deploy without GitHub",command:"mcp-use deploy --no-github"}]});await Le(i,c);let d=await Q(e,n);l=await Be(d,i,c);let f=i.name??await ye(o),R=we(f),G;try{G=await e.request(`/github/installations/${encodeURIComponent(l.installationId)}/repos`,{method:"POST",body:JSON.stringify({name:R,private:!0,org:l.account?.login??void 0})})}catch(x){throw new p("github_repository_creation_failed",`Could not create the private GitHub repository ${R}.`,{account:l.account?.login??null,cause:x instanceof Error?x.message:String(x),nextSteps:[{description:"Retry with a unique repository name",command:"mcp-use deploy --name <unique-name> --yes"},{description:"Deploy without GitHub",command:"mcp-use deploy --no-github"}]})}try{await qe(o,a,G.cloneUrl)}catch(x){let S=x instanceof p?x:B(x,o),Pe=S.details!==null&&typeof S.details=="object"&&!Array.isArray(S.details)?S.details:{},H=Me(S.details);throw H.some(xe=>xe.command==="mcp-use deploy --yes")||H.push({description:"Retry using the repository already created",command:"mcp-use deploy --yes"}),new p(S.code,S.message,{...Pe,repository:G.fullName,url:G.htmlUrl,nextSteps:H})}a=await ee(o),u=G.fullName}else u=We(a.remote);let y=a.root??o,w=i.branch??a.branch;if(w===void 0||w===""||w==="HEAD")throw new p("detached_head","Cannot infer a branch from detached HEAD; pass --branch.",{nextSteps:[{description:"Deploy an explicit branch",command:"mcp-use deploy --branch <branch>"}]});L(y,i["root-dir"],"--root-dir"),L(y,i.dockerfile,"--dockerfile");let I=await he(o,i["env-file"],i.env??[]);a.dirty===!0&&await Fe(y,w,i,c);let m,g,P;if(s!==null)m=s.serverId,g=s.serverSlug,await le(e,m,i),await ue(e,m,I,i.branch),P=(await e.request("/deployments",{method:"POST",body:JSON.stringify({serverId:m,branch:w,trigger:"manual"})})).id;else{let d=l===void 0?await Q(e,n):[l];if(l??=await Ke(e,d,u),l===void 0){let R=`${N()}/settings`;throw new p(d.length===0?"github_installation_required":"github_access_required",d.length===0?"No GitHub App installation is connected to this organization.":`The mcp-use GitHub App cannot access ${u}.`,{repository:u,url:R,nextSteps:[{description:"Configure GitHub access",command:R},{description:"Retry deployment",command:"mcp-use deploy"}]})}let f=await e.request("/servers",{method:"POST",body:JSON.stringify({type:"github",organizationId:n,installationId:l.id??l.installationId,name:i.name??se(u),repoFullName:u,branch:w,...i["root-dir"]!==void 0?{rootDir:i["root-dir"]}:{},...i.region!==void 0?{region:i.region}:{},...i["build-command"]!==void 0?{buildCommand:i["build-command"]}:{},...i["start-command"]!==void 0?{startCommand:i["start-command"]}:{},...i.dockerfile!==void 0?{dockerfilePath:i.dockerfile}:{},...i["watch-paths"]!==void 0?{watchPaths:i["watch-paths"]}:{},...i["wait-for-ci"]!==void 0?{waitForCi:i["wait-for-ci"]}:{},...Object.keys(I).length>0?{env:I}:{}})});if(f.deploymentId===null)throw ve(f.server.id);m=f.server.id,g=f.server.slug,P=f.deploymentId}return await U(r,{organizationId:n,serverId:m,...g!==void 0?{serverSlug:g}:{},repository:u,sourceType:"github"}),await pe(y),ke({sourceType:"github",serverId:m,...g!==void 0?{serverSlug:g}:{},deploymentId:P,label:u,values:i,json:c})}async function ue(t,e,n,o){if(Object.keys(n).length===0)return;let r=o===void 0?"":`?branch=${encodeURIComponent(o)}`,s=await t.request(`/servers/${encodeURIComponent(e)}/env-variables${r}`),i=new Map(s.map(c=>[c.key,c]));await Promise.all(Object.entries(n).map(async([c,a])=>{let u=i.get(c),l=JSON.stringify({key:c,value:a,branch:o??null,environments:o===void 0?["production"]:["preview"]});u===void 0?await t.request(`/servers/${encodeURIComponent(e)}/env-variables`,{method:"POST",body:l}):await t.request(`/servers/${encodeURIComponent(e)}/env-variables/${encodeURIComponent(u.id)}`,{method:"PATCH",body:l})}))}async function le(t,e,n){let o={...n["root-dir"]!==void 0?{rootDir:n["root-dir"]}:{},...n["build-command"]!==void 0?{buildCommand:n["build-command"]}:{},...n["start-command"]!==void 0?{startCommand:n["start-command"]}:{},...n.dockerfile!==void 0?{dockerfilePath:n.dockerfile}:{}},r={...n.name!==void 0?{name:n.name}:{},...n.branch!==void 0?{productionBranch:n.branch}:{},...n.region!==void 0?{region:n.region}:{},...n["watch-paths"]!==void 0?{watchPaths:n["watch-paths"]}:{},...n["wait-for-ci"]!==void 0?{waitForCi:n["wait-for-ci"]}:{},...Object.keys(o).length>0?{config:o}:{}};Object.keys(r).length!==0&&await t.request(`/servers/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(r)})}async function ze(t,e){if(e.sourceType!==void 0)return e.sourceType==="managed";if(e.repository===void 0)return!0;try{return(await t.request(`/servers/${encodeURIComponent(e.serverId)}`)).connectedRepository?.isManaged===!0}catch{return!1}}async function Le(t,e){if(t.yes===!0)return;if(e||!process.stdin.isTTY)throw new v("deployment_mode_required","No GitHub origin was found. Choose a deployment mode explicitly.",{nextSteps:[{description:"Upload local source without GitHub",command:"mcp-use deploy --no-github"},{description:"Create a private GitHub repository and push",command:"mcp-use deploy --yes"}]});if(!await be("No GitHub origin was found. Create a private repository and push this project?",!0))throw new v("deployment_mode_required","Deployment cancelled. Choose a deployment mode.",{nextSteps:[{description:"Upload local source without GitHub",command:"mcp-use deploy --no-github"},{description:"Retry GitHub setup",command:"mcp-use deploy"}]})}async function Q(t,e){let n=await t.request(`/github/installations?organizationId=${encodeURIComponent(e)}`);if(n.installations.length===0){let o=`${N()}/settings`;throw new p("github_installation_required","No GitHub App installation is connected to this organization.",{url:o,nextSteps:[{description:"Connect GitHub in the cloud dashboard",command:o},{description:"Retry deployment after connecting GitHub",command:"mcp-use deploy"},{description:"Deploy without GitHub",command:"mcp-use deploy --no-github"}]})}return n.installations}async function Be(t,e,n){let o=[...t].sort((s,i)=>{let c=s.account?.type?.toLowerCase()==="organization",a=i.account?.type?.toLowerCase()==="organization";return Number(a)-Number(c)});if(o.length===1||e.yes===!0)return o[0];if(n||!process.stdin.isTTY)throw new v("github_installation_required","Multiple GitHub installations are available; pass --yes to select deterministically.",{nextSteps:[{description:"Use the default organization installation",command:"mcp-use deploy --yes"}]});process.stdout.write(`Choose the GitHub account for the new repository:
62
+ `);for(let[s,i]of o.entries())process.stdout.write(` ${s+1}. ${i.account?.login??i.installationId}
63
+ `);let r=ce({input:process.stdin,output:process.stdout});try{let s=await r.question("Account [1]: "),i=s.trim()===""?0:Number(s)-1;if(!Number.isInteger(i)||i<0||i>=o.length)throw new h("Invalid GitHub account selection.");return o[i]}finally{r.close()}}async function qe(t,e,n){try{await Je(t),e.isRepository||await b(t,["init"]),await b(t,["remote","add","origin",n]),await b(t,["add","."]),(await j(t,["diff","--cached","--quiet"])).ok||await b(t,["commit","-m","Initial commit"]),await b(t,["branch","-M","main"]),await b(t,["push","-u","origin","main"])}catch(o){throw B(o,t)}}function Me(t){if(t===null||typeof t!="object")return[];let e=t.nextSteps;return Array.isArray(e)?e.filter(o=>o!==null&&typeof o=="object"&&"description"in o&&typeof o.description=="string"&&"command"in o&&typeof o.command=="string"):[]}async function Je(t){let e=k(t,".gitignore"),n="";try{n=await T(e,"utf8")}catch(o){if(o.code!=="ENOENT")throw o}n.split(/\r?\n/).map(o=>o.trim()).includes(".mcp-use/")||(n===""?await $e(e,`.mcp-use/
64
+ `,"utf8"):await re(e,`${n.endsWith(`
65
+ `)?"":`
66
+ `}.mcp-use/
67
+ `))}async function pe(t){let e=k(t,".git","info","exclude");if(await E(e))try{let n=await T(e,"utf8");if(n.split(/\r?\n/).map(o=>o.trim()).includes(".mcp-use/"))return;await re(e,`${n.endsWith(`
68
+ `)||n===""?"":`
69
+ `}.mcp-use/
70
+ `)}catch{}}async function Fe(t,e,n,o){if(n.yes!==!0){if(o||!process.stdin.isTTY)throw new v("git_changes_require_confirmation","The repository has uncommitted changes.",{nextSteps:[{description:"Authorize committing and pushing the changes",command:"mcp-use deploy --yes"},{description:"Commit the changes yourself",command:"git add . && git commit && git push"}]});if(!await be("Commit and push the current changes before deploying?",!0))return}try{await b(t,["add","."]),await b(t,["commit","-m","Deploy changes"]),await b(t,["push","origin",e])}catch(r){throw B(r,t)}}async function ee(t){let e=await j(t,["rev-parse","--is-inside-work-tree"]);if(!e.ok){if(e.unavailable!==!0&&!Ve(e))throw A("git rev-parse --is-inside-work-tree",e);return{isRepository:!1,...e.unavailable!==void 0?{unavailable:e.unavailable}:{}}}let[n,o,r,s]=await Promise.all([j(t,["rev-parse","--show-toplevel"]),j(t,["remote","get-url","origin"]),j(t,["branch","--show-current"]),j(t,["status","--porcelain"])]);if(!n.ok||n.stdout==="")throw A("git rev-parse --show-toplevel",n);if(!o.ok&&!Ye(o))throw A("git remote get-url origin",o);if(!r.ok)throw A("git branch --show-current",r);if(!s.ok)throw A("git status --porcelain",s);return{isRepository:!0,root:n.stdout,...o.ok&&o.stdout!==""?{remote:o.stdout}:{},...r.ok?{branch:r.stdout}:{},dirty:s.ok&&s.stdout!==""}}async function j(t,e){try{let n=await de("git",e,{cwd:t});return{ok:!0,stdout:n.stdout.trim(),stderr:n.stderr.trim()}}catch(n){let o=n;return{ok:!1,stdout:String(o.stdout??"").trim(),stderr:String(o.stderr??o.message??"").trim(),...o.code==="ENOENT"?{unavailable:!0}:{},...o.code!==void 0?{code:o.code}:{}}}}function Ve(t){return/not a git repository|not inside a work tree/i.test(`${t.stderr}
71
+ ${t.stdout}`)}function Ye(t){return/no such remote(?:\s+['"]?origin)?/i.test(`${t.stderr}
72
+ ${t.stdout}`)}function A(t,e){let n=$(e.stderr||e.stdout||"Git returned no diagnostics.");return new p("git_command_failed",`${t} failed: ${n}`,{command:t,...e.code!==void 0?{exitCode:e.code}:{},nextSteps:[{description:"Verify the repository with Git",command:"git status"},{description:"Deploy without GitHub",command:"mcp-use deploy --no-github"}]})}async function b(t,e){try{await de("git",e,{cwd:t})}catch(n){let o=n;throw new O(`git ${e.join(" ")}`,String(o.stderr??o.stdout??""),o.code)}}var O=class extends Error{constructor(n,o,r){super(o.trim()||`${n} failed`);this.command=n;this.output=o;this.exitCode=r}};function B(t,e){if(!(t instanceof O))return new p("git_command_failed",t instanceof Error?t.message:String(t));if(/tell me who you are|author identity unknown|unable to auto-detect email address|empty ident (?:name|email)|user\.email|user\.name/i.test(t.output)){let r=$(t.command);return new p("git_identity_required","Git needs a user name and email before it can create a commit.",{command:r,nextSteps:[{description:"Set the email for this project",command:`git -C ${JSON.stringify(e)} config user.email "you@example.com"`},{description:"Set the name for this project",command:`git -C ${JSON.stringify(e)} config user.name "Your Name"`},{description:"Retry deployment",command:"mcp-use deploy --yes"}]})}if(/non-fast-forward|rejected|unrelated histories/i.test(t.output)){let r=$(t.command);return new p("git_push_rejected","GitHub rejected the push because the remote branch contains other commits.",{command:r,nextSteps:[{description:"Reconcile the remote branch",command:"git pull --rebase origin main --allow-unrelated-histories && git push -u origin main"}]})}let n=$(t.command),o=$(t.output.trim());return new p("git_command_failed",`${n} failed${o===""?".":`: ${o}`}`,{command:n,exitCode:t.exitCode})}function We(t){let e=t.match(/github\.com[/:]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/);if(e?.[1]===void 0||e[2]===void 0){let n=$(t);throw new p("unsupported_remote",`The origin remote is not a supported GitHub repository: ${n}`,{remote:n,nextSteps:[{description:"Set a GitHub origin",command:"git remote set-url origin https://github.com/<owner>/<repo>.git"},{description:"Deploy without GitHub",command:"mcp-use deploy --no-github"}]})}return`${e[1]}/${e[2]}`}function $(t){return t.replace(/\b(https?:\/\/)[^/@\s]+(?::[^@\s]*)?@/gi,"$1[REDACTED]@")}async function Ke(t,e,n){let[o,r]=n.split("/"),s=[...e].sort((i,c)=>{let a=i.account?.login?.toLowerCase()===o.toLowerCase(),u=c.account?.login?.toLowerCase()===o.toLowerCase();return Number(u)-Number(a)});for(let i of s)try{if((await t.request(`/github/installations/${encodeURIComponent(i.installationId)}/repos/${encodeURIComponent(o)}/${encodeURIComponent(r)}/access`)).hasAccess)return i}catch{}}async function Ze(t){let e=Ee(),n=[],o=(async()=>{for await(let r of e)n.push(Buffer.from(r))})();try{await me(e,t,""),await _(e,Buffer.alloc(1024)),e.end()}catch(r){throw e.destroy(r instanceof Error?r:new Error(String(r))),r}return await o,Buffer.concat(n)}async function me(t,e,n){let o=await je(n===""?e:k(e,n)),r=[];for await(let s of o)r.push(s);r.sort((s,i)=>s.name.localeCompare(i.name));for(let s of r){let i=n===""?s.name:k(n,s.name);if(!Xe(i))continue;let c=k(e,i),a=await Ie(c),l={path:`app/${i.replaceAll("\\","/")}`,mode:a.mode&511,mtime:Math.floor(a.mtimeMs/1e3)};if(a.isDirectory())await te(t,{...l,type:"directory",size:0}),await me(t,e,i);else if(a.isFile()){await te(t,{...l,type:"file",size:a.size});for await(let y of Ce(c))await _(t,y);await ge(t,a.size)}else if(a.isSymbolicLink())continue}}function Xe(t){let e=t.split(/[/\\]/).filter(Boolean);if(e.some(o=>Ae.has(o)))return!1;let n=e.at(-1)??"";return n===".DS_Store"||n==="Thumbs.db"||n==="desktop.ini"?!1:!n.startsWith(".env")}async function te(t,e){let n={},o=fe(e.path);if((o===void 0||!z(e.path))&&(n.path=e.path),e.linkPath!==void 0&&(Buffer.byteLength(e.linkPath)>100||!z(e.linkPath))&&(n.linkpath=e.linkPath),Object.keys(n).length>0){let r=Buffer.from(Object.entries(n).map(([s,i])=>Qe(s,i)).join(""));await _(t,ne({path:"PaxHeader/entry",mode:420,mtime:e.mtime,size:r.length,type:"pax"})),await _(t,r),await ge(t,r.length)}await _(t,ne({...e,path:o===void 0?"app/PaxEntry":e.path,...e.linkPath!==void 0&&(Buffer.byteLength(e.linkPath)>100||!z(e.linkPath))?{linkPath:"PaxLink"}:{}}))}function ne(t){let e=Buffer.alloc(512),n=fe(t.path)??{name:t.path.slice(-100),prefix:""};C(e,n.name,0,100),D(e,t.mode,100,8),D(e,0,108,8),D(e,0,116,8),D(e,t.size,124,12),D(e,t.mtime,136,12),e.fill(32,148,156),e[156]=t.type==="directory"?53:t.type==="symlink"?50:t.type==="pax"?120:48,t.linkPath!==void 0&&C(e,t.linkPath,157,100),C(e,"ustar",257,6),C(e,"00",263,2),C(e,"mcp-use",265,32),C(e,"mcp-use",297,32),C(e,n.prefix,345,155);let r=e.reduce((s,i)=>s+i,0).toString(8).padStart(6,"0");return e.write(r,148,6,"ascii"),e[154]=0,e[155]=32,e}function fe(t){if(Buffer.byteLength(t)<=100)return{name:t,prefix:""};for(let e=t.lastIndexOf("/");e>0;){let n=t.slice(0,e),o=t.slice(e+1);if(Buffer.byteLength(n)<=155&&Buffer.byteLength(o)<=100)return{name:o,prefix:n};e=t.lastIndexOf("/",e-1)}}function Qe(t,e){let n=`${t}=${e}
73
+ `,o=Buffer.byteLength(n)+3;for(;;){let r=`${o} ${n}`,s=Buffer.byteLength(r);if(s===o)return r;o=s}}function z(t){return Buffer.byteLength(t)===t.length}function C(t,e,n,o){t.write(e,n,o,"utf8")}function D(t,e,n,o){let r=Math.max(0,e).toString(8).padStart(o-1,"0").slice(-(o-1));t.write(r,n,o-1,"ascii"),t[n+o-1]=0}async function ge(t,e){let n=(512-e%512)%512;n>0&&await _(t,Buffer.alloc(n))}async function _(t,e){t.write(e)||await new Promise((n,o)=>{let r=()=>{t.off("drain",s),t.off("error",i)},s=()=>{r(),n()},i=c=>{r(),o(c)};t.once("drain",s),t.once("error",i)})}function oe(t,e){t.set("sourceFile",new Blob([new Uint8Array(e)],{type:"application/gzip"}),"source.tar.gz")}function q(t,e,n){if(Z(e))throw new h(`${n} must be relative.`);let o=ae(t,e),r=_e(t,o);if(r.startsWith("..")||Z(r))throw new h(`${n} must not escape the project directory.`);return o}function L(t,e,n){e!==void 0&&q(t,e,n)}async function he(t,e,n){let o={};if(e!==void 0){let r=q(t,e,"--env-file");if(!await E(r))throw new h(`Environment file not found: ${e}`);for(let s of(await T(r,"utf8")).split(/\r?\n/)){let i=s.trim();i===""||i.startsWith("#")||ie(o,i)}}for(let r of n)ie(o,r);return o}function ie(t,e){let n=e.indexOf("="),o=e.slice(0,n);if(n<=0||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))throw new h("Invalid environment assignment; expected KEY=VALUE.");t[o]=e.slice(n+1)}async function ye(t){try{let e=JSON.parse(await T(k(t,"package.json"),"utf8"));if(typeof e.name=="string"&&e.name.trim()!=="")return e.name}catch{}return se(t)}async function et(t){let e=k(t,"package.json");if(!await E(e))return;let n;try{n=JSON.parse(await T(e,"utf8"))}catch{return}if(n.workspaces!==void 0)return;let o=["dependencies","devDependencies","optionalDependencies","peerDependencies"],r=[];for(let s of o){let i=n[s];if(!(i===null||typeof i!="object"||Array.isArray(i)))for(let[c,a]of Object.entries(i))typeof a=="string"&&a.startsWith("workspace:")&&r.push(c)}if(r.length!==0)throw new p("workspace_dependencies_unresolved",`This upload root uses workspace dependencies but is not a workspace root: ${r.join(", ")}.`,{dependencies:r,nextSteps:[{description:"Deploy the monorepo root and select this package",command:"mcp-use deploy <monorepo-root> --no-github --root-dir <package-path>"},{description:"Use published dependency versions for a standalone upload",command:"Replace workspace:* versions in package.json, then run mcp-use deploy --no-github"}]})}function we(t){return t.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,80)||"mcp-server"}async function be(t,e){let n=ce({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${t} ${e?"[Y/n]":"[y/N]"} `)).trim().toLowerCase();return r===""?e:r==="y"||r==="yes"}finally{n.close()}}function ve(t){return new p("deployment_not_created","Server was created but no deployment was started.",{serverId:t,nextSteps:[{description:"Inspect the server",command:`mcp-use servers get ${t}`}]})}function ke(t){let e=`${N()}/${encodeURIComponent(t.serverSlug??t.serverId)}`,n={sourceType:t.sourceType,serverId:t.serverId,deploymentId:t.deploymentId,status:"pending",webUrl:e};return t.values.open===!0&&Y(e),J(n,t.json,`Deployment ${t.deploymentId} started for ${t.label}.`),0}export{He as assertManagedArchiveSize,ut as runDeploy};
@@ -1,6 +1,59 @@
1
- import{g as d}from"../chunk-3TSFYSEY.js";import{a,c as m,d as u,e as g,f as y}from"../chunk-VSIT62BK.js";import"../chunk-LNASFQWW.js";import{parseArgs as w}from"util";async function T(n){let t=m(n);try{let e=n[0];if(e==="list")return await I(n.slice(1),t);if(e==="get")return await P(n.slice(1),t);if(e==="logs")return await S(n.slice(1),t);if(e==="restart")return await v(n.slice(1),t);if(e==="stop")return await R(n.slice(1),t);if(e==="delete")return await E(n.slice(1),t);throw new a("Usage: mcp-use deployments <list|get|logs|restart|stop|delete>")}catch(e){return g(e instanceof TypeError?new a(e.message):e,t)}}async function I(n,t){let{values:e}=w({args:[...n],allowPositionals:!1,strict:!0,options:{org:{type:"string"},server:{type:"string"},limit:{type:"string",default:"30"},skip:{type:"string",default:"0"},json:{type:"boolean"}}}),i=f(e.limit,"--limit",1,100),s=f(e.skip,"--skip",0),o=new URLSearchParams({limit:String(i),skip:String(s),...e.server!==void 0?{serverId:e.server}:{}}),{api:r}=await d(e.org),l=await r.request(`/deployments?${o}`);return u(l,t),0}async function P(n,t){let{positionals:e}=p(n,{json:{type:"boolean"}}),i=c(e,"mcp-use deployments get <deployment-id>"),{api:s}=await d(),o=await s.request(`/deployments/${encodeURIComponent(i)}`);return u(o,t),0}async function S(n,t){let{values:e,positionals:i}=p(n,{build:{type:"boolean"},follow:{type:"boolean"},json:{type:"boolean"}}),s=c(i,"mcp-use deployments logs <deployment-id>"),{api:o}=await d();if(e.build===!0)await $(o,s,e.follow===!0,t);else{let r=await o.request(`/deployments/${encodeURIComponent(s)}/logs?lines=500`);t?u({deploymentId:s,logs:r.logs},!0):process.stdout.write(r.logs.endsWith(`
2
- `)?r.logs:`${r.logs}
3
- `)}return 0}async function v(n,t){let{values:e,positionals:i}=p(n,{branch:{type:"string"},follow:{type:"boolean"},json:{type:"boolean"}}),s=c(i,"mcp-use deployments restart <deployment-id>"),{api:o}=await d(),r=await o.request(`/deployments/${encodeURIComponent(s)}`);if(r.serverId===void 0||r.serverId===null)throw new a(`Deployment ${s} is not attached to a server.`);let l=await o.request("/deployments",{method:"POST",body:JSON.stringify({serverId:r.serverId,branch:e.branch??r.gitBranch??void 0,trigger:"redeploy"})});return e.follow===!0?await $(o,l.id,!0,t):u(l,t,`Restarted as deployment ${l.id}.`),0}async function R(n,t){return b(n,t,"stop")}async function E(n,t){return b(n,t,"delete")}async function b(n,t,e){let{values:i,positionals:s}=p(n,{yes:{type:"boolean"},json:{type:"boolean"}}),o=c(s,`mcp-use deployments ${e} <deployment-id>`);if(!await y(`${e==="stop"?"Stop":"Delete"} deployment ${o}?`,{yes:i.yes===!0,json:t}))return 0;let{api:r}=await d();return await r.request(`/deployments/${encodeURIComponent(o)}${e==="stop"?"/stop":""}`,{method:e==="stop"?"POST":"DELETE"}),u({[e==="stop"?"stopped":"deleted"]:o},t,`${e==="stop"?"Stopped":"Deleted"} ${o}.`),0}async function $(n,t,e,i){let s=0,o=new Set(["running","failed","stopped"]),r=!0;for(;r;){let l=await n.request(`/deployments/${encodeURIComponent(t)}/build-logs?offset=${s}`);l.logs!==""&&(i?process.stdout.write(`${JSON.stringify({deploymentId:t,offset:s,logs:l.logs,status:l.status})}
4
- `):process.stdout.write(l.logs.endsWith(`
5
- `)?l.logs:`${l.logs}
6
- `)),s=l.offset,r=e&&!o.has(l.status),r&&await new Promise(h=>setTimeout(h,1e3))}}function p(n,t){return w({args:[...n],allowPositionals:!0,strict:!0,options:t})}function c(n,t){if(n.length!==1)throw new a(`Usage: ${t}`);return n[0]}function f(n,t,e,i=Number.MAX_SAFE_INTEGER){let s=Number(n);if(!Number.isInteger(s)||s<e||s>i)throw new a(`${t} must be an integer from ${e} to ${i}.`);return s}export{T as runDeployments};
1
+ import{h as m}from"../chunk-3XW44DRS.js";import{a as u,d as h,e as a,f as w,g as b}from"../chunk-VUVLJMYY.js";import"../chunk-LNASFQWW.js";import{parseArgs as E}from"util";var A=`Usage: mcp-use deployments <command> [options]
2
+
3
+ Manage cloud deployments and logs.
4
+
5
+ Commands:
6
+ list List deployments
7
+ get <deployment-id> Show one deployment
8
+ logs <deployment-id> Read runtime or build logs
9
+ restart <deployment-id> Create a replacement deployment
10
+ stop <deployment-id> Stop a deployment
11
+ delete <deployment-id> Delete a deployment
12
+
13
+ Run mcp-use deployments <command> --help for all options.
14
+
15
+ Exit codes:
16
+ 0 Success or help
17
+ 2 Invalid arguments or confirmation required
18
+ 1 API or operational failure`,U={list:`Usage: mcp-use deployments list [options]
19
+
20
+ Options:
21
+ --org <id-or-slug> Override the active organization
22
+ --server <id> Filter by server
23
+ --limit <n> Results per page (default: 30; range: 1-100)
24
+ --skip <n> Results to skip (default: 0)
25
+ --json Emit the complete API page
26
+ -h, --help Show this help`,get:`Usage: mcp-use deployments get <deployment-id> [--json]
27
+
28
+ Options:
29
+ --json Emit the complete deployment object
30
+ -h, --help Show this help`,logs:`Usage: mcp-use deployments logs <deployment-id> [options]
31
+
32
+ Options:
33
+ --build Read build logs instead of runtime logs
34
+ --follow Poll build logs until a terminal status
35
+ --json Emit exactly one object; with --follow, emit only at completion
36
+ -h, --help Show this help`,restart:`Usage: mcp-use deployments restart <deployment-id> [options]
37
+
38
+ Options:
39
+ --branch <name> Override the source branch
40
+ --follow Follow build logs after restart
41
+ --json Emit exactly one object; with --follow, emit only at completion
42
+ -h, --help Show this help`,stop:`Usage: mcp-use deployments stop <deployment-id> [options]
43
+
44
+ Options:
45
+ --yes Confirm without prompting
46
+ --json Emit the result; never prompt
47
+ -h, --help Show this help`,delete:`Usage: mcp-use deployments delete <deployment-id> [options]
48
+
49
+ Options:
50
+ --yes Confirm without prompting
51
+ --json Emit the result; never prompt
52
+ -h, --help Show this help`};async function x(e){if(e.some(t=>t==="--help"||t==="-h"))return process.stdout.write(`${U[e[0]??""]??A}
53
+ `),0;let n=h(e);try{let t=e[0];if(t==="list")return await j(e.slice(1),n);if(t==="get")return await T(e.slice(1),n);if(t==="logs")return await C(e.slice(1),n);if(t==="restart")return await D(e.slice(1),n);if(t==="stop")return await O(e.slice(1),n);if(t==="delete")return await k(e.slice(1),n);throw new u("Usage: mcp-use deployments <list|get|logs|restart|stop|delete>")}catch(t){return w(t instanceof TypeError?new u(t.message):t,n)}}async function j(e,n){let{values:t}=E({args:[...e],allowPositionals:!1,strict:!0,options:{org:{type:"string"},server:{type:"string"},limit:{type:"string",default:"30"},skip:{type:"string",default:"0"},json:{type:"boolean"}}}),o=$(t.limit,"--limit",1,100),s=$(t.skip,"--skip",0),r=new URLSearchParams({limit:String(o),skip:String(s),...t.server!==void 0?{serverId:t.server}:{}}),{api:i}=await m(t.org),d=await i.request(`/deployments?${r}`);return a(d,n,L(d)),0}async function T(e,n){let{positionals:t}=g(e,{json:{type:"boolean"}}),o=y(t,"mcp-use deployments get <deployment-id>"),{api:s}=await m(),r=await s.request(`/deployments/${encodeURIComponent(o)}`);return a(r,n,B(r)),0}async function C(e,n){let{values:t,positionals:o}=g(e,{build:{type:"boolean"},follow:{type:"boolean"},json:{type:"boolean"}}),s=y(o,"mcp-use deployments logs <deployment-id>"),{api:r}=await m();if(t.build===!0)await S(r,s,t.follow===!0,n);else{let i=await r.request(`/deployments/${encodeURIComponent(s)}/logs?lines=500`);n?a({deploymentId:s,logs:i.logs},!0):process.stdout.write(i.logs.endsWith(`
54
+ `)?i.logs:`${i.logs}
55
+ `)}return 0}async function D(e,n){let{values:t,positionals:o}=g(e,{branch:{type:"string"},follow:{type:"boolean"},json:{type:"boolean"}}),s=y(o,"mcp-use deployments restart <deployment-id>"),{api:r}=await m(),i=await r.request(`/deployments/${encodeURIComponent(s)}`);if(i.serverId===void 0||i.serverId===null)throw new u(`Deployment ${s} is not attached to a server.`);let d=await r.request("/deployments",{method:"POST",body:JSON.stringify({serverId:i.serverId,branch:t.branch??i.gitBranch??void 0,trigger:"redeploy"})});return t.follow===!0?await S(r,d.id,!0,n):a(d,n,`Restarted as deployment ${d.id}.`),0}async function O(e,n){return R(e,n,"stop")}async function k(e,n){return R(e,n,"delete")}async function R(e,n,t){let{values:o,positionals:s}=g(e,{yes:{type:"boolean"},json:{type:"boolean"}}),r=y(s,`mcp-use deployments ${t} <deployment-id>`);if(!await b(`${t==="stop"?"Stop":"Delete"} deployment ${r}?`,{yes:o.yes===!0,json:n}))return 0;let{api:i}=await m();return await i.request(`/deployments/${encodeURIComponent(r)}${t==="stop"?"/stop":""}`,{method:t==="stop"?"POST":"DELETE"}),a({[t==="stop"?"stopped":"deleted"]:r},n,`${t==="stop"?"Stopped":"Deleted"} ${r}.`),0}async function S(e,n,t,o){let s=0,r="pending",i="",d=new Set(["running","failed","stopped"]),f=!0;for(;f;){let p=await e.request(`/deployments/${encodeURIComponent(n)}/build-logs?offset=${s}`);p.logs!==""&&(i+=p.logs,o||process.stdout.write(p.logs.endsWith(`
56
+ `)?p.logs:`${p.logs}
57
+ `)),s=p.offset,r=p.status,f=t&&!d.has(p.status),f&&await new Promise(P=>setTimeout(P,1e3))}o&&a({deploymentId:n,offset:s,logs:i,status:r},!0)}function g(e,n){return E({args:[...e],allowPositionals:!0,strict:!0,options:n})}function y(e,n){if(e.length!==1)throw new u(`Usage: ${n}`);return e[0]}function $(e,n,t,o=Number.MAX_SAFE_INTEGER){let s=Number(e);if(!Number.isInteger(s)||s<t||s>o)throw new u(`${n} must be an integer from ${t} to ${o}.`);return s}function L(e){let n=c(e)&&Array.isArray(e.items)?e.items.filter(c):[];return n.length===0?"No deployments.":["DEPLOYMENT SERVER STATUS TRIGGER BRANCH CREATED ERROR",...n.map(o=>[q(l(o,"id")),l(o,"serverId")??"-",l(o,"status")??"-",l(o,"deploymentTrigger")??"-",l(o,"gitBranch")??"-",l(o,"createdAt")??"-",I(l(o,"error"))].join(" "))].join(`
58
+ `)}function B(e){if(!c(e))return String(e);let n=l(e,"id")??"-",t=l(e,"error");return[`Deployment: ${n}`,`Server: ${l(e,"serverId")??"-"}`,`Status: ${l(e,"status")??"-"}`,`Trigger: ${l(e,"deploymentTrigger")??"-"}`,`Branch: ${l(e,"gitBranch")??"-"}`,`Created: ${l(e,"createdAt")??"-"}`,...t!==void 0?[`Error: ${I(t)}`,`Build logs: mcp-use deployments logs ${n} --build`]:[]].join(`
59
+ `)}function l(e,n){if(!c(e))return;let t=e[n];return typeof t=="string"&&t!==""?t:void 0}function q(e){return e===void 0?"-":e.slice(0,8)}function I(e){if(e===void 0)return"-";let n=e.split(/\r?\n/,1)[0]??e;return n.length>100?`${n.slice(0,97)}...`:n}function c(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}export{x as runDeployments};
@@ -1,2 +1,2 @@
1
- import{b as ie}from"../chunk-OVFUQAEG.js";import{a as ne,b as re}from"../chunk-N7BU45K6.js";import{b as Z,c as Q}from"../chunk-USIKTT3N.js";import{a as ae,b as ce,c as le,d as de,e as ue,f as pe,g as D,i as F,j as fe,l as me,m as ve,n as we}from"../chunk-YMYENQ4W.js";import{b as oe,c as se,d as x}from"../chunk-7G4TXPP4.js";import{a as A,b as te}from"../chunk-FLGSKQGU.js";import{a as ee}from"../chunk-LNASFQWW.js";import{existsSync as xe}from"fs";import{createServer as Fe}from"http";import{networkInterfaces as Be}from"os";import{join as Ne,resolve as We}from"path";import Ge from"@tailwindcss/vite";import qe from"@vitejs/plugin-react";import{createServer as ze,createServerModuleRunner as Je}from"vite";import{InMemoryServerEventBus as Ke,localhostAllowedHostnames as Xe,localhostAllowedOrigins as Ye,validateHostHeader as Ze,validateOriginHeader as Qe}from"@modelcontextprotocol/server";import{connect as De,createServer as Oe}from"net";var he=100,He=300,Ue=new Set(["127.0.0.1","localhost","::1"]);function ke(e,r){return new Promise(s=>{let n=Oe();n.unref(),n.once("error",()=>s(!1)),n.listen({port:e,host:r},()=>{n.close(()=>s(!0))})})}function ge(e,r){return new Promise(s=>{let n=De({port:e,host:r});n.setTimeout(He),n.once("connect",()=>{n.destroy(),s(!0)}),n.once("timeout",()=>{n.destroy(),s(!1)}),n.once("error",()=>{n.destroy(),s(!1)})})}async function Te(e){return await ge(e,"127.0.0.1")||await ge(e,"::1")}async function ye(e,r){for(let s=e;s<e+he;s++)if(await ke(s,r)&&!(Ue.has(r)&&await Te(s)))return{port:s,requested:e};throw new Error(`No free port found between ${e} and ${e+he-1} on ${r}.`)}function Pe(e,r){let s=()=>{let n=e.getBasePath(),{url:a}=e.tunnel.status();return{mcpUrl:a!==null?`${a.replace(/\/+$/,"")}${n}`:null,port:e.port,fromCli:!0,tunnelUrl:a}};return async n=>{let a=e.getBasePath(),u=`${a}/inspector/api/dev/info`,p=`${a}/inspector/api/dev/start-tunnel`,f=`${a}/inspector/api/dev/stop-tunnel`,y=new URL(n.url).pathname;if(n.method==="GET"&&y===u)return Response.json(s());if(n.method==="POST"&&y===p)try{return await e.tunnel.start(e.port),Response.json({ok:!0,restarting:!1})}catch(M){let O=M instanceof Error?M.message:"Failed to start tunnel";return Response.json({error:O},{status:500})}return n.method==="POST"&&y===f?(await e.tunnel.stop(),Response.json({ok:!0})):r(n)}}import{readFileSync as je}from"fs";import{createRequire as Ve}from"module";import{join as $e}from"path";import{pathToFileURL as Ae}from"url";async function Me(e){let r=$e(e,"package.json"),s=JSON.parse(je(r,"utf8"));if([s.dependencies,s.devDependencies,s.optionalDependencies].some(u=>u!==null&&typeof u=="object"&&"@mcp-use/inspector"in u)){let u=Ve(r);try{let p=u.resolve("@mcp-use/inspector");return _e(await import(Ae(p).href))}catch(p){if(!Re(p))throw p}}try{return _e(await import("@mcp-use/inspector"))}catch(u){if(Re(u))return{installed:!1};throw u}}function _e(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 Re(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"}var Ie="__mcpUseV1CompatServer";function et(e){ee(e)}function tt(){for(let e of Object.values(Be()))for(let r of e??[])if(!r.internal&&r.family==="IPv4")return r.address}function nt(e){if(e!==void 0)try{return new URL(`http://${e}`).hostname.replace(/^\[|\]$/g,"")}catch{return}}function rt(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 ot(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 a=Qe(n,Ye());!a.ok||a.origin===void 0||(r.setHeader("Access-Control-Allow-Origin",a.origin),rt(r))}function st(e){let r=e.default??globalThis[Ie];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 it(e){process.env.MCP_USE_DEV_CLI="1";let r=le(e.cwd),s=new Ke(t=>{console.error("[mcp-use] notification delivery failed:",t)});se(e.cwd,"development");let n=Q(e.host),a=["127.0.0.1","localhost","::1"].includes(n),u=n==="0.0.0.0"||n==="::",p=Fe(),{port:f,requested:y}=await ye(Z(e.port),n);f!==y&&console.log(`[mcp-use] port ${y} is taken, using ${f}`),process.env.PORT=String(f);let M=process.env.MCP_URL===void 0&&(n==="127.0.0.1"||n==="localhost"||n==="::1")?`http://localhost:${f}`:void 0,O=e.mcpDir===void 0?e.cwd:We(e.cwd,e.mcpDir),B=e.entry===void 0?A(O):A(e.cwd,e.entry),H=await te(e.cwd,B);(H==="created"||H==="updated")&&console.log(`[mcp-use] ${H} mcp-env.d.ts`);let P=e.viewsDir??(e.mcpDir===void 0?void 0:Ne(e.mcpDir,"views"));xe(pe(e.cwd,P))||console.log("[mcp-use] views directory not configured.");let d=D(e.cwd,P,{includeLegacy:!0}),C=!1,_=d.length>0,be=ae(e.cwd),U=["127.0.0.1","localhost","0.0.0.0","::","::1"].includes(n)?"localhost":n,I=`http://${U.includes(":")?`[${U}]`:U}:${f}`,m=await ze({root:e.cwd,configFile:_?be:!1,envDir:!1,logLevel:"warn",cacheDir:r.cache,resolve:{tsconfigPaths:!0,alias:{tailwindcss:ce()},dedupe:me},optimizeDeps:ve,oxc:{jsx:{runtime:"automatic"}},plugins:_?[x(e.cwd),ue(),Ge(),we({getViews:()=>d,dev:{reactRefresh:!0}}),qe()]:[x(e.cwd)],server:{middlewareMode:!0,..._&&{origin:I},cors:!1,hmr:_?{server:p}:!1,...!_&&{ws:!1}},ssr:{...oe(e.cwd)}}),k=m.environments.ssr,R=Je(k,{hmr:!1,sourcemapInterceptor:"node"}),N=async()=>{let t=async()=>{delete globalThis[Ie];let i=process.env.MCP_USE_CLI_IMPORT,l;try{process.env.MCP_USE_CLI_IMPORT="1",l=await R.import(B)}finally{i===void 0?delete process.env.MCP_USE_CLI_IMPORT:process.env.MCP_USE_CLI_IMPORT=i}let c=st(l);C=typeof c.__registerLegacyViews=="function",d=D(e.cwd,P,{includeLegacy:C});let w=d.filter(g=>g.legacy===!0);if(w.length>0){if(typeof c.__registerLegacyViews!="function")throw new Error("Legacy resources/*/widget.tsx views require the temporary mcp-use/server compatibility entry.");let g={};for(let L of w)g[L.name]=await R.import(de(L.entryPath));c.__registerLegacyViews(g)}let S=fe(d);if(typeof c.__primeViews!="function")throw new Error("Loaded MCPServer instance does not support __primeViews.");return c.__primeViews(S,{dev:!0,projectRoot:e.cwd}),c};if(M===void 0)return t();let o=process.env.MCP_URL;try{return process.env.MCP_URL=M,await t()}finally{o===void 0?delete process.env.MCP_URL:process.env.MCP_URL=o}},T,v;try{let t=await N();t.__setEventBus(s),t.__mount(),T=async o=>t.fetch(o),v=t.basePath??"/mcp"}catch(t){throw await R.close(),await m.close(),t}let j,b,W,G=t=>{if(j===void 0||W===t)return;let o=j.mountInspector({basePath:t,autoConnectUrl:`${I}${t}`,oauthProxyAllowLoopback:a||u,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.");b=o,W=t};try{if(e.inspector!==!1){let t=await Me(e.cwd);t.installed&&(j=t.module,G(v))}}catch(t){throw await R.close(),await m.close(),t}let V=!1,$=!1,q=()=>{if(V){$=!0;return}V=!0,(async()=>{do{$=!1;try{R.evaluatedModules.clear();let t=await N();t.__setEventBus(s),t.__mount();let o=async l=>t.fetch(l),i=t.basePath??"/mcp";G(i),T=o,v=i,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:
1
+ import{b as ie}from"../chunk-K63AC3Q2.js";import{a as ne,b as re}from"../chunk-N7BU45K6.js";import{b as Z,c as Q}from"../chunk-USIKTT3N.js";import{a as ae,b as ce,c as le,d as de,e as ue,f as pe,g as D,i as F,j as fe,l as me,m as ve,n as we}from"../chunk-YMYENQ4W.js";import{b as oe,c as se,d as x}from"../chunk-7G4TXPP4.js";import{a as A,b as te}from"../chunk-FLGSKQGU.js";import{a as ee}from"../chunk-LNASFQWW.js";import{existsSync as xe}from"fs";import{createServer as Fe}from"http";import{networkInterfaces as Be}from"os";import{join as Ne,resolve as We}from"path";import Ge from"@tailwindcss/vite";import qe from"@vitejs/plugin-react";import{createServer as ze,createServerModuleRunner as Je}from"vite";import{InMemoryServerEventBus as Ke,localhostAllowedHostnames as Xe,localhostAllowedOrigins as Ye,validateHostHeader as Ze,validateOriginHeader as Qe}from"@modelcontextprotocol/server";import{connect as De,createServer as Oe}from"net";var he=100,He=300,Ue=new Set(["127.0.0.1","localhost","::1"]);function ke(e,r){return new Promise(s=>{let n=Oe();n.unref(),n.once("error",()=>s(!1)),n.listen({port:e,host:r},()=>{n.close(()=>s(!0))})})}function ge(e,r){return new Promise(s=>{let n=De({port:e,host:r});n.setTimeout(He),n.once("connect",()=>{n.destroy(),s(!0)}),n.once("timeout",()=>{n.destroy(),s(!1)}),n.once("error",()=>{n.destroy(),s(!1)})})}async function Te(e){return await ge(e,"127.0.0.1")||await ge(e,"::1")}async function ye(e,r){for(let s=e;s<e+he;s++)if(await ke(s,r)&&!(Ue.has(r)&&await Te(s)))return{port:s,requested:e};throw new Error(`No free port found between ${e} and ${e+he-1} on ${r}.`)}function Pe(e,r){let s=()=>{let n=e.getBasePath(),{url:a}=e.tunnel.status();return{mcpUrl:a!==null?`${a.replace(/\/+$/,"")}${n}`:null,port:e.port,fromCli:!0,tunnelUrl:a}};return async n=>{let a=e.getBasePath(),u=`${a}/inspector/api/dev/info`,p=`${a}/inspector/api/dev/start-tunnel`,f=`${a}/inspector/api/dev/stop-tunnel`,y=new URL(n.url).pathname;if(n.method==="GET"&&y===u)return Response.json(s());if(n.method==="POST"&&y===p)try{return await e.tunnel.start(e.port),Response.json({ok:!0,restarting:!1})}catch(M){let O=M instanceof Error?M.message:"Failed to start tunnel";return Response.json({error:O},{status:500})}return n.method==="POST"&&y===f?(await e.tunnel.stop(),Response.json({ok:!0})):r(n)}}import{readFileSync as je}from"fs";import{createRequire as Ve}from"module";import{join as $e}from"path";import{pathToFileURL as Ae}from"url";async function Me(e){let r=$e(e,"package.json"),s=JSON.parse(je(r,"utf8"));if([s.dependencies,s.devDependencies,s.optionalDependencies].some(u=>u!==null&&typeof u=="object"&&"@mcp-use/inspector"in u)){let u=Ve(r);try{let p=u.resolve("@mcp-use/inspector");return _e(await import(Ae(p).href))}catch(p){if(!Re(p))throw p}}try{return _e(await import("@mcp-use/inspector"))}catch(u){if(Re(u))return{installed:!1};throw u}}function _e(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 Re(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"}var Ie="__mcpUseV1CompatServer";function et(e){ee(e)}function tt(){for(let e of Object.values(Be()))for(let r of e??[])if(!r.internal&&r.family==="IPv4")return r.address}function nt(e){if(e!==void 0)try{return new URL(`http://${e}`).hostname.replace(/^\[|\]$/g,"")}catch{return}}function rt(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 ot(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 a=Qe(n,Ye());!a.ok||a.origin===void 0||(r.setHeader("Access-Control-Allow-Origin",a.origin),rt(r))}function st(e){let r=e.default??globalThis[Ie];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 it(e){process.env.MCP_USE_DEV_CLI="1";let r=le(e.cwd),s=new Ke(t=>{console.error("[mcp-use] notification delivery failed:",t)});se(e.cwd,"development");let n=Q(e.host),a=["127.0.0.1","localhost","::1"].includes(n),u=n==="0.0.0.0"||n==="::",p=Fe(),{port:f,requested:y}=await ye(Z(e.port),n);f!==y&&console.log(`[mcp-use] port ${y} is taken, using ${f}`),process.env.PORT=String(f);let M=process.env.MCP_URL===void 0&&(n==="127.0.0.1"||n==="localhost"||n==="::1")?`http://localhost:${f}`:void 0,O=e.mcpDir===void 0?e.cwd:We(e.cwd,e.mcpDir),B=e.entry===void 0?A(O):A(e.cwd,e.entry),H=await te(e.cwd,B);(H==="created"||H==="updated")&&console.log(`[mcp-use] ${H} mcp-env.d.ts`);let P=e.viewsDir??(e.mcpDir===void 0?void 0:Ne(e.mcpDir,"views"));xe(pe(e.cwd,P))||console.log("[mcp-use] views directory not configured.");let d=D(e.cwd,P,{includeLegacy:!0}),C=!1,_=d.length>0,be=ae(e.cwd),U=["127.0.0.1","localhost","0.0.0.0","::","::1"].includes(n)?"localhost":n,I=`http://${U.includes(":")?`[${U}]`:U}:${f}`,m=await ze({root:e.cwd,configFile:_?be:!1,envDir:!1,logLevel:"warn",cacheDir:r.cache,resolve:{tsconfigPaths:!0,alias:{tailwindcss:ce()},dedupe:me},optimizeDeps:ve,oxc:{jsx:{runtime:"automatic"}},plugins:_?[x(e.cwd),ue(),Ge(),we({getViews:()=>d,dev:{reactRefresh:!0}}),qe()]:[x(e.cwd)],server:{middlewareMode:!0,..._&&{origin:I},cors:!1,hmr:_?{server:p}:!1,...!_&&{ws:!1}},ssr:{...oe(e.cwd)}}),k=m.environments.ssr,R=Je(k,{hmr:!1,sourcemapInterceptor:"node"}),N=async()=>{let t=async()=>{delete globalThis[Ie];let i=process.env.MCP_USE_CLI_IMPORT,l;try{process.env.MCP_USE_CLI_IMPORT="1",l=await R.import(B)}finally{i===void 0?delete process.env.MCP_USE_CLI_IMPORT:process.env.MCP_USE_CLI_IMPORT=i}let c=st(l);C=typeof c.__registerLegacyViews=="function",d=D(e.cwd,P,{includeLegacy:C});let w=d.filter(g=>g.legacy===!0);if(w.length>0){if(typeof c.__registerLegacyViews!="function")throw new Error("Legacy resources/*/widget.tsx views require the temporary mcp-use/server compatibility entry.");let g={};for(let L of w)g[L.name]=await R.import(de(L.entryPath));c.__registerLegacyViews(g)}let S=fe(d);if(typeof c.__primeViews!="function")throw new Error("Loaded MCPServer instance does not support __primeViews.");return c.__primeViews(S,{dev:!0,projectRoot:e.cwd}),c};if(M===void 0)return t();let o=process.env.MCP_URL;try{return process.env.MCP_URL=M,await t()}finally{o===void 0?delete process.env.MCP_URL:process.env.MCP_URL=o}},T,v;try{let t=await N();t.__setEventBus(s),t.__mount(),T=async o=>t.fetch(o),v=t.basePath??"/mcp"}catch(t){throw await R.close(),await m.close(),t}let j,b,W,G=t=>{if(j===void 0||W===t)return;let o=j.mountInspector({basePath:t,autoConnectUrl:`${I}${t}`,oauthProxyAllowLoopback:a||u,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.");b=o,W=t};try{if(e.inspector!==!1){let t=await Me(e.cwd);t.installed&&(j=t.module,G(v))}}catch(t){throw await R.close(),await m.close(),t}let V=!1,$=!1,q=()=>{if(V){$=!0;return}V=!0,(async()=>{do{$=!1;try{R.evaluatedModules.clear();let t=await N();t.__setEventBus(s),t.__mount();let o=async l=>t.fetch(l),i=t.basePath??"/mcp";G(i),T=o,v=i,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
2
  `,t)}}while($);V=!1})()},z=t=>{if(F(t,e.cwd,P))return;let o=k.moduleGraph.getModulesByFile(t);if(!(o===void 0||o.size===0)){for(let i of o)k.moduleGraph.invalidateModule(i);q()}},J=t=>{if(!F(t,e.cwd,P))return;let o=d;d=D(e.cwd,P,{includeLegacy:C});let i=o.length!==d.length||o.some((c,w)=>c.name!==d[w]?.name||c.entryPath!==d[w]?.entryPath),l=C&&d.some(c=>c.legacy===!0&&c.entryPath===t);(i||l)&&q()},K=t=>{J(t),z(t)},E=t=>{J(t),z(t)};m.watcher.on("change",K),m.watcher.on("add",E),m.watcher.on("unlink",E);let h=ie(r.tunnel);p.prependListener("upgrade",t=>{let o=h.status().url;if(o===null)return;let i=new URL(o).hostname;t.headers.host?.split(":")[0]===i&&(t.headers.host=`localhost:${f}`)});let Se=(t,o)=>{let i=h.status().url,l=i!==null?new URL(i).hostname:null,c=l!==null?[l]:[],w=Ze(t.headers.host,[...Xe(),...c]);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)},X=async()=>{m.watcher.off("change",K),m.watcher.off("add",E),m.watcher.off("unlink",E),await h.stop(),await new Promise(t=>p.close(()=>t())),await R.close(),await m.close()},Ce=Pe({getBasePath:()=>v,port:f,tunnel:h},t=>b!==void 0&&ne(t,v)?b(t):T(t)),{toNodeHandler:Ee}=await import("../node-bridge-WOT2W5YZ.js"),Y=Ee({fetch:Ce}),Le=(t,o)=>{if(a&&Se(t,o))return;let i=t.url??"/",l=new URL(i,"http://127.0.0.1").pathname,c=h.status().url,w=c===null?null:new URL(c).hostname,S=nt(t.headers.host);if((w!==null&&S===w||u&&S!==void 0&&!["localhost","127.0.0.1","::1"].includes(S))&&re(l,v)){o.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),o.end("Not Found");return}let g=_&&d.length>0,L=t.method==="GET"&&(l.startsWith("/@")||l.startsWith("/node_modules/")||l.startsWith("/.mcp-use/")||g&&l.startsWith("/views/"));g&&L?(ot(t,o,{tunnelActive:h.status().url!==null,localhostBind:a}),m.middlewares(t,o,()=>{Y(t,o)})):Y(t,o)};if(p.on("request",Le),await new Promise((t,o)=>{p.once("error",o),p.listen(f,n,()=>t())}),console.log("[mcp-use] dev server ready"),d.length>0&&console.log(` \u279C Views: ${d.map(t=>t.name).join(", ")}`),console.log(` \u279C MCP endpoint: ${I}${v}`),b!==void 0?console.log(` \u279C Inspector: ${I}${v}/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=tt();t!==void 0&&console.log(` \u279C Network: http://${t}:${f}${v}`)}if(a||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(f);console.log(` \u279C Tunnel: ${t}${v}`)}catch(t){throw await X(),t}b!==void 0&&e.open!==!1&&process.stdout.isTTY===!0&&et(`${I}${v}/inspector`),await new Promise(t=>{let o=!1,i=()=>{o||(o=!0,process.off("SIGINT",i),process.off("SIGTERM",i),(async()=>(await X(),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{it as runDev};
@@ -1,13 +1,38 @@
1
- import{a as u,b as _,c as C,d as b,e as k,f as p}from"../chunk-3TSFYSEY.js";import{a as c,b as s,c as y,d as l,e as w,f as h,g as v}from"../chunk-VSIT62BK.js";import"../chunk-LNASFQWW.js";import{parseArgs as g}from"util";var P="mcp-use-cli",I=1800*1e3,T=`Usage: mcp-use login [options]
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
2
 
3
3
  Authenticate the cloud CLI.
4
4
 
5
5
  Options:
6
6
  --api-key <key> Authenticate with an API key
7
7
  --device-code <code> Redeem a pre-approved device code
8
- --org <id-or-slug> Select the active organization
8
+ --org <id-or-slug> Select the active organization (required for headless
9
+ login when the account has no default)
9
10
  --no-open Do not open the verification URL
10
11
  --json Emit machine-readable output
11
- -h, --help Show this help`;async function N(n,o){if(n==="login"&&o.some(e=>e==="--help"||e==="-h"))return process.stdout.write(`${T}
12
- `),0;let i=y(o);try{return n==="login"?await E(o,i):n==="logout"?await O(o,i):await $(o,i)}catch(e){return w(e instanceof TypeError?new c(e.message):e,i)}}async function E(n,o){let{values:i}=g({args:[...n],allowPositionals:!1,strict:!0,options:{"api-key":{type:"string"},"device-code":{type:"string"},org:{type:"string"},"no-open":{type:"boolean"},json:{type:"boolean"}}});if(i["api-key"]!==void 0&&i["device-code"]!==void 0)throw new c("--api-key and --device-code cannot be used together.");let e=i["device-code"]?.trim();if(i["device-code"]!==void 0&&e==="")throw new c("--device-code must not be empty.");let t=e===void 0?i["api-key"]??process.env.MCP_USE_API_KEY:void 0;t===void 0&&(t=e===void 0?await A(i["no-open"]===!0||!process.stdout.isTTY):await L(e));let a=await p.withApiKey(t).identity(),r=i.org!==void 0?k(a.organizations,i.org):a.organizations.find(d=>d.id===a.defaultOrganizationId);return await C({apiKey:t,...r!==void 0?{orgId:r.id,orgName:r.name,...r.slug!==null?{orgSlug:r.slug}:{}}:{}}),l({email:a.email,organization:r??null},o,`Logged in as ${a.email}${r!==void 0?` (${r.name})`:""}.`),0}async function O(n,o){let{values:i}=g({args:[...n],allowPositionals:!1,strict:!0,options:{yes:{type:"boolean"},json:{type:"boolean"}}});return await h("Delete local cloud credentials?",{yes:i.yes===!0,json:o})&&(await b(),l({loggedOut:!0},o,"Logged out.")),0}async function $(n,o){g({args:[...n],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"}}});let i=await _(),e=await(await p.create()).identity(),t=e.organizations.find(r=>r.id===i.orgId)??null,a={userId:e.userId,email:e.email,organization:t};return l(a,o,`${e.email}${t!==null?` \u2014 ${t.name}`:""}`),0}async function A(n){let o=u(),i=await fetch(`${o}/api/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:P,scope:"openid profile email"})});if(!i.ok)throw new s("login_failed",`Could not start device login (${i.status}).`);let e=await i.json(),t=e.verification_uri_complete??e.verification_uri;return process.stderr.write(`Open ${t} and enter code ${e.user_code}.
13
- `),n||v(t),D(o,e.device_code,Math.max(e.interval,1),Date.now()+e.expires_in*1e3)}async function L(n){return D(u(),n,2,Date.now()+I)}async function D(n,o,i,e){let t=i,a=!0;for(;Date.now()<e;){a||await z(t*1e3),a=!1;let d=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:o,client_id:P})})).json();if(d.access_token!==void 0){let f=await fetch(`${n}/api/auth/api-key/create`,{method:"POST",headers:{Authorization:`Bearer ${d.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({name:"CLI",prefix:"mcp_"})});if(!f.ok)throw new s("login_failed","Could not create a CLI API key.");let m=await f.json();if(typeof m.key!="string")throw new s("login_failed","Cloud returned an invalid API key.");return m.key}if(d.error!=="authorization_pending"){if(d.error==="slow_down"){t+=5;continue}throw j(d)}}throw new s("login_timeout","Device login expired.")}function j(n){return n.error==="access_denied"?new s("login_failed","Device login was denied."):n.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 z(n){return new Promise(o=>setTimeout(o,n))}export{N as runIdentity};
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-3TSFYSEY.js";import{a as s,c as g,d as l,e as f}from"../chunk-VSIT62BK.js";import"../chunk-LNASFQWW.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-KL7RFX6A.js";import{a as c,b as s,c as _,d as k,e as R}from"../chunk-VSIT62BK.js";import"../chunk-LNASFQWW.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-3TSFYSEY.js";import{a as u,c as k,d as l,e as P,f as y}from"../chunk-VSIT62BK.js";import"../chunk-LNASFQWW.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-3KGZXHWI.js")).runStart(t)}export{e as runStart};
1
+ async function e(t){return(await import("../start-XZVTYNNH.js")).runStart(t)}export{e as runStart};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-5CBUF6UX.js";import"./chunk-USIKTT3N.js";export{a as main};
1
+ import{a}from"./chunk-DYXX5Q3W.js";import"./chunk-USIKTT3N.js";export{a as main};
@@ -1,4 +1,4 @@
1
1
  import{a as M}from"./chunk-N7BU45K6.js";import{b as v,c as E}from"./chunk-USIKTT3N.js";import{c as S}from"./chunk-7G4TXPP4.js";import{readFile as C}from"fs/promises";import{join as f}from"path";import{pathToFileURL as L}from"url";var k=".mcp-use",T="build",O="manifest.json";async function V(t){let o=f(t.cwd,k,T),s=f(o,O),c;try{c=await C(s,"utf8")}catch{throw new Error(`No production build found (missing ${s}).
2
2
  Run \`mcp-use build\` first, then \`mcp-use start\`.`)}let i;try{let n=JSON.parse(c);if(typeof n.entryPoint!="string"||n.entryPoint==="")throw new Error("missing entryPoint");i=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",S(t.cwd,"production");let a=f(o,i),u=L(a).href,l="__mcpUseV1CompatServer";delete globalThis[l];let y=process.env.MCP_USE_CLI_IMPORT,P;try{process.env.MCP_USE_CLI_IMPORT="1",P=await import(u)}finally{y===void 0?delete process.env.MCP_USE_CLI_IMPORT:process.env.MCP_USE_CLI_IMPORT=y}let b=P.default??globalThis[l];if(b===void 0)throw new Error(`The built entry (${a}) has no default export.
4
- The server entry must \`export default\` its MCPServer instance (see the mcp-use entry contract).`);let e=b;if(!A(e))throw new Error(`The default export of ${a} is not an MCPServer: it has no listen() method. Export the MCPServer instance as the default export.`);let U=typeof e.port=="number"?e.port:void 0,R=typeof e.host=="string"?e.host:void 0,h=v(t.port,process.env,U),g=E(t.host,process.env,R),p=await(t.withInspector===!0?x(e,h,g):e.listen(h,{host:g})),m=typeof p?.port=="number"?p.port:h,I=typeof p?.url=="string"?p.url:`http://localhost:${m}`,d,w;if(t.tunnel===!0)try{let{createTunnelManager:n}=await import("./tunnel-AQ2WE7EL.js");d=n(f(t.cwd,k,"state","tunnel.json"));let r=await d.start(m),_=new URL(I);w=new URL(`${_.pathname}${_.search}`,`${r.url}/`).toString()}catch(n){try{await d?.stop()}catch{}try{await e.close?.()}catch{}throw n}return{port:m,url:I,...w!==void 0&&{tunnelUrl:w},close:async()=>{let n;try{await d?.stop()}catch(r){n=r}try{await e.close?.()}catch(r){n??=r}if(n!==void 0)throw n}}}async function x(t,o,s){let{mountInspector:c}=await N(),i=typeof t.basePath=="string"?t.basePath:"/mcp",a=c({basePath:i,devMode:!1,oauthProxyAllowLoopback:!1,manufactChatUrl:process.env.MANUFACT_CHAT_URL});return t.app.use("*",async(u,l)=>{if(M(u.req.raw,i))return a(u.req.raw);await l()}),t.listen(o,{host:s})}async function N(){let t;try{t=await import("@mcp-use/inspector")}catch(o){throw D(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 D(t){return t!==null&&typeof t=="object"&&"code"in t&&(t.code==="ERR_MODULE_NOT_FOUND"||t.code==="MODULE_NOT_FOUND")}export{V as runStart};
4
+ The server entry must \`export default\` its MCPServer instance (see the mcp-use entry contract).`);let e=b;if(!A(e))throw new Error(`The default export of ${a} is not an MCPServer: it has no listen() method. Export the MCPServer instance as the default export.`);let U=typeof e.port=="number"?e.port:void 0,R=typeof e.host=="string"?e.host:void 0,h=v(t.port,process.env,U),g=E(t.host,process.env,R),p=await(t.withInspector===!0?x(e,h,g):e.listen(h,{host:g})),m=typeof p?.port=="number"?p.port:h,I=typeof p?.url=="string"?p.url:`http://localhost:${m}`,d,w;if(t.tunnel===!0)try{let{createTunnelManager:n}=await import("./tunnel-LBEIQBEU.js");d=n(f(t.cwd,k,"state","tunnel.json"));let r=await d.start(m),_=new URL(I);w=new URL(`${_.pathname}${_.search}`,`${r.url}/`).toString()}catch(n){try{await d?.stop()}catch{}try{await e.close?.()}catch{}throw n}return{port:m,url:I,...w!==void 0&&{tunnelUrl:w},close:async()=>{let n;try{await d?.stop()}catch(r){n=r}try{await e.close?.()}catch(r){n??=r}if(n!==void 0)throw n}}}async function x(t,o,s){let{mountInspector:c}=await N(),i=typeof t.basePath=="string"?t.basePath:"/mcp",a=c({basePath:i,devMode:!1,oauthProxyAllowLoopback:!1,manufactChatUrl:process.env.MANUFACT_CHAT_URL});return t.app.use("*",async(u,l)=>{if(M(u.req.raw,i))return a(u.req.raw);await l()}),t.listen(o,{host:s})}async function N(){let t;try{t=await import("@mcp-use/inspector")}catch(o){throw D(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 D(t){return t!==null&&typeof t=="object"&&"code"in t&&(t.code==="ERR_MODULE_NOT_FOUND"||t.code==="MODULE_NOT_FOUND")}export{V as runStart};
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-K63AC3Q2.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.14",
4
+ "version": "4.0.0-beta.15",
5
5
  "description": "Prebuilt CLI, development server, and build pipeline for mcp-use",
6
6
  "author": "mcp-use, Inc.",
7
7
  "license": "MIT",
@@ -1 +0,0 @@
1
- import{b as o,i as g,j as c,k as l,l as f}from"./chunk-VSIT62BK.js";import{join as C}from"path";var d=C(f,"config.json");function p(){return(process.env.MCP_USE_CLOUD_API_URL??"https://cloud.manufact.com/api/v1").replace(/\/+$/,"").replace(/\/api\/v1$/,"")+"/api/v1"}function z(){return p().replace(/\/api\/v1$/,"")}async function m(){return g(d,{})}async function I(i){await c(d,i)}async function O(){await l(d)}function _(i,t){let n=i.filter(e=>e.id===t||e.slug===t);if(n.length!==1)throw new o(n.length===0?"organization_not_found":"organization_ambiguous",`Organization not found: ${t}`);return n[0]}var s=class i{#n;#t;constructor(t,n){this.#n=t,this.#t=n}static async create(t){let n=await m(),e=process.env.MCP_USE_API_KEY??n.apiKey;if(e===void 0||e==="")throw new o("not_authenticated","Not logged in. Run `mcp-use login`.");return new i(e,t??n.orgId)}static withApiKey(t){return new i(t)}async request(t,n={}){let e=n.organizationId??this.#t,r=await fetch(`${p()}${t}`,{...n,headers:{Accept:"application/json","x-api-key":this.#n,...e!==void 0?{"x-profile-id":e}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{},...n.headers}}),u=await r.text(),a;try{a=u===""?void 0:JSON.parse(u)}catch{a=u}if(!r.ok)throw new o(r.status===401?"not_authenticated":r.status===403?"forbidden":"cloud_api_error",h(a)??`Cloud API request failed (${r.status}).`,{status:r.status});return a}async identity(){let t=await this.request("/test-auth");return{userId:t.user_id,email:t.email,organizations:t.profiles.map(n=>({id:n.id,name:n.profile_name,slug:n.slug,role:n.role})),defaultOrganizationId:t.default_profile_id}}async setDefaultOrganization(t){await this.request(`/organizations/${t}/set-default`,{method:"POST"})}};async function P(i){let t=await m(),n=await(await s.create()).identity(),e=i!==void 0?_(n.organizations,i):n.organizations.find(r=>r.id===(t.orgId??n.defaultOrganizationId));if(e===void 0)throw new o("organization_required","No active organization. Run `mcp-use org use <id-or-slug>`.");return{api:await s.create(e.id),organizationId:e.id}}function h(i){if(typeof i=="string"&&i!=="")return i;if(!(i===null||typeof i!="object"))for(let t of["message","error","detail"]){let n=i[t];if(typeof n=="string"&&n!=="")return n}}export{z as a,m as b,I as c,O as d,_ as e,s as f,P as g};
@@ -1,37 +0,0 @@
1
- import{a as c}from"./chunk-USIKTT3N.js";import{resolve as s}from"path";var i=`mcp-use \u2014 run MCP servers built with mcp-use
2
-
3
- Usage: mcp-use <command> [options]
4
-
5
- Commands:
6
- dev Start the dev server
7
- build Build the server into .mcp-use/build
8
- typecheck Refresh MCP types and run the project's TypeScript compiler
9
- start Serve the production build from .mcp-use/build
10
- login Authenticate the cloud CLI
11
- logout Delete local cloud credentials
12
- whoami Show the authenticated cloud identity
13
- org Manage the active organization
14
- servers Manage cloud servers and environment variables
15
- deployments Manage cloud deployments and logs
16
- deploy Deploy the current GitHub project
17
- client Connect to and invoke MCP servers
18
- screenshot Capture an MCP Apps view
19
-
20
- Options:
21
- -p, --port <n> Port to serve on (dev/start; default: $PORT or 3000)
22
- --host <host> Host to bind (dev/start; default: $HOST or 127.0.0.1)
23
- --entry <path> Server entry module (dev/build/typecheck only)
24
- --path <directory> Project root (default: current directory)
25
- --mcp-dir <dir> Directory containing the MCP entry and views/
26
- --views-dir <dir> Views directory (default: views/ or <mcp-dir>/views/)
27
- --source-maps Emit source maps in build output (build only)
28
- --inline Embed view JS and CSS in MCP resources (build only)
29
- -- <tsc options> Forward remaining options to TypeScript (typecheck only)
30
- --with-inspector Mount Inspector on the production listener (start only)
31
- --tunnel Expose the server through a public tunnel (dev/start only)
32
- --no-open Do not auto-open the inspector in a browser (dev only)
33
- --no-inspector Start dev without loading the optional Inspector
34
- -h, --help Show this help
35
- -v, --version Print the version`;async function u(t,n={frameworkVersion:"unknown"}){if(t.length===1&&["--version","-v"].includes(t[0]??""))return console.log(n.frameworkVersion),0;if(t.some(e=>e==="--help"||e==="-h")){let e=t[0];if(e===void 0||e==="--help"||e==="-h")return console.log(i),0}let o=t[0];if(o==="login"||o==="logout"||o==="whoami"){let{runIdentity:e}=await import("./commands/identity.js");return e(o,t.slice(1))}if(o==="org"){let{runOrganizations:e}=await import("./commands/organizations.js");return e(t.slice(1))}if(o==="servers"){let{runServers:e}=await import("./commands/servers.js");return e(t.slice(1))}if(o==="deployments"){let{runDeployments:e}=await import("./commands/deployments.js");return e(t.slice(1))}if(o==="deploy"){let{runDeploy:e}=await import("./commands/deploy.js");return e(t.slice(1))}if(o==="client"){let{runClient:e}=await import("./commands/client.js");return e(t.slice(1))}if(o==="screenshot"){let{runScreenshot:e}=await import("./commands/screenshot.js");return e(t.slice(1))}let r;try{r=c(t)}catch(e){return console.error(e instanceof Error?e.message:String(e)),2}if(r.version)return console.log(n.frameworkVersion),0;if(r.help)return console.log(i),0;switch(r.command){case"start":return p(r);case"dev":case"build":return a(r.command,r);case"typecheck":return l(r);case void 0:return console.error(i),2;default:return console.error(`Unknown command: ${r.command}
36
-
37
- ${i}`),2}}async function l(t){try{let{runTypecheck:n}=await import("./commands/typecheck.js");return await n({cwd:s(process.cwd(),t.path??"."),...t.entry!==void 0&&{entry:t.entry},...t.mcpDir!==void 0&&{mcpDir:t.mcpDir},...t.passthrough.length>0&&{tscArgs:t.passthrough}})}catch(n){return console.error(n instanceof Error?n.message:String(n)),1}}async function p(t){let n;try{let{runStart:e}=await import("./commands/start.js");n=await e({cwd:s(process.cwd(),t.path??"."),port:t.port,host:t.host,...t.inspector===!0&&{withInspector:!0},tunnel:t.tunnel})}catch(e){return console.error(e instanceof Error?e.message:String(e)),1}console.log(`mcp-use server running at ${n.url}`),n.tunnelUrl!==void 0&&console.log(`mcp-use public MCP URL: ${n.tunnelUrl}`);let o=!1,r=()=>{o||(o=!0,n.close().then(()=>process.exit(0),e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)}))};return process.once("SIGINT",r),process.once("SIGTERM",r),0}async function a(t,n){let o={cwd:s(process.cwd(),n.path??"."),...n.entry!==void 0&&{entry:n.entry},...n.mcpDir!==void 0&&{mcpDir:n.mcpDir},...n.viewsDir!==void 0&&{viewsDir:n.viewsDir},...n.port!==void 0&&{port:n.port},...n.host!==void 0&&{host:n.host},...n.tunnel&&{tunnel:!0},...!n.open&&{open:!1},...n.inspector===!1&&{inspector:!1},...n.sourceMaps&&{sourceMaps:!0},...n.inline&&{inline:!0}};try{if(t==="dev"){let{runDev:r}=await import("./commands/dev.js");await r(o)}else{let{runBuild:r}=await import("./commands/build.js");await r(o)}return 0}catch(r){return console.error(r instanceof Error?r.message:String(r)),1}}export{u as a};
@@ -1,14 +0,0 @@
1
- import{a as u,b as v,c as j,d as f,e as I,f as D,g as H,h as C,i as A,j as y,l as E}from"./chunk-VSIT62BK.js";import{createHash as de}from"crypto";import{rm as K}from"fs/promises";import{join as $}from"path";import{createInterface as fe}from"readline/promises";import{parseArgs as x}from"util";var m=["-h, --help","Show this help"],g=["--json","Emit machine-readable JSON (accepted anywhere after client)"],P=new Map;function p(e,t){P.set(e,t)}p("",{usage:"mcp-use client <command>",summary:"Connect to and invoke saved HTTP(S) MCP servers.",commands:[["connect <name> <url>","Connect and save a server"],["list","List saved servers"],["remove <name>","Remove a saved server"],["<name>","Invoke a saved server"]],options:[m]});p("connect",{usage:"mcp-use client connect <name> <url> [options]",summary:"Connect to and save an HTTP(S) MCP server.",options:[['-H, --header <"Key: Value">',"Static header (repeatable)"],["--no-oauth","Skip OAuth on authorization challenges"],["--auth-timeout <ms>","OAuth wait timeout (default: 300000)"],["--protocol <auto|legacy|modern>","Protocol mode (default: auto; modern is stateless/sessionless)"],["--no-open","Print the OAuth URL without opening a browser"],g,m]});p("list",{usage:"mcp-use client list [options]",summary:"List saved MCP servers.",options:[g,m]});p("remove",{usage:"mcp-use client remove <name> [options]",summary:"Immediately remove a saved server and its credentials.",options:[m]});p("<name>",{usage:"mcp-use client <name> <command>",summary:"Invoke a saved MCP server.",commands:[["tools","List, describe, or call tools"],["resources","List or read resources"],["prompts","List or get prompts"],["auth","Inspect or clear saved OAuth state"]],options:[m]});p("<name> tools",{usage:"mcp-use client <name> tools <command>",summary:"Use tools on a saved MCP server.",commands:[["list","List tools"],["describe <tool>","Show a tool definition"],["call <tool> [args...]","Call a tool"]],options:[m]});p("<name> tools list",{usage:"mcp-use client <name> tools list [options]",summary:"List tools on a saved MCP server.",options:[g,m]});p("<name> tools describe",{usage:"mcp-use client <name> tools describe <tool> [options]",summary:"Show one tool definition.",options:[g,m]});p("<name> tools call",{usage:"mcp-use client <name> tools call <tool> [args...] [options]",summary:"Call a tool on a saved MCP server.",options:[["--timeout <ms>","Call timeout (default: 30000)"],g,m],notes:["Arguments are one JSON object or key=value/key:=<json> pairs; do not mix forms."]});p("<name> resources",{usage:"mcp-use client <name> resources <command>",summary:"Use resources on a saved MCP server.",commands:[["list","List resources"],["read <uri>","Read a resource"]],options:[m]});p("<name> resources list",{usage:"mcp-use client <name> resources list [options]",summary:"List resources on a saved MCP server.",options:[g,m]});p("<name> resources read",{usage:"mcp-use client <name> resources read <uri> [options]",summary:"Read one resource.",options:[g,m]});p("<name> prompts",{usage:"mcp-use client <name> prompts <command>",summary:"Use prompts on a saved MCP server.",commands:[["list","List prompts"],["get <prompt> [args...]","Get a prompt"]],options:[m]});p("<name> prompts list",{usage:"mcp-use client <name> prompts list [options]",summary:"List prompts on a saved MCP server.",options:[g,m]});p("<name> prompts get",{usage:"mcp-use client <name> prompts get <prompt> [args...] [options]",summary:"Get a prompt from a saved MCP server.",options:[g,m],notes:["Arguments are one JSON object or key=value/key:=<json> pairs; do not mix forms."]});p("<name> auth",{usage:"mcp-use client <name> auth <command>",summary:"Manage saved OAuth state.",commands:[["status","Show OAuth status"],["logout","Delete saved OAuth credentials"]],options:[m]});p("<name> auth status",{usage:"mcp-use client <name> auth status [options]",summary:"Show saved OAuth status.",options:[g,m]});p("<name> auth logout",{usage:"mcp-use client <name> auth logout [options]",summary:"Delete saved OAuth credentials but keep the server.",options:[["--yes","Skip the confirmation prompt"],g,m]});function B(e){let t=e.filter(a=>a!=="--help"&&a!=="-h"&&a!=="--json"),n=t[0];if(n===void 0)return{text:S(P.get(""))};if(n==="connect"||n==="list"||n==="remove")return{text:S(P.get(n))};let o=t[1];if(o===void 0)return{text:S(P.get("<name>"))};if(!["tools","resources","prompts","auth"].includes(o))return{error:`Unknown client command family: ${o}`};let r=t[2],s=`<name> ${o}`;if(r===void 0)return{text:S(P.get(s))};let i=`${s} ${r}`,l=P.get(i);return l===void 0?{error:`Unknown client ${o} command: ${r}`}:{text:S(l)}}function S(e){let t=[`Usage: ${e.usage}`,e.summary];return e.commands!==void 0&&t.push(J("Commands",e.commands)),e.options!==void 0&&t.push(J("Options",e.options)),e.notes!==void 0&&t.push(e.notes.join(`
2
- `)),t.join(`
3
-
4
- `)}function J(e,t){let n=Math.max(...t.map(([o])=>o.length));return`${e}:
5
- ${t.map(([o,r])=>` ${o.padEnd(n)} ${r}`).join(`
6
- `)}`}import{spawn as Q}from"child_process";import{readFileSync as X}from"fs";import{chmod as ee,mkdir as te}from"fs/promises";import{dirname as ne,join as b,resolve as oe}from"path";import{pathToFileURL as G}from"url";var k=b(E,"client-sdk"),h="@mcp-use/client",re="^2.0.0-alpha.0",se=[`[mcp-use] ${h} 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(`
7
- `);async function ie(e){let t=oe(e);for(;;){if(await C(b(t,"package.json")))return t;let n=ne(t);if(n===t)return;t=n}}async function q(){try{return await le()}catch(e){if(!F(e))throw e;let t=await ae();try{return t.location==="sandbox"?await pe():await me(t.projectRoot)}catch(n){throw F(n)?new u(se):n}}}async function ae(){let e=ue(),t=`${h}@${e}`,n=await ie(process.cwd());if(process.stderr.write(`[mcp-use] installing ${h}\u2026
8
- `),n!==void 0){let[s,i]=ce(t);if(await z(s,i,n)!==0)throw new v("client_install_failed",`Failed to install ${h}.`);return{location:"project",projectRoot:n}}await te(k,{recursive:!0,mode:448}),await ee(k,448);let o=b(k,"package.json");if(await C(o)||await y(o,{private:!0,dependencies:{[h]:e}}),await z("npm",["install",t],k)!==0)throw new v("client_install_failed",`Failed to install ${h}.`);return{location:"sandbox"}}function ce(e){let t=process.env.npm_config_user_agent??"";return t.startsWith("pnpm/")?["pnpm",["add",e]]:t.startsWith("bun/")?["bun",["add",e]]:["npm",["install",e]]}function ue(){for(let e of["../package.json","../../package.json"])try{let t=X(new URL(e,import.meta.url),"utf8"),n=JSON.parse(t);if(n.name!=="mcp-use")continue;let o=n.peerDependencies?.[h];if(typeof o=="string"&&o.length>0)return o}catch{}return re}async function le(){return import("@mcp-use/client")}async function me(e){let t=G(b(e,"package.json")).href;return import(await import.meta.resolve(h,t))}async function pe(){let e=b(k,"node_modules",h,"dist","index.js");return await import(G(e).href)}function F(e){if(!(e instanceof Error))return!1;let t=e.code;return t==="ERR_MODULE_NOT_FOUND"||t==="MODULE_NOT_FOUND"?e.message.includes(h)||e.message.includes("Cannot find package"):!1}function z(e,t,n){return new Promise((o,r)=>{let s=Q(e,t,{cwd:n,stdio:"inherit",shell:process.platform==="win32"});s.once("error",r),s.once("exit",(i,l)=>{o(l==="SIGINT"?130:i??1)})})}var W=$(E,"client"),L=$(W,"servers.json");async function Fe(e){if(e.includes("--help")||e.includes("-h")){let s=B(e);return s.text!==void 0?(process.stdout.write(`${s.text}
9
- `),0):(process.stderr.write(`${s.error}
10
- `),2)}let t=j(e),n=e.filter(s=>s!=="--json"),o=n[0],r=t&&o!=="remove";try{if(o==="connect")return await ge(n.slice(1),t);if(o==="list")return await we(n.slice(1),t);if(o==="remove"){let s=e.indexOf("remove");return await he(e.filter((i,l)=>l!==s))}if(o===void 0)throw new u("Usage: mcp-use client <connect|list|remove|name>");return await ve(o,n.slice(1),t)}catch(s){return I(s instanceof TypeError?new u(s.message):s,r)}}async function ge(e,t){let{values:n,positionals:o}=x({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"},"no-open":{type:"boolean"}}});if(o.length!==2)throw new u("Usage: mcp-use client connect <name> <url>");let[r,s]=o;ke(r);let i=new URL(s);if(!["http:","https:"].includes(i.protocol))throw new u("Client URLs must use http or https.");let l=Se(n.protocol),a=Z(n["auth-timeout"]??"300000","--auth-timeout"),c=await R();if(c.servers[r]!==void 0)throw new u(`Saved server already exists: ${r}`);let d={headers:Ce(n.header??[])},w={url:i.href,oauth:n["no-oauth"]!==!0,protocol:l};return await(await M(r,w,d,a,Y({noOpen:n["no-open"]===!0,json:t}))).disconnect(),c.servers[r]=w,await y(L,c),await y(N(r),d),f({name:r,url:w.url,protocol:l},t,`Connected and saved ${r}.`),0}async function we(e,t){O(e);let n=await R(),o=Object.entries(n.servers).map(([r,s])=>({name:r,...s}));return f(o,t,o.map(r=>`${r.name} ${r.url}`).join(`
11
- `)||"No saved servers."),0}async function he(e){let{positionals:t}=x({args:[...e],allowPositionals:!0,strict:!0,options:{}}),n=_(t,"mcp-use client remove <name>"),o=await R();return delete o.servers[n],await y(L,o),await K(U(n),{recursive:!0,force:!0}),f({removed:n},!1,`Removed ${n}.`),0}async function ve(e,t,n){let r=(await R()).servers[e];if(r===void 0)throw new u(`Unknown saved server: ${e}. Run \`mcp-use client connect ${e} <url>\`.`);let s=t[0],i=t[1];if(s==="auth"){if(i==="status"){O(t.slice(2));let c=await C(T(e));return f({name:e,oauth:r.oauth,authenticated:c},n,c?"Authenticated.":"No saved OAuth session."),0}if(i==="logout"){let{values:c,positionals:d}=x({args:[...t.slice(2)],allowPositionals:!0,strict:!0,options:{yes:{type:"boolean"}}});if(d.length!==0)throw new u(`Usage: mcp-use client ${e} auth logout`);return await D(`Delete OAuth credentials for ${e}?`,{yes:c.yes===!0,json:n})&&(await K(T(e),{recursive:!0,force:!0}),f({loggedOut:e},n,`Logged out ${e}.`)),0}}let l=await A(N(e),{}),a=await M(e,r,l,3e5,Y({noOpen:!1,json:n}));try{if(s==="tools"){if(i==="list"){O(t.slice(2));let c=await a.listTools();return f(c,n,c.map(d=>d.description?`${d.name} - ${d.description}`:d.name).join(`
12
- `)),0}if(i==="describe"){let c=_(t.slice(2),`mcp-use client ${e} tools describe <tool>`),d=(await a.listTools()).find(w=>w.name===c);if(d===void 0)throw new u(`Tool not found: ${c}`);return f(d,n),0}if(i==="call")return await ye(a,e,t.slice(2),n)}if(s==="resources"){if(i==="list"){O(t.slice(2));let c=await a.listResources();return f(c,n),0}if(i==="read"){let c=_(t.slice(2),`mcp-use client ${e} resources read <uri>`);return f(await a.readResource(c),n),0}}if(s==="prompts"){if(i==="list")return O(t.slice(2)),f(await a.listPrompts(),n),0;if(i==="get"){let c=t[2];if(c===void 0)throw new u(`Usage: mcp-use client ${e} prompts get <prompt> [args]`);return f(await a.getPrompt(c,V(t.slice(3))),n),0}}throw new u(`Usage: mcp-use client ${e} <tools|resources|prompts|auth> ...`)}finally{await a.disconnect()}}async function ye(e,t,n,o){let r=n[0];if(r===void 0)throw new u(`Usage: mcp-use client ${t} tools call <tool> [args]`);let{values:s,positionals:i}=x({args:[...n.slice(1)],allowPositionals:!0,strict:!0,options:{timeout:{type:"string",default:"30000"}}}),l=Z(s.timeout,"--timeout"),a=await e.callTool(r,V(i),{timeout:l});if(a.isError===!0)throw new v("tool_error",`Tool ${r} returned an error.`,a);return f(a,o),0}async function M(e,t,n,o,r=process.stdin.isTTY?"ask":"never"){let{createOAuthProvider:s,MCPClient:i}=await q(),l=T(e),a=t.oauth?await s(t.url,{baseDir:l,authTimeoutMs:o,storageKeyPrefix:`mcp-use-cli:${e}`,openBrowser:async w=>{if(r==="never"){process.stderr.write(`Open this URL to authenticate:
13
- ${w}
14
- `);return}await Pe(),H(w)}}):void 0,c=t.protocol==="auto"?{protocolNegotiation:"auto"}:t.protocol==="modern"?{protocolNegotiation:{pin:"2026-07-28"}}:{protocolNegotiation:"legacy",clientOptions:{supportedProtocolVersions:["2025-11-25"]}},d=new i({mcpServers:{[e]:{url:t.url,...n.headers!==void 0?{headers:n.headers}:{},...a!==void 0?{authProvider:a}:{oauth:!1},...c}}});try{return await d.connect(e)}catch(w){throw Oe(w,t.protocol)}}async function ze(e,t=3e5){let o=(await R()).servers[e];if(o===void 0)throw new u(`Unknown saved server: ${e}`);let r=await A(N(e),{});return M(e,o,r,t)}async function Ge(e,t){return M("screenshot",{url:e,oauth:!1,protocol:"auto"},{headers:t},3e5)}function V(e){if(e.length===0)return{};if(e.length===1&&e[0]?.trimStart().startsWith("{")){let n=JSON.parse(e[0]);if(n===null||Array.isArray(n)||typeof n!="object")throw new u("The JSON argument must be an object.");return n}let t={};for(let n of e){let o=n.indexOf(":="),r=n.indexOf("="),s=o>=0?o:r,i=o>=0?2:1;if(s<=0)throw new u(`Expected key=value or key:=<json>, received: ${n}`);let l=n.slice(0,s).replace(/^--/,""),a=n.slice(s+i);t[l]=o>=0?JSON.parse(a):a}return t}function Y(e){return e.json||e.noOpen||!process.stdin.isTTY?"never":"ask"}async function Pe(){let e=fe({input:process.stdin,output:process.stderr});try{await e.question("This server requires OAuth. Press Enter to open your browser.")}finally{e.close()}}function Ce(e){let t={};for(let n of e){let o=n.indexOf(":");if(o<=0)throw new u(`Invalid header: ${n}`);t[n.slice(0,o).trim()]=n.slice(o+1).trim()}return t}function Se(e){if(e!=="auto"&&e!=="legacy"&&e!=="modern")throw new u("Invalid protocol. Expected auto, legacy, or modern.");return e}function Z(e,t){let n=Number(e);if(!Number.isInteger(n)||n<=0)throw new u(`${t} must be a positive integer.`);return n}function ke(e){if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(e))throw new u("Server names must be 1-64 filesystem-safe letters, numbers, dots, dashes, or underscores.")}async function R(){let e=await A(L,{servers:{}}),t={servers:{}},n=!1;for(let[o,r]of Object.entries(e.servers)){let s=be(r.protocol);t.servers[o]={...r,protocol:s},n||=s!==r.protocol}return n&&await y(L,t),t}function be(e){if(e==="auto"||e==="legacy"||e==="modern")return e;if(e===void 0)return"auto";if(e==="2025-11-25")return"legacy";if(e==="2026-07-28")return"modern";throw new u("Saved server has an invalid protocol setting. Remove and reconnect it.")}function Oe(e,t){return t==="auto"||!(e instanceof Error)||!e.message.includes("Unsupported protocol version")&&!e.message.includes("pinned protocol version")?e:t==="legacy"?new v("protocol_mismatch","Server does not support the requested legacy protocol."):new v("protocol_mismatch","Server does not support the requested modern protocol (stateless/sessionless, no fallback).")}function U(e){return $(W,"credentials",de("sha256").update(e).digest("hex"))}function N(e){return $(U(e),"credentials.json")}function T(e){return $(U(e),"oauth")}function O(e){x({args:[...e],allowPositionals:!1,strict:!0,options:{}})}function _(e,t){if(e.length!==1)throw new u(`Usage: ${t}`);return e[0]}export{Fe as a,ze as b,Ge as c,V as d};
@@ -1 +0,0 @@
1
- import{mkdir as U,readFile as L,writeFile as O}from"fs/promises";import{spawn as R}from"child_process";import{dirname as z}from"path";var D="https://local.mcp-use.run";function W(){return process.env.MCP_USE_TUNNEL_API??D}var y=1e3,q=3e4;function H(h){let i,o=null,u,l,d=!1,c,m=y,M=e=>new Promise(n=>{setTimeout(n,e)}),$=()=>{i!==void 0&&"markShutdown"in i&&typeof i.markShutdown=="function"&&i.markShutdown()},b=async e=>{try{await fetch(`${W()}/api/tunnels/${e}`,{method:"DELETE",signal:AbortSignal.timeout(2e3)})}catch{}},P=async()=>{try{let e=await L(h,"utf8"),n=JSON.parse(e);return typeof n.subdomain=="string"?n.subdomain:void 0}catch{return}},_=async e=>{try{await U(z(h),{recursive:!0}),await O(h,JSON.stringify({subdomain:e},null,2),"utf8")}catch(n){console.warn(`[mcp-use] failed to save tunnel subdomain: ${n instanceof Error?n.message:String(n)}`)}},E=()=>{},w=(e,n)=>new Promise((t,f)=>{console.log(`[mcp-use] starting tunnel for port ${e}\u2026`);let k=process.env.npm_config_user_agent??"",[F,x]=k.startsWith("pnpm/")?["pnpm",["--silent","dlx","@mcp-use/tunnel",String(e)]]:k.startsWith("bun/")?["bunx",["@mcp-use/tunnel",String(e)]]:["npx",["--yes","--prefer-offline","@mcp-use/tunnel",String(e)]];n!==void 0&&x.push("--subdomain",n);let a=R(F,x,{stdio:["ignore","pipe","pipe"],shell:process.platform==="win32"}),p=!1,S=!1,I=()=>{S=!0};a.markShutdown=I,a.stdout.on("data",r=>{let s=r.toString(),N=s.includes("Shutting down")||s.includes("\u{1F6D1}"),C=s.includes("\u2716")||s.includes("Error:");!S&&!N&&!C&&process.stdout.write(s);let v=s.match(/https?:\/\/([a-z0-9-]+\.[a-z0-9.-]+)/i);if(v!==null&&!p){let B=v[0],A=v[1]??"",g=A.match(/^([a-z0-9-]+)\./i)?.[1]??A.split(".")[0]??"";/^[a-z0-9-]+$/i.test(g)||(console.warn(`[mcp-use] warning: extracted subdomain "${g}" does not match expected format`),g=""),p=!0,clearTimeout(T),t({url:B,subdomain:g,process:a})}}),a.stderr.on("data",r=>{let s=r.toString();!S&&!s.includes("INFO")&&!s.includes("bore_cli")&&!s.includes("Shutting down")&&!/npm warn Unknown (?:env|project|user|builtin) config/.test(s)&&process.stderr.write(r)}),a.on("error",r=>{p||(clearTimeout(T),f(new Error(`Failed to start tunnel: ${r.message}`)))}),a.on("exit",r=>{r!==0&&r!==null&&!p&&(clearTimeout(T),f(new Error(`Tunnel process exited with code ${r}`))),i===a&&(i=void 0,o=null,d?u=void 0:E())});let T=setTimeout(()=>{p||(a.kill(),f(new Error("Tunnel setup timed out")))},3e4)});return E=()=>{d||l===void 0||o!==null||c===void 0&&(c=(async()=>{for(;!d&&l!==void 0&&o===null;){console.log("[mcp-use] tunnel disconnected, restarting\u2026");let e=u??await P();try{e!==void 0&&await b(e);let n;try{n=await w(l,e)}catch(t){if(e!==void 0)console.log(`[mcp-use] subdomain "${e}" unavailable, requesting a new one\u2026`),n=await w(l,void 0);else throw t}i=n.process,o=n.url,u=n.subdomain,await _(n.subdomain),m=y;return}catch(n){console.warn(`[mcp-use] tunnel restart failed: ${n instanceof Error?n.message:String(n)}`),await M(m),m=Math.min(m*2,q)}}})().finally(()=>{c=void 0}))},{status(){return{url:o}},async start(e){if(d=!1,l=e,o!==null)return{url:o,subdomain:u??""};let n=await P();n!==void 0&&(console.log(`[mcp-use] found existing subdomain: ${n}`),await b(n));let t;try{t=await w(e,n)}catch(f){if(n!==void 0)console.log(`[mcp-use] subdomain "${n}" unavailable, requesting a new one\u2026`),t=await w(e,void 0);else throw f}return i=t.process,o=t.url,u=t.subdomain,await _(t.subdomain),{url:t.url,subdomain:t.subdomain}},async stop(){d=!0,$(),c!==void 0&&await c,u!==void 0&&await b(u),i!==void 0&&(i.kill("SIGINT"),i=void 0),l=void 0,o=null,u=void 0,m=y}}}export{W as a,H as b};
@@ -1,8 +0,0 @@
1
- import{a}from"./chunk-LNASFQWW.js";import{constants as f}from"fs";import{access as p,chmod as c,mkdir as l,readFile as m,rename as w,rm as y,writeFile as g}from"fs/promises";import{homedir as x}from"os";import{dirname as $,join as d}from"path";import{createInterface as E}from"readline/promises";var r=class extends Error{exitCode=2},s=class extends Error{code;details;constructor(n,t,o){super(t),this.code=n,this.details=o}};function P(e){return e.includes("--json")}function k(e,n,t){n?process.stdout.write(`${JSON.stringify(e)}
2
- `):t!==void 0?process.stdout.write(`${t}
3
- `):typeof e=="string"?process.stdout.write(`${e}
4
- `):process.stdout.write(`${JSON.stringify(e,null,2)}
5
- `)}function _(e,n){let t=e instanceof r,o=e instanceof s,u=o?e.code:t?"usage_error":"command_failed",i=e instanceof Error?e.message:String(e);return n?process.stderr.write(`${JSON.stringify({error:{code:u,message:i,...o&&e.details!==void 0?{details:e.details}:{}}})}
6
- `):process.stderr.write(`${i}
7
- `),t?2:1}async function v(e,n){if(n.yes)return!0;if(n.json||!process.stdin.isTTY)throw new r(`${e} Pass --yes to confirm.`);let t=E({input:process.stdin,output:process.stdout});try{return(await t.question(`${e} [y/N] `)).trim().toLowerCase()==="y"}finally{t.close()}}function h(e){a(e)}async function j(e){try{return await p(e,f.F_OK),!0}catch{return!1}}async function B(e,n){try{return JSON.parse(await m(e,"utf8"))}catch(t){if(t.code==="ENOENT")return n;throw new s("invalid_state",`Could not read ${e}.`,{cause:t instanceof Error?t.message:String(t)})}}async function F(e,n){let t=$(e);await l(t,{recursive:!0,mode:448}),await c(t,448);let o=d(t,`.${e.slice(e.lastIndexOf("/")+1)}.${process.pid}.${Date.now()}.tmp`);await g(o,`${JSON.stringify(n,null,2)}
8
- `,{mode:384}),await w(o,e),await c(e,384)}async function I(e){await y(e,{force:!0})}var L=d(x(),".mcp-use");export{r as a,s as b,P as c,k as d,_ as e,v as f,h as g,j as h,B as i,F as j,I as k,L as l};
@@ -1 +0,0 @@
1
- import{a,b}from"./chunk-OVFUQAEG.js";export{b as createTunnelManager,a as tunnelApiBase};