@mcp-use/cli 4.2.0 → 4.2.1-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as o}from"./chunk-EYLXU2LV.js";import"./chunk-F6ENE4MX.js";import"./chunk-WOT6VMZA.js";import{readFileSync as i}from"fs";import{createRequire as a}from"module";import{dirname as t,join as c,parse as m}from"path";function p(){try{let e=a(import.meta.url).resolve("mcp-use"),n=t(e),s=m(n).root;for(;n!==s;){try{let r=JSON.parse(i(c(n,"package.json"),"utf8"));if(r.name==="mcp-use"&&typeof r.version=="string")return r.version}catch{}n=t(n)}}catch{}}o(process.argv.slice(2),{frameworkVersion:p()??"4.2.0"}).then(e=>{process.exitCode=e},e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
2
+ import{a as o}from"./chunk-RJXPUWMH.js";import"./chunk-F6ENE4MX.js";import"./chunk-WOT6VMZA.js";import{readFileSync as i}from"fs";import{createRequire as a}from"module";import{dirname as t,join as c,parse as m}from"path";function p(){try{let e=a(import.meta.url).resolve("mcp-use"),n=t(e),s=m(n).root;for(;n!==s;){try{let r=JSON.parse(i(c(n,"package.json"),"utf8"));if(r.name==="mcp-use"&&typeof r.version=="string")return r.version}catch{}n=t(n)}}catch{}}o(process.argv.slice(2),{frameworkVersion:p()??"4.2.1-canary.1"}).then(e=>{process.exitCode=e},e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
@@ -1,15 +1,15 @@
1
- import{a,b as h,d as G,e as f,f as K,g as W,h as V,i as O,j as U,k as C,m as j}from"./chunk-Q6AC7LJS.js";import{createHash as Oe}from"crypto";import{rm as oe}from"fs/promises";import{join as T}from"path";import{createInterface as $e}from"readline/promises";import{parseArgs as x}from"util";var d=["-h, --help","Show this help"],g=["--json","Emit machine-readable JSON (accepted anywhere after client)"],b=new Map;function m(e,t){b.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"],g,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:[g,d]});m("remove",{usage:"mcp-use client remove <name> [options]",summary:"Immediately remove a saved server and its credentials.",options:[g,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","Authenticate or inspect 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:[g,d]});m("<name> tools describe",{usage:"mcp-use client <name> tools describe <tool> [options]",summary:"Show one tool definition.",options:[g,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)"],g,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:[g,d]});m("<name> resources read",{usage:"mcp-use client <name> resources read <uri> [options]",summary:"Read one resource.",options:[g,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:[g,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:[g,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:[["login","Authenticate this server"],["status","Show OAuth status"],["logout","Delete saved OAuth credentials"]],options:[d]});m("<name> auth login",{usage:"mcp-use client <name> auth login [options]",summary:"Authenticate a saved MCP server with OAuth.",options:[g,d]});m("<name> auth status",{usage:"mcp-use client <name> auth status [options]",summary:"Show saved OAuth status.",options:[g,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"],g,d]});function Z(e){let t=e.filter(u=>u!=="--help"&&u!=="-h"&&u!=="--json"),n=t[0];if(n===void 0)return{text:$(b.get(""))};if(n==="connect"||n==="list"||n==="remove")return{text:$(b.get(n))};let o=t[1];if(o===void 0)return{text:$(b.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:$(b.get(s))};let i=`${s} ${r}`,l=b.get(i);return l===void 0?{error:`Unknown client ${o} command: ${r}`}:{text:$(l)}}function $(e){let t=[`Usage: ${e.usage}`,e.summary];return e.commands!==void 0&&t.push(Y("Commands",e.commands)),e.options!==void 0&&t.push(Y("Options",e.options)),e.notes!==void 0&&t.push(e.notes.join(`
1
+ import{a,b as h,d as G,e as f,f as K,g as W,h as V,i as $,j as U,k as C,m as j}from"./chunk-Q6AC7LJS.js";import{createHash as $e}from"crypto";import{rm as oe}from"fs/promises";import{join as T}from"path";import{createInterface as Oe}from"readline/promises";import{parseArgs as x}from"util";var d=["-h, --help","Show this help"],g=["--json","Emit machine-readable JSON (accepted anywhere after client)"],b=new Map;function m(e,t){b.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"],g,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:[g,d]});m("remove",{usage:"mcp-use client remove <name> [options]",summary:"Immediately remove a saved server and its credentials.",options:[g,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","Authenticate or inspect 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:[g,d]});m("<name> tools describe",{usage:"mcp-use client <name> tools describe <tool> [options]",summary:"Show one tool definition.",options:[g,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)"],g,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:[g,d]});m("<name> resources read",{usage:"mcp-use client <name> resources read <uri> [options]",summary:"Read one resource.",options:[g,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:[g,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:[g,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:[["login","Authenticate this server"],["status","Show OAuth status"],["logout","Delete saved OAuth credentials"]],options:[d]});m("<name> auth login",{usage:"mcp-use client <name> auth login [options]",summary:"Authenticate a saved MCP server with OAuth.",options:[g,d]});m("<name> auth status",{usage:"mcp-use client <name> auth status [options]",summary:"Show saved OAuth status.",options:[g,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"],g,d]});function Z(e){let t=e.filter(u=>u!=="--help"&&u!=="-h"&&u!=="--json"),n=t[0];if(n===void 0)return{text:O(b.get(""))};if(n==="connect"||n==="list"||n==="remove")return{text:O(b.get(n))};let o=t[1];if(o===void 0)return{text:O(b.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:O(b.get(s))};let i=`${s} ${r}`,l=b.get(i);return l===void 0?{error:`Unknown client ${o} command: ${r}`}:{text:O(l)}}function O(e){let t=[`Usage: ${e.usage}`,e.summary];return e.commands!==void 0&&t.push(Y("Commands",e.commands)),e.options!==void 0&&t.push(Y("Options",e.options)),e.notes!==void 0&&t.push(e.notes.join(`
2
2
  `)),t.join(`
3
3
 
4
4
  `)}function Y(e,t){let n=Math.max(...t.map(([o])=>o.length));return`${e}:
5
5
  ${t.map(([o,r])=>` ${o.padEnd(n)} ${r}`).join(`
6
6
  `)}`}import{spawn as le}from"child_process";import{readFileSync as de}from"fs";import{chmod as me,mkdir as pe}from"fs/promises";import{dirname as fe,join as R,resolve as ge}from"path";import{pathToFileURL as ee}from"url";var A=R(j,"client-sdk"),w="@mcp-use/client",he="^2.0.0-alpha.0",we=[`[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 ve(e){let t=ge(e);for(;;){if(await O(R(t,"package.json")))return t;let n=fe(t);if(n===t)return;t=n}}async function te(e={}){try{return await Ce()}catch(t){if(!Q(t))throw t;if(e.allowInstall===!1)throw new h("client_install_required",`${w} is required for this command.`,{nextSteps:[{description:"Install the optional client SDK",command:`npm install ${w}`}]});let n=await ye();try{return n.location==="sandbox"?await ke():await be(n.projectRoot)}catch(o){throw Q(o)?new a(we):o}}}async function ye(){let e=Se(),t=`${w}@${e}`,n=await ve(process.cwd());if(process.stderr.write(`[mcp-use] installing ${w}\u2026
8
- `),n!==void 0){let[s,i]=Pe(t);if(await X(s,i,n)!==0)throw new h("client_install_failed",`Failed to install ${w}.`);return{location:"project",projectRoot:n}}await pe(A,{recursive:!0,mode:448}),await me(A,448);let o=R(A,"package.json");if(await O(o)||await C(o,{private:!0,dependencies:{[w]:e}}),await X("npm",["install",t],A)!==0)throw new h("client_install_failed",`Failed to install ${w}.`);return{location:"sandbox"}}function Pe(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 Se(){for(let e of["../package.json","../../package.json"])try{let t=de(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 he}async function Ce(){return D(),import("@mcp-use/client")}async function be(e){D();let t=ee(R(e,"package.json")).href;return import(await import.meta.resolve(w,t))}async function ke(){D();let e=R(A,"node_modules",w,"dist","index.js");return await import(ee(e).href)}function D(){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 Q(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 X(e,t,n){return new Promise((o,r)=>{let s=le(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 re=T(j,"client"),M=T(re,"servers.json");async function ot(e){if(e.includes("--help")||e.includes("-h")){let r=Z(e);return r.text!==void 0?(process.stdout.write(`${r.text}
7
+ `);async function ve(e){let t=ge(e);for(;;){if(await $(R(t,"package.json")))return t;let n=fe(t);if(n===t)return;t=n}}async function te(e={}){try{return await Ce()}catch(t){if(!Q(t))throw t;if(e.allowInstall===!1)throw new h("client_install_required",`${w} is required for this command.`,{nextSteps:[{description:"Install the optional client SDK",command:`npm install ${w}`}]});let n=await ye();try{return n.location==="sandbox"?await ke():await be(n.projectRoot)}catch(o){throw Q(o)?new a(we):o}}}async function ye(){let e=Se(),t=`${w}@${e}`,n=await ve(process.cwd());if(process.stderr.write(`[mcp-use] installing ${w}\u2026
8
+ `),n!==void 0){let[s,i]=Pe(t);if(await X(s,i,n)!==0)throw new h("client_install_failed",`Failed to install ${w}.`);return{location:"project",projectRoot:n}}await pe(A,{recursive:!0,mode:448}),await me(A,448);let o=R(A,"package.json");if(await $(o)||await C(o,{private:!0,dependencies:{[w]:e}}),await X("npm",["install",t],A)!==0)throw new h("client_install_failed",`Failed to install ${w}.`);return{location:"sandbox"}}function Pe(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 Se(){for(let e of["../package.json","../../package.json"])try{let t=de(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 he}async function Ce(){return D(),import("@mcp-use/client")}async function be(e){D();let t=ee(R(e,"package.json")).href;return import(await import.meta.resolve(w,t))}async function ke(){D();let e=R(A,"node_modules",w,"dist","index.js");return await import(ee(e).href)}function D(){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 Q(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 X(e,t,n){return new Promise((o,r)=>{let s=le(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 re=T(j,"client"),M=T(re,"servers.json");async function ot(e){if(e.includes("--help")||e.includes("-h")){let r=Z(e);return r.text!==void 0?(process.stdout.write(`${r.text}
9
9
  `),0):(process.stderr.write(`${r.error}
10
10
  `),2)}let t=G(e),n=e.filter(r=>r!=="--json"),o=n[0];try{if(o==="connect")return await Ae(n.slice(1),t);if(o==="list")return await Re(n.slice(1),t);if(o==="remove")return await Ee(n.slice(1),t);if(o===void 0)throw new a("Usage: mcp-use client <connect|list|remove|name>");return await Te(o,n.slice(1),t)}catch(r){return K(r instanceof TypeError?new a(r.message):r,t)}}async function Ae(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 a("Usage: mcp-use client connect <name> <url>");let[r,s]=o;Me(r);let i=new URL(s);if(!["http:","https:"].includes(i.protocol))throw new a("Client URLs must use http or https.");let l=je(n.protocol),u=ae(n["auth-timeout"]??"300000","--auth-timeout"),c=await _();if(c.servers[r]!==void 0)throw new a(`Saved server already exists: ${r}`);let p={headers:Ue(n.header??[])},P={url:i.href,oauth:n["no-oauth"]!==!0,protocol:l},k=await N(r,P,p,u,ie({noOpen:n["no-open"]===!0,json:t}),t,`mcp-use client connect ${r} <url> --no-open`);await k.discoverAuthorization();let y=k.authorization;return await k.disconnect(),c.servers[r]=P,await C(M,c),await C(q(r),p),f({name:r,url:H(P.url),protocol:l,...y?{authorization:{...y,...y.resource?{resource:H(y.resource)}:{}}}:{}},t,y?.mode==="mixed"&&!y.authenticated?`Connected and saved ${r}.
11
11
  This server is using mixed auth. Public tools are available now; run \`mcp-use client ${r} auth login\` to authenticate.`:`Connected and saved ${r}.`),0}async function Re(e,t){S(e);let n=await _(),o=Object.entries(n.servers).map(([r,s])=>({name:r,...s,url:H(s.url)}));return f(o,t,o.map(r=>`${r.name} ${r.url}`).join(`
12
- `)||"No saved servers."),0}async function Ee(e,t){let{positionals:n}=x({args:[...e],allowPositionals:!0,strict:!0,options:{}}),o=E(n,"mcp-use client remove <name>"),r=await _();if(!Object.hasOwn(r.servers,o))throw new a(`Unknown saved server: ${o}. Run \`mcp-use client list\` to see saved servers.`);return delete r.servers[o],await C(M,r),await oe(B(o),{recursive:!0,force:!0}),f({removed:o},t,`Removed ${o}.`),0}async function Te(e,t,n){let r=(await _()).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"){S(t.slice(2));let c=await O(z(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}=x({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 W(`Delete OAuth credentials for ${e}?`,{yes:c.yes===!0,json:n})&&(await oe(z(e),{recursive:!0,force:!0}),f({loggedOut:e},n,`Logged out ${e}.`)),0}}xe(e,s,i,t.slice(2));let l=await U(q(e),{}),u=await N(e,r,l,3e5,ie({noOpen:!1,json:n}),n,s==="auth"&&i==="login"?`mcp-use client ${e} auth login`:void 0);try{if(s==="auth"&&i==="login")return S(t.slice(2)),await u.authenticate(),f({name:e,authenticated:!0},n,`Authenticated ${e}.`),0;if(s==="tools"){if(i==="list"){S(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
+ `)||"No saved servers."),0}async function Ee(e,t){let{positionals:n}=x({args:[...e],allowPositionals:!0,strict:!0,options:{}}),o=E(n,"mcp-use client remove <name>"),r=await _();if(!Object.hasOwn(r.servers,o))throw new a(`Unknown saved server: ${o}. Run \`mcp-use client list\` to see saved servers.`);return delete r.servers[o],await C(M,r),await oe(B(o),{recursive:!0,force:!0}),f({removed:o},t,`Removed ${o}.`),0}async function Te(e,t,n){let r=(await _()).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"){S(t.slice(2));let c=await $(z(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}=x({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 W(`Delete OAuth credentials for ${e}?`,{yes:c.yes===!0,json:n})&&(await oe(z(e),{recursive:!0,force:!0}),f({loggedOut:e},n,`Logged out ${e}.`)),0}}xe(e,s,i,t.slice(2));let l=await U(q(e),{}),u=await N(e,r,l,3e5,ie({noOpen:!1,json:n}),n,s==="auth"&&i==="login"?`mcp-use client ${e} auth login`:void 0);try{if(s==="auth"&&i==="login")return S(t.slice(2)),await u.authenticate(),f({name:e,authenticated:!0},n,`Authenticated ${e}.`),0;if(s==="tools"){if(i==="list"){S(t.slice(2));let c=await u.listTools();return f(c,n,c.map(p=>p.description?`${p.name} - ${p.description}`:p.name).join(`
13
13
  `)),0}if(i==="describe"){let c=E(t.slice(2),`mcp-use client ${e} tools describe <tool>`),p=(await u.listTools()).find(P=>P.name===c);if(p===void 0)throw new a(`Tool not found: ${c}`);return f(p,n),0}if(i==="call")return await _e(u,e,t.slice(2),n)}if(s==="resources"){if(i==="list"){S(t.slice(2));let c=await u.listResources();return f(c,n),0}if(i==="read"){let c=E(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 S(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,I(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"){S(o);return}if(t==="auth"&&n==="login"){S(o);return}if(t==="tools"&&n==="describe"){E(o,`mcp-use client ${e} tools describe <tool>`);return}if(t==="tools"&&n==="call"){se(e,o);return}if(t==="resources"&&n==="read"){E(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]`);I(o.slice(1));return}throw new a(`Usage: mcp-use client ${e} <tools|resources|prompts|auth> ...`)}async function _e(e,t,n,o){let{tool:r,timeout:s,positionals:i}=se(t,n),l=await e.callTool(r,I(i),{timeout:s});if(l.isError===!0)throw new h("tool_error",`Tool ${r} returned an error.`,l);return f(l,o),0}function se(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}=x({args:[...t.slice(1)],allowPositionals:!0,strict:!0,options:{timeout:{type:"string",default:"30000"}}}),s=ae(o.timeout,"--timeout");return I(r),{tool:n,timeout:s,positionals:r}}async function N(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 te({allowInstall:!s});s&&(c.level="silent");let p,P=s&&t.oauth?new Promise((v,L)=>{p=L}):void 0,k=z(e),y=t.oauth?await l(t.url,{baseDir:k,authTimeoutMs:o,storageKeyPrefix:`mcp-use-cli:${e}`,openBrowser:async v=>{if(s){let L=new h("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}]});throw p?.(L),L}if(r==="never"){process.stderr.write(`Open this URL to authenticate:
14
14
  ${v}
15
- `);return}await Le(),V(v)}}):void 0,ue=t.protocol==="auto"?{protocolNegotiation:"auto"}:t.protocol==="modern"?{protocolNegotiation:{pin:"2026-07-28"}}:{protocolNegotiation:"legacy",clientOptions:{supportedProtocolVersions:["2025-11-25"]}},F=new u({mcpServers:{[e]:{url:t.url,...n.headers!==void 0?{headers:n.headers}:{},...y!==void 0?{authProvider:y}:{oauth:!1},...ue}}});try{let v=F.connect(e);return await(P===void 0?v:Promise.race([v,P]))}catch(v){throw v instanceof h&&v.code==="oauth_interaction_required"?(y?.dispose?.(),await F.closeSession?.(e),v):De(Ie(v,t.protocol),t,n)}}async function rt(e,t=3e5,n=!1){let r=(await _()).servers[e];if(r===void 0)throw new a(`Unknown saved server: ${e}`);let s=await U(q(e),{});return N(e,r,s,t,process.stdin.isTTY?"ask":"never",n)}async function st(e,t,n=!1){return N("screenshot",{url:e,oauth:!1,protocol:"auto"},{headers:t},3e5,"never",n)}function I(e){if(e.length===0)return{};if(e.length===1&&e[0]?.trimStart().startsWith("{")){let n=ne(e[0],"The JSON argument");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?ne(u,`The value for "${l}"`):u}return t}function ne(e,t){try{return JSON.parse(e)}catch(n){throw new a(`${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function ie(e){return e.json||e.noOpen||!process.stdin.isTTY?"never":"ask"}async function Le(){let e=$e({input:process.stdin,output:process.stderr});try{await e.question("This server requires OAuth. Press Enter to open your browser.")}finally{e.close()}}function Ue(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 je(e){if(e!=="auto"&&e!=="legacy"&&e!=="modern")throw new a("Invalid protocol. Expected auto, legacy, or modern.");return e}function ae(e,t){let n=Number(e);if(!Number.isInteger(n)||n<=0)throw new a(`${t} must be a positive integer.`);return n}function Me(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 H(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 _(){let e=await U(M,{servers:{}}),t={servers:{}},n=!1;for(let[o,r]of Object.entries(e.servers)){let s=Ne(r.protocol);t.servers[o]={...r,protocol:s},n||=s!==r.protocol}return n&&await C(M,t),t}function Ne(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 h("protocol_mismatch","Server does not support the requested legacy protocol."):new h("protocol_mismatch","Server does not support the requested modern protocol (stateless/sessionless, no fallback).")}function De(e,t,n){let o=He(t.url,n.headers);if(!(e instanceof Error)||o.size===0)return e;let r=ce(e.message,o);if(e instanceof h)return new h(e.code,r,J(e.details,o));let s=new Error(r);return s.name=e.name,s}function He(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 J(e,t){return typeof e=="string"?ce(e,t):Array.isArray(e)?e.map(n=>J(n,t)):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([n,o])=>[n,J(o,t)]))}function ce(e,t){let n=e;for(let o of t)n=n.replaceAll(o,"[REDACTED]");return n}function B(e){return T(re,"credentials",Oe("sha256").update(e).digest("hex"))}function q(e){return T(B(e),"credentials.json")}function z(e){return T(B(e),"oauth")}function S(e){x({args:[...e],allowPositionals:!1,strict:!0,options:{}})}function E(e,t){if(e.length!==1)throw new a(`Usage: ${t}`);return e[0]}export{ot as a,rt as b,st as c,I as d};
15
+ `);return}await Le(),V(v)}}):void 0,ue=t.protocol==="auto"?{protocolNegotiation:"auto"}:t.protocol==="modern"?{protocolNegotiation:{pin:"2026-07-28"}}:{protocolNegotiation:"legacy",clientOptions:{supportedProtocolVersions:["2025-11-25"]}},F=new u({mcpServers:{[e]:{url:t.url,...n.headers!==void 0?{headers:n.headers}:{},...y!==void 0?{authProvider:y}:{oauth:!1},...ue}}});try{let v=F.connect(e);return await(P===void 0?v:Promise.race([v,P]))}catch(v){throw v instanceof h&&v.code==="oauth_interaction_required"?(y?.dispose?.(),await F.closeSession?.(e),v):De(Ie(v,t.protocol),t,n)}}async function rt(e,t=3e5,n=!1){let r=(await _()).servers[e];if(r===void 0)throw new a(`Unknown saved server: ${e}`);let s=await U(q(e),{});return N(e,r,s,t,process.stdin.isTTY?"ask":"never",n)}async function st(e,t,n=!1){return N("screenshot",{url:e,oauth:!1,protocol:"auto"},{headers:t},3e5,"never",n)}function I(e){if(e.length===0)return{};if(e.length===1&&e[0]?.trimStart().startsWith("{")){let n=ne(e[0],"The JSON argument");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=o>0&&n[o-1]===":",s=r?o-1:o,i=r?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]=r?ne(u,`The value for "${l}"`):u}return t}function ne(e,t){try{return JSON.parse(e)}catch(n){throw new a(`${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function ie(e){return e.json||e.noOpen||!process.stdin.isTTY?"never":"ask"}async function Le(){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 Ue(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 je(e){if(e!=="auto"&&e!=="legacy"&&e!=="modern")throw new a("Invalid protocol. Expected auto, legacy, or modern.");return e}function ae(e,t){let n=Number(e);if(!Number.isInteger(n)||n<=0)throw new a(`${t} must be a positive integer.`);return n}function Me(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 H(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 _(){let e=await U(M,{servers:{}}),t={servers:{}},n=!1;for(let[o,r]of Object.entries(e.servers)){let s=Ne(r.protocol);t.servers[o]={...r,protocol:s},n||=s!==r.protocol}return n&&await C(M,t),t}function Ne(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 h("protocol_mismatch","Server does not support the requested legacy protocol."):new h("protocol_mismatch","Server does not support the requested modern protocol (stateless/sessionless, no fallback).")}function De(e,t,n){let o=He(t.url,n.headers);if(!(e instanceof Error)||o.size===0)return e;let r=ce(e.message,o);if(e instanceof h)return new h(e.code,r,J(e.details,o));let s=new Error(r);return s.name=e.name,s}function He(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 J(e,t){return typeof e=="string"?ce(e,t):Array.isArray(e)?e.map(n=>J(n,t)):e===null||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([n,o])=>[n,J(o,t)]))}function ce(e,t){let n=e;for(let o of t)n=n.replaceAll(o,"[REDACTED]");return n}function B(e){return T(re,"credentials",$e("sha256").update(e).digest("hex"))}function q(e){return T(B(e),"credentials.json")}function z(e){return T(B(e),"oauth")}function S(e){x({args:[...e],allowPositionals:!1,strict:!0,options:{}})}function E(e,t){if(e.length!==1)throw new a(`Usage: ${t}`);return e[0]}export{ot as a,rt as b,st as c,I as d};
@@ -1 +1 @@
1
- import{a,b,c,d}from"../chunk-IS5RROVD.js";import"../chunk-Q6AC7LJS.js";import"../chunk-S3WHXP7I.js";import"../chunk-WOT6VMZA.js";export{c as openDirectConnection,b as openSavedConnection,d as parseMcpArguments,a as runClient};
1
+ import{a,b,c,d}from"../chunk-VEME7ZQL.js";import"../chunk-Q6AC7LJS.js";import"../chunk-S3WHXP7I.js";import"../chunk-WOT6VMZA.js";export{c as openDirectConnection,b as openSavedConnection,d as parseMcpArguments,a as runClient};
@@ -1,4 +1,4 @@
1
- import{b as T,c as R,d as B}from"../chunk-IS5RROVD.js";import{a,b as s,d as k,e as x,f as M}from"../chunk-Q6AC7LJS.js";import"../chunk-S3WHXP7I.js";import"../chunk-WOT6VMZA.js";import{spawn as $}from"child_process";import{access as j,mkdtemp as F,rm as H,writeFile as G}from"fs/promises";import{createServer as V}from"net";import{tmpdir as J}from"os";import{basename as q,join as z,resolve as W}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]
1
+ import{b as k,c as A,d as T}from"../chunk-VEME7ZQL.js";import{a as c,b as s,d as M,e as _,f as R}from"../chunk-Q6AC7LJS.js";import"../chunk-S3WHXP7I.js";import"../chunk-WOT6VMZA.js";import{spawn as O}from"child_process";import{access as j,mkdtemp as F,rm as B,writeFile as G}from"fs/promises";import{createServer as J}from"net";import{tmpdir as V}from"os";import{basename as W,join as q,resolve as z}from"path";import{parseArgs as X}from"util";import{fileURLToPath as K}from"url";var Q=`Usage: mcp-use screenshot (--server <name> | --mcp <url>) --tool <name> [args...] [options]
2
2
 
3
3
  Call a view-backed MCP tool and capture its rendered MCP App as PNG.
4
4
 
@@ -37,15 +37,15 @@ Examples:
37
37
  Exit codes:
38
38
  0 Capture succeeded or help
39
39
  2 Invalid arguments
40
- 1 MCP, tool, Inspector, browser, readiness, or write failure`;async function ke(r){if(r.some(o=>o==="--help"||o==="-h"))return process.stdout.write(`${Q}
41
- `),0;let e=k(r),t,n,i;try{let{values:o,positionals:c}=K({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:"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 a("Exactly one of --server or --mcp is required.");if(o.tool===void 0)throw new a("--tool is required.");if(o.server!==void 0&&o.header!==void 0)throw new a("--header is valid only with --mcp.");if(o.theme!=="light"&&o.theme!=="dark")throw new a("--theme must be light or dark.");let d=A(o.width,"--width"),y=A(o.height,"--height"),l=Number(o["device-scale-factor"]);if(!Number.isFinite(l)||l<=0||l>4)throw new a("--device-scale-factor must be greater than 0 and at most 4.");let p=we(o.timeout,"--timeout"),b=fe(o.delay,"--delay"),L=me(o.header??[]);t=o.server!==void 0?await T(o.server,3e5,e):await R(new URL(o.mcp).href,L,e);let P=(await t.listTools()).find(O=>O.name===o.tool);if(P===void 0)throw new s("tool_not_found",`Tool not found: ${o.tool}`);let w=te(P),C=B(c),f=await t.callTool(o.tool,C,{timeout:p});if(f.isError===!0)throw new s("tool_failed",`Tool ${o.tool} returned an error.`,f);let I=await t.readResource(w);re(I),i=o.inspector===void 0?await Y(p):void 0;let S=(o.inspector??i.origin).replace(/\/+$/,"");await N(S,p);let E=ne(w),m=new URL(`${S}/inspector/preview/${encodeURIComponent(E)}`);m.searchParams.set("protocol","1"),m.searchParams.set("theme",o.theme),m.searchParams.set("width",String(d)),n=o["cdp-url"]!==void 0?await ie(o["cdp-url"]):await oe(),await n.cdp.send("Emulation.setDeviceMetricsOverride",{width:d,height:y,deviceScaleFactor:l,mobile:!1},n.sessionId),await n.cdp.send("Page.enable",{},n.sessionId),await n.cdp.send("Runtime.enable",{},n.sessionId),await n.cdp.send("Page.addScriptToEvaluateOnNewDocument",{source:`globalThis.__mcpUsePreviewBundle = ${he({resourceUri:w,resourceContents:I,toolInput:C,toolOutput:f})};`},n.sessionId),await n.cdp.send("Page.navigate",{url:m.href},n.sessionId),await se(n,p),await ce(n,o["wait-for"],p),b>0&&await u(b);let h=await de(n),_=await n.cdp.send("Page.captureScreenshot",{format:"png",captureBeyondViewport:!0,fromSurface:!0,clip:{...h,scale:1}},n.sessionId);if(typeof _.data!="string")throw new s("capture_failed","Chrome returned no screenshot data.");let g=W(o.output??`${E}-${new Date().toISOString().replace(/[:.]/g,"-")}.png`);return await G(g,Buffer.from(_.data,"base64")),x({path:g,width:h.width,height:h.height,viewport:{width:d,height:y},deviceScaleFactor:l,theme:o.theme},e,g),0}catch(o){return M(o instanceof TypeError?new a(o.message):o,e)}finally{await n?.close().catch(()=>{}),await i?.close().catch(()=>{}),await t?.disconnect().catch(()=>{})}}async function Y(r){let e=await D(),t=import.meta.resolve("@mcp-use/inspector"),n=X(new URL("../cli.js",t)),i=$(process.execPath,[n,"--port",String(e),"--no-open"],{stdio:"ignore"}),o=`http://127.0.0.1:${e}`;try{await Z(o,i,Math.min(r,1e4))}catch(c){throw i.kill("SIGTERM"),c}return{origin:o,async close(){await ee(i)}}}async function Z(r,e,t){let n=Date.now()+t;for(;Date.now()<n;){if(e.exitCode!==null)throw new s("inspector_start_failed",`Packaged Inspector exited before becoming ready (code ${e.exitCode}).`);try{await N(r,Math.min(1e3,t));return}catch{await u(100)}}throw new s("inspector_start_failed","Packaged Inspector did not start in time.")}async function ee(r){r.exitCode===null&&(r.kill("SIGTERM"),await Promise.race([new Promise(e=>r.once("exit",()=>e())),u(2e3)]),r.exitCode===null&&r.kill("SIGKILL"))}async function N(r,e){let t=await fetch(`${r}/inspector/health`,{signal:AbortSignal.timeout(e)});if(!t.ok)throw new s("incompatible_inspector",`Inspector health check failed (${t.status}).`);let n=await t.json();if(n.status!=="ok"||n.protocol!=="mcp-use-inspector-preview"||n.version!==1||!n.capabilities?.includes("view-preview"))throw new s("incompatible_inspector","Inspector does not support mcp-use-inspector-preview version 1.")}function te(r){let e=r!==null&&typeof r=="object"?r._meta:void 0,n=(e?.ui!==null&&typeof e?.ui=="object"?e.ui.resourceUri:void 0)??e?.["ui/resourceUri"];if(typeof n!="string")throw new s("missing_view","Tool does not advertise an MCP Apps UI resource.");return n}function re(r){let e=r!==null&&typeof r=="object"?r.contents:void 0;if(!Array.isArray(e))throw new s("invalid_view","View resource has no contents.");let t=e.find(n=>n!==null&&typeof n=="object"&&typeof n.text=="string");if(t===void 0)throw new s("invalid_view","View resource has no HTML document.");return t.text}function ne(r){let e=new URL(r);return q(e.pathname).replace(/\.html$/,"")||e.hostname}async function oe(){let r=await le(),e=await D(),t=await F(z(J(),"mcp-use-chrome-")),n=$(r,[`--remote-debugging-port=${e}`,`--user-data-dir=${t}`,"--headless=new","--no-first-run","--no-default-browser-check","about:blank"],{stdio:"ignore"});try{let i=await pe(`http://127.0.0.1:${e}/json/version`,1e4),o=await U(i.webSocketDebuggerUrl);return{...o,async close(){await o.close(),n.kill("SIGTERM"),await H(t,{recursive:!0,force:!0})}}}catch(i){throw n.kill("SIGTERM"),await H(t,{recursive:!0,force:!0}),i}}async function ie(r){return U(r)}async function U(r){let e=await v.connect(r),t=await e.send("Target.createTarget",{url:"about:blank"}),n=await e.send("Target.attachToTarget",{targetId:t.targetId,flatten:!0});return{cdp:e,sessionId:n.sessionId,async close(){await e.send("Target.closeTarget",{targetId:t.targetId}).catch(()=>{}),e.close()}}}async function se(r,e){let t=Date.now()+e;for(;Date.now()<t;){if((await r.cdp.send("Runtime.evaluate",{expression:"document.readyState",returnByValue:!0},r.sessionId)).result?.value==="complete")return;await u(100)}throw new s("browser_timeout","Inspector page did not load in time.")}function ae(r){if(r?.error==="view_load_failed")return new s("view_load_failed",r.errorMessage?`MCP App failed to initialize: ${r.errorMessage}`:"MCP App failed to initialize.")}async function ce(r,e,t){let n=Date.now()+t;for(;Date.now()<n;){let i=`(() => ({
40
+ 1 MCP, tool, Inspector, browser, readiness, or write failure`;async function Re(t){if(t.some(o=>o==="--help"||o==="-h"))return process.stdout.write(`${Q}
41
+ `),0;let e=M(t),n,r,i;try{let{values:o,positionals:a}=X({args:[...t],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 d=H(o.width,"--width"),y=H(o.height,"--height"),l=Number(o["device-scale-factor"]);if(!Number.isFinite(l)||l<=0||l>4)throw new c("--device-scale-factor must be greater than 0 and at most 4.");let p=he(o.timeout,"--timeout"),b=ge(o.delay,"--delay"),D=fe(o.header??[]);n=o.server!==void 0?await k(o.server,3e5,e):await A(new URL(o.mcp).href,D,e);let P=(await n.listTools()).find(U=>U.name===o.tool);if(P===void 0)throw new s("tool_not_found",`Tool not found: ${o.tool}`);let w=te(P),C=T(a),f=await n.callTool(o.tool,C,{timeout:p});if(f.isError===!0)throw new s("tool_failed",`Tool ${o.tool} returned an error.`,f);let S=await n.readResource(w);re(S),i=o.inspector===void 0?await Y(p):void 0;let I=(o.inspector??i.origin).replace(/\/+$/,"");await L(I,p);let E=ne(w),m=new URL(`${I}/inspector/preview/${encodeURIComponent(E)}`);m.searchParams.set("protocol","1"),m.searchParams.set("theme",o.theme),m.searchParams.set("width",String(d)),r=o["cdp-url"]!==void 0?await ie(o["cdp-url"]):await oe(),await r.cdp.send("Emulation.setDeviceMetricsOverride",{width:d,height:y,deviceScaleFactor:l,mobile:!1},r.sessionId),await r.cdp.send("Page.enable",{},r.sessionId),await r.cdp.send("Runtime.enable",{},r.sessionId),await r.cdp.send("Page.addScriptToEvaluateOnNewDocument",{source:`globalThis.__mcpUsePreviewBundle = ${ve({resourceUri:w,resourceContents:S,toolInput:C,toolOutput:f})};`},r.sessionId),await r.cdp.send("Page.navigate",{url:m.href},r.sessionId),await se(r,p),await ce(r,o["wait-for"],p),b>0&&await u(b);let h=await de(r),x=await r.cdp.send("Page.captureScreenshot",{format:"png",captureBeyondViewport:!0,fromSurface:!0,clip:{...h,scale:1}},r.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:h.width,height:h.height,viewport:{width:d,height:y},deviceScaleFactor:l,theme:o.theme},e,g),0}catch(o){return R(o instanceof TypeError?new c(o.message):o,e)}finally{await r?.close().catch(()=>{}),await i?.close().catch(()=>{}),await n?.disconnect().catch(()=>{})}}async function Y(t){let e=await $(),n=import.meta.resolve("@mcp-use/inspector"),r=K(new URL("../cli.js",n)),i=O(process.execPath,[r,"--port",String(e),"--no-open"],{stdio:"ignore"}),o=`http://127.0.0.1:${e}`;try{await Z(o,i,Math.min(t,1e4))}catch(a){throw i.kill("SIGTERM"),a}return{origin:o,async close(){await ee(i)}}}async function Z(t,e,n){let r=Date.now()+n;for(;Date.now()<r;){if(e.exitCode!==null)throw new s("inspector_start_failed",`Packaged Inspector exited before becoming ready (code ${e.exitCode}).`);try{await L(t,Math.min(1e3,n));return}catch{await u(100)}}throw new s("inspector_start_failed","Packaged Inspector did not start in time.")}async function ee(t){t.exitCode===null&&(t.kill("SIGTERM"),await Promise.race([new Promise(e=>t.once("exit",()=>e())),u(2e3)]),t.exitCode===null&&t.kill("SIGKILL"))}async function L(t,e){let n=await fetch(`${t}/inspector/health`,{signal:AbortSignal.timeout(e)});if(!n.ok)throw new s("incompatible_inspector",`Inspector health check failed (${n.status}).`);let r=await n.json();if(r.status!=="ok"||r.protocol!=="mcp-use-inspector-preview"||r.version!==1||!r.capabilities?.includes("view-preview"))throw new s("incompatible_inspector","Inspector does not support mcp-use-inspector-preview version 1.")}function te(t){let e=t!==null&&typeof t=="object"?t._meta:void 0,r=(e?.ui!==null&&typeof e?.ui=="object"?e.ui.resourceUri:void 0)??e?.["ui/resourceUri"];if(typeof r!="string")throw new s("missing_view","Tool does not advertise an MCP Apps UI resource.");return r}function re(t){let e=t!==null&&typeof t=="object"?t.contents:void 0;if(!Array.isArray(e))throw new s("invalid_view","View resource has no contents.");let n=e.find(r=>r!==null&&typeof r=="object"&&typeof r.text=="string");if(n===void 0)throw new s("invalid_view","View resource has no HTML document.");return n.text}function ne(t){let e=new URL(t);return W(e.pathname).replace(/\.html$/,"")||e.hostname}async function oe(){let t=await me(),e=await $(),n=await F(q(V(),"mcp-use-chrome-")),r=O(t,[`--remote-debugging-port=${e}`,`--user-data-dir=${n}`,"--headless=new","--no-first-run","--no-default-browser-check","about:blank"],{stdio:"ignore"});try{let i=await we(`http://127.0.0.1:${e}/json/version`,1e4),o=await N(i.webSocketDebuggerUrl);return{...o,async close(){await o.close(),r.kill("SIGTERM"),await B(n,{recursive:!0,force:!0})}}}catch(i){throw r.kill("SIGTERM"),await B(n,{recursive:!0,force:!0}),i}}async function ie(t){return N(t)}async function N(t){let e=await v.connect(t),n=await e.send("Target.createTarget",{url:"about:blank"}),r=await e.send("Target.attachToTarget",{targetId:n.targetId,flatten:!0});return{cdp:e,sessionId:r.sessionId,async close(){await e.send("Target.closeTarget",{targetId:n.targetId}).catch(()=>{}),e.close()}}}async function se(t,e){let n=Date.now()+e;for(;Date.now()<n;){if((await t.cdp.send("Runtime.evaluate",{expression:"document.readyState",returnByValue:!0},t.sessionId)).result?.value==="complete")return;await u(100)}throw new s("browser_timeout","Inspector page did not load in time.")}function ae(t){if(t?.error==="view_load_failed")return new s("view_load_failed",t.errorMessage?`MCP App failed to initialize: ${t.errorMessage}`:"MCP App failed to initialize.")}async function ce(t,e,n){let r=Date.now()+n;for(;Date.now()<r;){let i=`(() => ({
42
42
  ready: document.body?.dataset.viewReady === "true",
43
43
  error: document.body?.dataset.viewError || null,
44
44
  errorMessage: document.body?.dataset.viewErrorMessage || null,
45
45
  selector: ${JSON.stringify(e)} === undefined || !!document.querySelector(${JSON.stringify(e??"")})
46
- }))()`,c=(await r.cdp.send("Runtime.evaluate",{expression:i,returnByValue:!0},r.sessionId)).result?.value,d=ae(c);if(d)throw d;if(c?.ready===!0&&c.selector===!0)return;await u(100)}throw new s("browser_timeout","View did not become ready in time.")}async function de(r){let e=await r.cdp.send("Runtime.evaluate",{expression:`(() => {
46
+ }))()`,a=(await t.cdp.send("Runtime.evaluate",{expression:i,returnByValue:!0},t.sessionId)).result?.value,d=ae(a);if(d)throw d;if(a?.ready===!0&&a.selector===!0)return;await u(100)}throw new s("browser_timeout","View did not become ready in time.")}async function de(t){let e=await t.cdp.send("Runtime.evaluate",{expression:`(() => {
47
47
  const frame = document.querySelector("iframe");
48
48
  if (!frame) return null;
49
49
  const rect = frame.getBoundingClientRect();
50
50
  return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
51
- })()`,returnByValue:!0},r.sessionId);return ue(e.result?.value)}function ue(r){if(r===null||typeof r!="object")throw new s("capture_failed","Inspector preview did not expose rendered widget bounds.");let e=r;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 n=Math.floor(e.x),i=Math.floor(e.y);return{x:n,y:i,width:Math.ceil(e.x+e.width)-n,height:Math.ceil(e.y+e.height)-i}}var v=class r{#t;#r=1;#e=new Map;constructor(e){this.#t=e,e.addEventListener("message",t=>{let n=JSON.parse(String(t.data));if(n.id===void 0)return;let i=this.#e.get(n.id);i!==void 0&&(this.#e.delete(n.id),n.error!==void 0?i.reject(new Error(n.error.message??"CDP command failed.")):i.resolve(n.result))}),e.addEventListener("close",()=>{for(let t of this.#e.values())t.reject(new Error("Chrome DevTools connection closed."));this.#e.clear()})}static async connect(e){let t=new WebSocket(e);return await new Promise((n,i)=>{t.addEventListener("open",()=>n(),{once:!0}),t.addEventListener("error",()=>i(new Error("Could not connect to Chrome DevTools.")),{once:!0})}),new r(t)}send(e,t={},n){let i=this.#r++;return new Promise((o,c)=>{this.#e.set(i,{resolve:o,reject:c}),this.#t.send(JSON.stringify({id:i,method:e,params:t,...n!==void 0?{sessionId:n}:{}}))})}close(){this.#t.close()}};async function le(){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(t=>t!==void 0&&t!=="");for(let t of e)try{return await j(t),t}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,e)=>{let t=V();t.once("error",e),t.listen(0,"127.0.0.1",()=>{let n=t.address(),i=typeof n=="object"&&n!==null?n.port:0;t.close(o=>o?e(o):r(i))})})}async function pe(r,e){let t=Date.now()+e;for(;Date.now()<t;){try{let n=await fetch(r);if(n.ok)return await n.json()}catch{}await u(100)}throw new s("chrome_start_failed","Chrome DevTools did not start.")}function me(r){let e={};for(let t of r){let n=t.indexOf(":");if(n<=0)throw new a(`Invalid header: ${t}`);e[t.slice(0,n).trim()]=t.slice(n+1).trim()}return e}function we(r,e){let t=Number(r);if(!Number.isFinite(t)||t<=0)throw new a(`${e} must be positive.`);return t}function A(r,e){let t=Number(r);if(!Number.isInteger(t)||t<1||t>1e7)throw new a(`${e} must be an integer from 1 to 10000000.`);return t}function fe(r,e){let t=Number(r);if(!Number.isFinite(t)||t<0)throw new a(`${e} must be non-negative.`);return t}function he(r){return JSON.stringify(r).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function u(r){return new Promise(e=>setTimeout(e,r))}export{ue as normalizeCaptureBounds,A as parseDimension,ae as readyStateFailure,ke as runScreenshot};
51
+ })()`,returnByValue:!0},t.sessionId);return ue(e.result?.value)}function ue(t){if(t===null||typeof t!="object")throw new s("capture_failed","Inspector preview did not expose rendered widget bounds.");let e=t;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 r=Math.floor(e.x),i=Math.floor(e.y);return{x:r,y:i,width:Math.ceil(e.x+e.width)-r,height:Math.ceil(e.y+e.height)-i}}var v=class t{#t;#r=1;#e=new Map;constructor(e){this.#t=e,e.addEventListener("message",n=>{let r=JSON.parse(String(n.data));if(r.id===void 0)return;let i=this.#e.get(r.id);i!==void 0&&(this.#e.delete(r.id),r.error!==void 0?i.reject(new Error(r.error.message??"CDP command failed.")):i.resolve(r.result))}),e.addEventListener("close",()=>{for(let n of this.#e.values())n.reject(new Error("Chrome DevTools connection closed."));this.#e.clear()})}static async connect(e){let n=new WebSocket(e);return await new Promise((r,i)=>{n.addEventListener("open",()=>r(),{once:!0}),n.addEventListener("error",()=>i(new Error("Could not connect to Chrome DevTools.")),{once:!0})}),new t(n)}send(e,n={},r){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:n,...r!==void 0?{sessionId:r}:{}}))})}close(){this.#t.close()}},le=[["PROGRAMFILES","Google\\Chrome\\Application\\chrome.exe"],["LOCALAPPDATA","Google\\Chrome\\Application\\chrome.exe"],["PROGRAMFILES(X86)","Google\\Chrome\\Application\\chrome.exe"],["PROGRAMFILES(X86)","Microsoft\\Edge\\Application\\msedge.exe"],["PROGRAMFILES","Microsoft\\Edge\\Application\\msedge.exe"],["PROGRAMFILES","BraveSoftware\\Brave-Browser\\Application\\brave.exe"],["LOCALAPPDATA","BraveSoftware\\Brave-Browser\\Application\\brave.exe"]];function pe(t,e){let n=e.MCP_USE_CHROME_PATH??e.PUPPETEER_EXECUTABLE_PATH??e.CHROME_PATH,r=t==="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"]:t==="win32"?le.flatMap(([i,o])=>{let a=e[i];return a?[`${a}\\${o}`]:[]}):["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser"];return n?[n,...r]:r}async function me(){for(let t of pe(process.platform,process.env))try{return await j(t),t}catch{}throw new s("chrome_not_found","Chrome, Chromium, Edge, or Brave was not found. Set MCP_USE_CHROME_PATH.")}function $(){return new Promise((t,e)=>{let n=J();n.once("error",e),n.listen(0,"127.0.0.1",()=>{let r=n.address(),i=typeof r=="object"&&r!==null?r.port:0;n.close(o=>o?e(o):t(i))})})}async function we(t,e){let n=Date.now()+e;for(;Date.now()<n;){try{let r=await fetch(t);if(r.ok)return await r.json()}catch{}await u(100)}throw new s("chrome_start_failed","Chrome DevTools did not start.")}function fe(t){let e={};for(let n of t){let r=n.indexOf(":");if(r<=0)throw new c(`Invalid header: ${n}`);e[n.slice(0,r).trim()]=n.slice(r+1).trim()}return e}function he(t,e){let n=Number(t);if(!Number.isFinite(n)||n<=0)throw new c(`${e} must be positive.`);return n}function H(t,e){let n=Number(t);if(!Number.isInteger(n)||n<1||n>1e7)throw new c(`${e} must be an integer from 1 to 10000000.`);return n}function ge(t,e){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new c(`${e} must be non-negative.`);return n}function ve(t){return JSON.stringify(t).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function u(t){return new Promise(e=>setTimeout(e,t))}export{pe as browserCandidates,ue as normalizeCaptureBounds,H as parseDimension,ae as readyStateFailure,Re as runScreenshot};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a}from"./chunk-EYLXU2LV.js";import"./chunk-F6ENE4MX.js";import"./chunk-WOT6VMZA.js";export{a as main};
1
+ import{a}from"./chunk-RJXPUWMH.js";import"./chunk-F6ENE4MX.js";import"./chunk-WOT6VMZA.js";export{a as main};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcp-use/cli",
3
3
  "type": "module",
4
- "version": "4.2.0",
4
+ "version": "4.2.1-canary.1",
5
5
  "description": "Prebuilt CLI, development server, and build pipeline for mcp-use",
6
6
  "author": "mcp-use, Inc.",
7
7
  "license": "MIT",
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "peerDependencies": {
57
57
  "@mcp-use/client": "^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5 || ^2.2.0 || ^2.2.1 || ^2.2.2 || ^2.2.3 || ^2.2.4 || ^2.2.5 || ^2.3.0 || ^2.3.1 || ^2.3.2 || ^2.3.3 || ^2.3.4 || ^2.3.5 || ^2.4.0",
58
- "@mcp-use/inspector": "^20.3.8 || ^20.3.9 || ^20.3.10 || ^20.3.11 || ^20.3.12 || ^20.3.13 || ^20.3.14"
58
+ "@mcp-use/inspector": "^20.3.8 || ^20.3.9 || ^20.3.10 || ^20.3.11 || ^20.3.12 || ^20.3.13 || ^20.3.14 || ^20.3.15-canary.0"
59
59
  },
60
60
  "peerDependenciesMeta": {
61
61
  "@mcp-use/client": {
File without changes