@gaiventures/pilotfish-mcp 0.1.40 → 0.1.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -10
- package/cli.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# pilotfish MCP
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp)
|
|
4
|
-
[](
|
|
4
|
+
[](https://opensource.org/license/mit)
|
|
5
5
|
|
|
6
6
|
Give your AI agent a real Chrome browser on your own computer. It works with Claude Code, Codex CLI, Cursor,
|
|
7
7
|
Claude Desktop, VS Code and any other [MCP](https://modelcontextprotocol.io) client.
|
|
@@ -13,8 +13,9 @@ picks each step, and pilotfish carries it out, checks it and tells the agent wha
|
|
|
13
13
|
claude mcp add pilotfish -- npx -y @gaiventures/pilotfish-mcp
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
> **Want pilotfish to do the whole task for you?**
|
|
17
|
-
>
|
|
16
|
+
> **Want pilotfish to do the whole task for you?**
|
|
17
|
+
> [pilotfish managed](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp-managed) runs it in our cloud
|
|
18
|
+
> browser, signed in with your saved logins, and hands your agent the answer. See "Local or managed?" below.
|
|
18
19
|
|
|
19
20
|
## Why pilotfish
|
|
20
21
|
|
|
@@ -32,15 +33,17 @@ claude mcp add pilotfish -- npx -y @gaiventures/pilotfish-mcp
|
|
|
32
33
|
|
|
33
34
|
## Local or managed?
|
|
34
35
|
|
|
35
|
-
This package is the local version. **pilotfish managed**
|
|
36
|
-
|
|
36
|
+
This package is the local version. **pilotfish managed**
|
|
37
|
+
([`@gaiventures/pilotfish-mcp-managed`](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp-managed)) is the
|
|
38
|
+
same browser engine run for you in the cloud, as a paid service on your organization's pilotfish account.
|
|
37
39
|
|
|
38
40
|
| | **Local** (this package) | **Managed** |
|
|
39
41
|
| --- | --- | --- |
|
|
40
42
|
| Who does the work | Your agent's model, one step at a time | pilotfish runs the whole task and returns the result |
|
|
41
43
|
| Your agent's tokens | Every page it reads | A call or two per task |
|
|
42
44
|
| Browser | Chrome on your computer, your IP | pilotfish's cloud browser, on even when your computer is off |
|
|
43
|
-
| Sign-ins | You sign in each time; nothing is kept | Saved logins and sessions, two-factor codes, phone sign-in by code |
|
|
45
|
+
| Sign-ins | You sign in each time; nothing is kept | Saved logins and sessions (several accounts a site), two-factor codes, phone sign-in by code |
|
|
46
|
+
| Tasks for your product's users | No | Identities: each user's logins, sessions, IP and device kept apart, and the cost per user |
|
|
44
47
|
| Sites that block bots | You clear each check yourself | Residential IPs, stealth browsing and CAPTCHA solving, with you as the last resort |
|
|
45
48
|
| Watching and history | The browser window | Live view, take control, replays, per-task cost |
|
|
46
49
|
| Price | Free | Pay as you go, from $10 of credit |
|
|
@@ -58,9 +61,19 @@ hands you each sign-in the result marks `NEEDS A PERSON`. With managed, send the
|
|
|
58
61
|
`browser_task`: pilotfish splits it into parts, asks for every sign-in at the start, carries what each site gives
|
|
59
62
|
to the next and checks the end result. Split the work yourself only for steps that are not browser work.
|
|
60
63
|
|
|
61
|
-
**Get started with managed:**
|
|
62
|
-
|
|
63
|
-
|
|
64
|
+
**Get started with managed:**
|
|
65
|
+
|
|
66
|
+
1. [Sign up with Google](https://pilotfish.gai.ventures/signup) and name your organization (you become its admin),
|
|
67
|
+
or accept an emailed invitation to join one.
|
|
68
|
+
2. An admin adds credits under **Usage → Credits** in the app (pay as you go, from $10). Members run tasks on the
|
|
69
|
+
organization's credits, within any allowance an admin sets for them.
|
|
70
|
+
3. Connect your agent to `https://pilotfish-be.gai.ventures/mcp` and sign in when it asks
|
|
71
|
+
(`claude mcp add --transport http pilotfish https://pilotfish-be.gai.ventures/mcp`, then `/mcp` in Claude Code).
|
|
72
|
+
Scripts and clients that cannot sign in use one of the organization's API keys, which its admins make in
|
|
73
|
+
**Org settings → API keys**.
|
|
74
|
+
|
|
75
|
+
The [managed package's page](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp-managed) has every client's
|
|
76
|
+
setup, the tools, roles, limits and prices.
|
|
64
77
|
|
|
65
78
|
## Requirements
|
|
66
79
|
|
|
@@ -108,7 +121,9 @@ In Cursor's `~/.cursor/mcp.json` (or `.cursor/mcp.json` in a project), Claude De
|
|
|
108
121
|
}
|
|
109
122
|
```
|
|
110
123
|
|
|
111
|
-
Settings go in an `env` object next to `args`.
|
|
124
|
+
Settings go in an `env` object next to `args`. `npx -y` runs the newest release; to stay on one, put its number
|
|
125
|
+
after the name (`@gaiventures/pilotfish-mcp@<version>`). `npx -y @gaiventures/pilotfish-mcp --version` prints the
|
|
126
|
+
version you have.
|
|
112
127
|
|
|
113
128
|
The browser opens in its own window, where you sign in or solve a CAPTCHA when a page needs a person.
|
|
114
129
|
`PILOTFISH_HEADLESS=1` hides it; on a Linux machine without a display it is hidden already.
|
|
@@ -194,6 +209,18 @@ pilotfish connects only to the sites your agent opens, plus the public ad-block
|
|
|
194
209
|
uBlock Origin's filters), downloaded about once a week and cached in `~/.pilotfish/adblock`. No telemetry, no
|
|
195
210
|
pilotfish servers, no model providers.
|
|
196
211
|
|
|
212
|
+
## Troubleshooting
|
|
213
|
+
|
|
214
|
+
- **"No Chromium executable found":** install Google Chrome, or set `PILOTFISH_CHROME` to the path of Chrome, Edge
|
|
215
|
+
or Chromium.
|
|
216
|
+
- **The server does not start on Windows:** start `npx` through `cmd /c` (see Claude Code above), and check
|
|
217
|
+
`node --version` is 22 or newer.
|
|
218
|
+
- **A call times out while you sign in:** raise your client's tool timeout above 300 seconds (Codex:
|
|
219
|
+
`tool_timeout_sec`), since `browser_resume` waits up to 300 s for you.
|
|
220
|
+
- **A site keeps blocking the browser:** this package uses your own IP and a plain Chrome, and never solves CAPTCHAs.
|
|
221
|
+
Clear the check in the browser window yourself, or use
|
|
222
|
+
[pilotfish managed](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp-managed).
|
|
223
|
+
|
|
197
224
|
## More from pilotfish
|
|
198
225
|
|
|
199
226
|
- [pilotfish managed](https://www.npmjs.com/package/@gaiventures/pilotfish-mcp-managed): whole tasks in the cloud,
|
package/cli.js
CHANGED
|
@@ -451,7 +451,7 @@ return __pfClassify("Accept all") === "accept" && __pfClassify("Reject all") ===
|
|
|
451
451
|
return click.call(this);
|
|
452
452
|
};
|
|
453
453
|
})();
|
|
454
|
-
${us(Nr(Lr,"autoconsent.playwright.js"),"utf8")}`,lh=3,dh=2500,uh=6500,hh=6e3,ph=3e3,fh=1500,mh=3e3,gh=4e3;function wh(n,e){if(n.doneAt)return"opted_out";if(n.optOut===!1)return"failed";if(n.optOut===!0)return e-n.optOutAt>ph?"opted_out":"pending";if(n.popupAt)return"pending";if(n.detectedAt)return e-n.detectedAt<uh?"pending":"no_cmp";let t=n.topLifecycle!=="nothingDetected",s=l((o,i)=>e-o>=dh&&i!==void 0&&n.topAttempts>=i+lh,"quiet");return n.cmpRequestAt&&e-n.cmpRequestAt<hh&&t&&!s(n.cmpRequestAt,n.roundAtCmpRequest)||!n.topInitAt&&/^https?:/.test(n.url)&&e-n.navAt<fh||n.topInitAt&&n.topAttempts<2&&e-n.topInitAt<mh||n.patternsAt&&e-n.patternsAt<gh&&t&&!s(n.patternsAt,n.roundAtPatterns)?"pending":"no_cmp"}l(wh,"outcomeOf");var ds=class{static{l(this,"ConsentEngine")}opts;emitter=new th;pages=new WeakMap;disposers=new Set;armed=new WeakSet;retried=new WeakSet;retryTimers=new Set;disposed=!1;config;constructor(e={}){if(this.opts=e,this.config=rh(e),this.config.autoAction!=="optOut"||!["off","reject"].includes(this.config.heuristicMode))throw new Error("ConsentEngine only ever opts out")}on(e,t){return this.emitter.on(e,t),()=>this.emitter.off(e,t)}consentStatus(e){let t=this.state(e),s=Date.now(),o=wh(t,s),i=o==="opted_out"?t.doneAt??t.optOutAt:s;return{cmp:t.cmp,outcome:o,ms:Math.max(0,i-t.navAt),url:t.url,...t.cosmetic!==void 0?{cosmetic:t.cosmetic}:{},...t.selfTest!==void 0?{selfTest:t.selfTest}:{},refusedClicks:t.refused,frames:t.frames.size}}async waitForConsent(e,t=1e4){let s=Date.now()+t;for(;;){let o=this.consentStatus(e);if(o.outcome!=="pending"||Date.now()>=s||e.closed)return o;await new Promise(i=>setTimeout(i,Math.min(100,Math.max(1,s-Date.now()))))}}dispose(){this.disposed=!0;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear();for(let e of this.disposers)e();this.disposers.clear()}initSession=l(async e=>{let t=e.session,s=e.page;if(!e.isMain&&xe(e.url)||this.armed.has(t))return;this.armed.add(t);let o=new Map,i=[()=>this.armed.delete(t)],r;try{[,r]=await Promise.all([t.send("Runtime.addBinding",{name:Xe,executionContextName:In},{timeoutMs:5e3}),t.send("Page.addScriptToEvaluateOnNewDocument",{source:ch,worldName:In,runImmediately:!0},{timeoutMs:5e3})])}catch(p){if(this.armed.delete(t),e.isMain&&!this.retried.has(t)&&!this.disposed){this.retried.add(t);let f=setTimeout(()=>{this.retryTimers.delete(f),this.disposed||this.initSession(e).catch(()=>{})},2e3);f.unref?.(),this.retryTimers.add(f)}throw p}let a=l(()=>{for(let p of i)p();t.send("Page.removeScriptToEvaluateOnNewDocument",{identifier:r.identifier}).catch(()=>{}),t.send("Runtime.removeBinding",{name:Xe}).catch(()=>{})},"dispose");this.disposers.add(a),i.push(()=>this.disposers.delete(a));let c=l(async(p,f,g)=>{if(!/^https?:/.test(f)||!g&&xe(f))return;let{executionContextId:w}=await t.send("Page.createIsolatedWorld",{frameId:p,worldName:In,grantUniveralAccess:!1},{timeoutMs:5e3});o.set(w,{frameId:p,mainFrame:g}),await t.send("Runtime.addBinding",{name:Xe,executionContextId:w},{timeoutMs:5e3}),await t.send("Runtime.evaluate",{contextId:w,expression:"globalThis.__pfAcFlush && __pfAcFlush()",returnByValue:!0},{timeoutMs:5e3})},"arm"),d=l((p,f,g)=>{c(p,f,g).catch(w=>{/not found|Cannot find|No frame|detached|closed|destroyed|navigated/i.test(String(w))||this.emit("error",{page:s,frameId:p,url:f,error:`arm: ${String(w)}`})})},"armSafe");i.push(t.on("Page.frameNavigated",p=>{let f=e.isMain&&!p.frame.parentId;f&&this.reset(s,p.frame.url),d(p.frame.id,p.frame.url,f)}),t.on("Runtime.bindingCalled",p=>{if(p.name!==Xe)return;let f=o.get(p.executionContextId);f&&this.onMessage(t,s,p.executionContextId,f,p.payload).catch(()=>{})}),t.on("Network.requestWillBeSent",p=>{if(!yr(p.request.url))return;let f=this.state(s);f.cmpRequestAt===void 0&&(f.cmpRequestAt=Date.now(),f.roundAtCmpRequest=f.topAttempts)}));let{frameTree:u}=await t.send("Page.getFrameTree"),h=l((p,f)=>{d(p.frame.id,p.frame.url,f);for(let g of p.childFrames??[])h(g,!1)},"walk");h(u,e.isMain)},"initSession");async onMessage(e,t,s,o,i){let r;try{r=JSON.parse(i)}catch{return}let a=this.state(t),c=typeof r.url=="string"?r.url:"",d={page:t,frameId:o.frameId,url:c},u=typeof r.cmp=="string"?r.cmp:"";switch(r.type){case"init":{a.frames.add(o.frameId),o.mainFrame&&(a.topInitAt??=Date.now());let h={autoconsent:[],compact:oh(Fr,{url:c,mainFrame:o.mainFrame})};await this.reply(e,s,{type:"initResp",config:this.config,rules:h});return}case"eval":await this.reply(e,s,{type:"evalResp",id:r.id,result:await this.runSnippet(e,t,s,o,r.snippetId)});return;case"cmpDetected":a.cmp??=u,a.detectedAt??=Date.now(),this.emit("cmpDetected",{...d,cmp:u});return;case"popupFound":a.cmp=u,a.popupAt??=Date.now(),this.emit("popupFound",{...d,cmp:u});return;case"optOutResult":a.cmp=u||a.cmp,a.optOut=r.result===!0,a.optOutAt=Date.now(),r.result===!0&&r.scheduleSelfTest===!0&&(a.selfTestTarget={s:e,contextId:s}),this.emit("optOutResult",{...d,cmp:u,result:r.result===!0});return;case"autoconsentDone":{a.cmp=u||a.cmp,a.doneAt=Date.now(),a.cosmetic=r.isCosmetic===!0,this.emit("autoconsentDone",{...d,cmp:u,cosmetic:a.cosmetic,durationMs:Number(r.duration)||0,clicks:Number(r.totalClicks)||0});let h=a.selfTestTarget;a.selfTestTarget=void 0,this.opts.selfTest!==!1&&h&&await this.reply(h.s,h.contextId,{type:"selfTest"});return}case"selfTestResult":a.selfTest=r.result===!0,this.emit("selfTestResult",{...d,cmp:u,result:a.selfTest});return;case"optInResult":this.emit("error",{...d,error:"unexpected optInResult",details:r});return;case"autoconsentError":this.emit("error",{...d,error:"autoconsent",details:r.details});return;case"pfRefusedClick":a.refused++,this.emit("error",{...d,error:`refused to click an accept button: "${String(r.text)}"`});return;case"report":{let h=r.state??{};if(!o.mainFrame||r.mainFrame!==!0)return;a.topLifecycle=h.lifecycle,a.topAttempts=Math.max(a.topAttempts,Number(h.findCmpAttempts)||0),h.heuristicPatterns?.length&&a.patternsAt===void 0&&(a.patternsAt=Date.now(),a.roundAtPatterns=a.topAttempts);return}default:return}}reply(e,t,s){return e.send("Runtime.evaluate",{contextId:t,expression:`autoconsentReceiveMessage(${JSON.stringify(s)})`,returnByValue:!0}).catch(()=>{})}async runSnippet(e,t,s,o,i){let r=typeof i=="string"?Dr[i]:void 0;if(!r||ih.has(i))return this.emit("error",{page:t,frameId:o.frameId,error:`refused eval snippet ${String(i)}`}),!1;let a=await e.send("Runtime.evaluate",{contextId:s,expression:"document",returnByValue:!1});if(!a.result.objectId)return!1;try{let{node:c}=await e.send("DOM.describeNode",{objectId:a.result.objectId}),{object:d}=await e.send("DOM.resolveNode",{backendNodeId:c.backendNodeId});if(!d.objectId)return!1;try{return(await e.send("Runtime.callFunctionOn",{objectId:d.objectId,functionDeclaration:`async function () { try { return !!(await (${r.toString()}).call(window)); } catch (e) { return false; } }`,returnByValue:!0,awaitPromise:!0})).result.value===!0}finally{e.send("Runtime.releaseObject",{objectId:d.objectId}).catch(()=>{})}}catch{return!1}finally{e.send("Runtime.releaseObject",{objectId:a.result.objectId}).catch(()=>{})}}state(e){let t=this.pages.get(e);return t||(t={navAt:Date.now(),url:e.url,cmp:null,refused:0,frames:new Set,topAttempts:0},this.pages.set(e,t)),t}reset(e,t){this.pages.set(e,{navAt:Date.now(),url:t,cmp:null,refused:0,frames:new Set,topAttempts:0})}emit(e,t){e==="error"&&this.emitter.listenerCount("error")===0||this.emitter.emit(e,t)}};var yh=["cmpDetected","popupFound","optOutResult","autoconsentDone","selfTestResult","error"],bh=["blocked","error"];async function An(n,e={}){let t=e.consent===!1?null:new ds(typeof e.consent=="object"?e.consent:{}),s=e.adblock===!1?null:await ls.create(typeof e.adblock=="object"?e.adblock:{}),o=[];if(e.onEvent){let r=e.onEvent;if(t)for(let a of yh)o.push(t.on(a,(c=>r({source:"consent",type:a,data:c}))));if(s)for(let a of bh)o.push(s.on(a,(c=>r({source:"adblock",type:a,data:c}))))}let i=l(async r=>{await Promise.all([t?.initSession(r),s?.initSession(r)])},"init");return o.push(n.addSessionInitializer(i)),{consent:t,adblock:s,detach(){for(let r of o)r();t?.dispose(),s?.dispose()}}}l(An,"attachInterrupts");var kh="pilotfish's open MCP makes no model calls: the MCP client's own model reads the page and decides the next step",vh=l(()=>{let n=l(async()=>{throw new Error(kh)},"refuse");return{messages:{create:n},beta:{messages:{create:n}}}},"noModelClient"),Mn=class{static{l(this,"ConfirmThrough")}inner;canAsk;constructor(e,t){this.inner=e,this.canAsk=t}async check(e){let t=await this.inner.check(e);return t.kind!=="confirm"||this.canAsk()?t:{kind:"deny",reason:`${t.reason}. This needs a person's confirmation, and this MCP client cannot ask for one (no elicitation support)`}}},Qe=class{static{l(this,"BrowserSession")}config;opts;browser=null;launching=null;interrupts=null;tabs=null;agent=null;queue=Promise.resolve();policy;asker;constructor(e,t={}){this.config=e,this.opts=t,this.policy=new Ne({allowedHosts:e.allowedHosts,allowPrivateNetwork:e.allowPrivateNetwork})}get launched(){return!!this.browser&&!this.browser.closed}async page(){return await this.ensure(),this.tabs.current}get tabTable(){return this.tabs}async ensure(){return this.browser&&!this.browser.closed?this.browser:(this.launching??=this.start().finally(()=>{this.launching=null}),this.launching)}async start(){let e=await Ts({...this.opts.launch,headless:this.config.headless});this.interrupts=await An(e,{consent:!0,adblock:!0}).catch(()=>null);let t=e.allPages()[0]??await e.newPage();return this.tabs=new De(t),this.browser=e,e.on("disconnected",()=>{this.browser===e&&this.reset()}),e}reset(){this.agent?.dispose(),this.agent=null,this.tabs?.dispose(),this.tabs=null,this.interrupts?.detach(),this.interrupts=null,this.browser=null}executor(){return this.agent??=new bt(this.tabs.current,{tabs:this.tabs,client:vh(),secrets:this.config.secrets,policy:new Mn(this.policy,()=>!!this.asker),consent:this.interrupts?.consent??void 0,allowScreenshots:this.config.allowScreenshots,askUser:l(e=>this.asker?.(e)??Promise.resolve(null),"askUser"),fastSettle:!0,enableQuery:!0,compactSnapshots:!0,autoDismiss:!0,awaitLoading:!0,actionSnapshotBand:0,snapshotMoreHint:"browser_scroll for the next screen, browser_get_text for the page's text, or browser_snapshot (whole_page) for every element"}),this.agent}async act(e,t,s={}){let o=this.queue.then(async()=>(await this.ensure(),this.executor().act(e,t,"",s)));return this.queue=o.catch(()=>{}),o}async obstacle(e={}){if(!this.launched)return null;let t=this.queue.then(()=>this.executor().obstacle(e));return this.queue=t.catch(()=>{}),t.catch(()=>null)}async close(){let e=this.browser??(this.launching?await this.launching.catch(()=>null):null);return e?(this.reset(),await e.close().catch(()=>{}),!0):!1}};import{McpServer as xh}from"@modelcontextprotocol/sdk/server/mcp.js";import{ListToolsRequestSchema as _h}from"@modelcontextprotocol/sdk/types.js";import{z}from"zod";var hs="0.1.40";var ps=Oe.click.shape.ref.describe('From the latest snapshot, e.g. "e12" or "f1e3"'),Hr=z.enum(["down","up","left","right"]),Sh={click:["ref"],type:["ref","text","submit"],select:["ref","values"],press:["key"],scroll:["direction"],wait:["seconds"]},$h={click:1,type:2,select:2,press:1,scroll:1,wait:1},Th=z.object({action:z.enum(["click","type","select","press","scroll","wait"]).describe("click, select, type take ref; type: text (submit: Enter after); select: values; press: key; scroll: direction; wait: seconds"),ref:ps.optional(),text:z.string().max(2e4).optional(),submit:z.boolean().optional(),values:z.array(z.string()).min(1).max(50).optional(),key:z.string().min(1).max(40).optional(),direction:Hr.optional(),seconds:z.number().min(.5).max(10).optional()}).strict().superRefine((n,e)=>{let t=Sh[n.action];for(let s of t.slice(0,$h[n.action]))n[s]===void 0&&e.addIssue({code:"custom",path:[s],message:`${n.action} needs ${s}`});for(let s of Object.keys(n))s!=="action"&&!t.includes(s)&&e.addIssue({code:"custom",path:[s],message:`${s} is not a field of ${n.action} (it takes ${t.join(", ")})`})}),ae={browser_navigate:z.object({url:z.url({protocol:/^https?$/}).describe("Absolute http(s) URL"),snapshot:z.boolean().optional().describe("Default true. false: no page snapshot, only what happened (title, counts). Only when this same reply also reads the page with browser_query and you will not act on it; keep it for a page you have not seen or whose tabs, sorts, filters or forms you may use.")}).strict(),browser_snapshot:z.object({whole_page:z.boolean().optional()}).strict(),browser_click:z.object({ref:ps}).strict(),browser_type:z.object({ref:ps,text:z.string().max(2e4),submit:z.boolean().optional().describe("Press Enter afterwards")}).strict(),browser_select:z.object({ref:ps,values:z.array(z.string()).min(1).max(50)}).strict(),browser_press:z.object({key:z.string().min(1).max(40).describe('e.g. "Enter", "Escape", "Tab", "ArrowDown", "Control+a"')}).strict(),browser_scroll:z.object({direction:Hr}).strict(),browser_screenshot:z.object({}).strict(),browser_get_text:z.object({max_chars:z.number().int().min(500).max(6e4).optional().describe("Default 20000. Ask for less when the start of the page is enough."),selector:z.string().min(1).max(300).optional().describe(`CSS selector: only the first match's text, e.g. "main" or "#results"`)}).strict(),browser_query:z.object({expression:z.string().min(1).max(4e3).describe("e.g. [...document.querySelectorAll('.result')].slice(0,10).map(e => e.innerText)")}).strict(),browser_find:z.object({query:z.string().min(1).max(300).describe('Words naming the element(s), e.g. "Sort by" or "price max input, Go button"')}).strict(),browser_wait:z.object({seconds:z.number().min(.5).max(10),until:z.string().max(120).optional().describe("Return once the page shows this text"),gone:z.string().max(120).optional().describe("Return once this text is gone")}).strict(),browser_resume:z.object({timeout_s:z.number().int().min(5).max(900).optional().describe("Default 300")}).strict(),browser_actions:z.object({actions:z.array(Th).min(1).max(10)}).strict(),browser_tabs:z.object({switch_to:z.string().min(1).max(10).optional().describe('Tab id to work in from now on, e.g. "t2"')}).strict(),browser_close:z.object({}).strict()};function Ce(n,e=!1){return{content:[{type:"text",text:n}],...e?{isError:!0}:{}}}l(Ce,"text");function Eh(n){let e=Object.keys(n.secrets),t=[e.length?`Secrets are typed as placeholders and never shown: ${e.map(s=>`{{${s}}}`).join(", ")}.`:"",n.allowedHosts.length?`Navigation is limited to: ${n.allowedHosts.join(", ")}.`:""].filter(Boolean);return t.length?t.join(`
|
|
454
|
+
${us(Nr(Lr,"autoconsent.playwright.js"),"utf8")}`,lh=3,dh=2500,uh=6500,hh=6e3,ph=3e3,fh=1500,mh=3e3,gh=4e3;function wh(n,e){if(n.doneAt)return"opted_out";if(n.optOut===!1)return"failed";if(n.optOut===!0)return e-n.optOutAt>ph?"opted_out":"pending";if(n.popupAt)return"pending";if(n.detectedAt)return e-n.detectedAt<uh?"pending":"no_cmp";let t=n.topLifecycle!=="nothingDetected",s=l((o,i)=>e-o>=dh&&i!==void 0&&n.topAttempts>=i+lh,"quiet");return n.cmpRequestAt&&e-n.cmpRequestAt<hh&&t&&!s(n.cmpRequestAt,n.roundAtCmpRequest)||!n.topInitAt&&/^https?:/.test(n.url)&&e-n.navAt<fh||n.topInitAt&&n.topAttempts<2&&e-n.topInitAt<mh||n.patternsAt&&e-n.patternsAt<gh&&t&&!s(n.patternsAt,n.roundAtPatterns)?"pending":"no_cmp"}l(wh,"outcomeOf");var ds=class{static{l(this,"ConsentEngine")}opts;emitter=new th;pages=new WeakMap;disposers=new Set;armed=new WeakSet;retried=new WeakSet;retryTimers=new Set;disposed=!1;config;constructor(e={}){if(this.opts=e,this.config=rh(e),this.config.autoAction!=="optOut"||!["off","reject"].includes(this.config.heuristicMode))throw new Error("ConsentEngine only ever opts out")}on(e,t){return this.emitter.on(e,t),()=>this.emitter.off(e,t)}consentStatus(e){let t=this.state(e),s=Date.now(),o=wh(t,s),i=o==="opted_out"?t.doneAt??t.optOutAt:s;return{cmp:t.cmp,outcome:o,ms:Math.max(0,i-t.navAt),url:t.url,...t.cosmetic!==void 0?{cosmetic:t.cosmetic}:{},...t.selfTest!==void 0?{selfTest:t.selfTest}:{},refusedClicks:t.refused,frames:t.frames.size}}async waitForConsent(e,t=1e4){let s=Date.now()+t;for(;;){let o=this.consentStatus(e);if(o.outcome!=="pending"||Date.now()>=s||e.closed)return o;await new Promise(i=>setTimeout(i,Math.min(100,Math.max(1,s-Date.now()))))}}dispose(){this.disposed=!0;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear();for(let e of this.disposers)e();this.disposers.clear()}initSession=l(async e=>{let t=e.session,s=e.page;if(!e.isMain&&xe(e.url)||this.armed.has(t))return;this.armed.add(t);let o=new Map,i=[()=>this.armed.delete(t)],r;try{[,r]=await Promise.all([t.send("Runtime.addBinding",{name:Xe,executionContextName:In},{timeoutMs:5e3}),t.send("Page.addScriptToEvaluateOnNewDocument",{source:ch,worldName:In,runImmediately:!0},{timeoutMs:5e3})])}catch(p){if(this.armed.delete(t),e.isMain&&!this.retried.has(t)&&!this.disposed){this.retried.add(t);let f=setTimeout(()=>{this.retryTimers.delete(f),this.disposed||this.initSession(e).catch(()=>{})},2e3);f.unref?.(),this.retryTimers.add(f)}throw p}let a=l(()=>{for(let p of i)p();t.send("Page.removeScriptToEvaluateOnNewDocument",{identifier:r.identifier}).catch(()=>{}),t.send("Runtime.removeBinding",{name:Xe}).catch(()=>{})},"dispose");this.disposers.add(a),i.push(()=>this.disposers.delete(a));let c=l(async(p,f,g)=>{if(!/^https?:/.test(f)||!g&&xe(f))return;let{executionContextId:w}=await t.send("Page.createIsolatedWorld",{frameId:p,worldName:In,grantUniveralAccess:!1},{timeoutMs:5e3});o.set(w,{frameId:p,mainFrame:g}),await t.send("Runtime.addBinding",{name:Xe,executionContextId:w},{timeoutMs:5e3}),await t.send("Runtime.evaluate",{contextId:w,expression:"globalThis.__pfAcFlush && __pfAcFlush()",returnByValue:!0},{timeoutMs:5e3})},"arm"),d=l((p,f,g)=>{c(p,f,g).catch(w=>{/not found|Cannot find|No frame|detached|closed|destroyed|navigated/i.test(String(w))||this.emit("error",{page:s,frameId:p,url:f,error:`arm: ${String(w)}`})})},"armSafe");i.push(t.on("Page.frameNavigated",p=>{let f=e.isMain&&!p.frame.parentId;f&&this.reset(s,p.frame.url),d(p.frame.id,p.frame.url,f)}),t.on("Runtime.bindingCalled",p=>{if(p.name!==Xe)return;let f=o.get(p.executionContextId);f&&this.onMessage(t,s,p.executionContextId,f,p.payload).catch(()=>{})}),t.on("Network.requestWillBeSent",p=>{if(!yr(p.request.url))return;let f=this.state(s);f.cmpRequestAt===void 0&&(f.cmpRequestAt=Date.now(),f.roundAtCmpRequest=f.topAttempts)}));let{frameTree:u}=await t.send("Page.getFrameTree"),h=l((p,f)=>{d(p.frame.id,p.frame.url,f);for(let g of p.childFrames??[])h(g,!1)},"walk");h(u,e.isMain)},"initSession");async onMessage(e,t,s,o,i){let r;try{r=JSON.parse(i)}catch{return}let a=this.state(t),c=typeof r.url=="string"?r.url:"",d={page:t,frameId:o.frameId,url:c},u=typeof r.cmp=="string"?r.cmp:"";switch(r.type){case"init":{a.frames.add(o.frameId),o.mainFrame&&(a.topInitAt??=Date.now());let h={autoconsent:[],compact:oh(Fr,{url:c,mainFrame:o.mainFrame})};await this.reply(e,s,{type:"initResp",config:this.config,rules:h});return}case"eval":await this.reply(e,s,{type:"evalResp",id:r.id,result:await this.runSnippet(e,t,s,o,r.snippetId)});return;case"cmpDetected":a.cmp??=u,a.detectedAt??=Date.now(),this.emit("cmpDetected",{...d,cmp:u});return;case"popupFound":a.cmp=u,a.popupAt??=Date.now(),this.emit("popupFound",{...d,cmp:u});return;case"optOutResult":a.cmp=u||a.cmp,a.optOut=r.result===!0,a.optOutAt=Date.now(),r.result===!0&&r.scheduleSelfTest===!0&&(a.selfTestTarget={s:e,contextId:s}),this.emit("optOutResult",{...d,cmp:u,result:r.result===!0});return;case"autoconsentDone":{a.cmp=u||a.cmp,a.doneAt=Date.now(),a.cosmetic=r.isCosmetic===!0,this.emit("autoconsentDone",{...d,cmp:u,cosmetic:a.cosmetic,durationMs:Number(r.duration)||0,clicks:Number(r.totalClicks)||0});let h=a.selfTestTarget;a.selfTestTarget=void 0,this.opts.selfTest!==!1&&h&&await this.reply(h.s,h.contextId,{type:"selfTest"});return}case"selfTestResult":a.selfTest=r.result===!0,this.emit("selfTestResult",{...d,cmp:u,result:a.selfTest});return;case"optInResult":this.emit("error",{...d,error:"unexpected optInResult",details:r});return;case"autoconsentError":this.emit("error",{...d,error:"autoconsent",details:r.details});return;case"pfRefusedClick":a.refused++,this.emit("error",{...d,error:`refused to click an accept button: "${String(r.text)}"`});return;case"report":{let h=r.state??{};if(!o.mainFrame||r.mainFrame!==!0)return;a.topLifecycle=h.lifecycle,a.topAttempts=Math.max(a.topAttempts,Number(h.findCmpAttempts)||0),h.heuristicPatterns?.length&&a.patternsAt===void 0&&(a.patternsAt=Date.now(),a.roundAtPatterns=a.topAttempts);return}default:return}}reply(e,t,s){return e.send("Runtime.evaluate",{contextId:t,expression:`autoconsentReceiveMessage(${JSON.stringify(s)})`,returnByValue:!0}).catch(()=>{})}async runSnippet(e,t,s,o,i){let r=typeof i=="string"?Dr[i]:void 0;if(!r||ih.has(i))return this.emit("error",{page:t,frameId:o.frameId,error:`refused eval snippet ${String(i)}`}),!1;let a=await e.send("Runtime.evaluate",{contextId:s,expression:"document",returnByValue:!1});if(!a.result.objectId)return!1;try{let{node:c}=await e.send("DOM.describeNode",{objectId:a.result.objectId}),{object:d}=await e.send("DOM.resolveNode",{backendNodeId:c.backendNodeId});if(!d.objectId)return!1;try{return(await e.send("Runtime.callFunctionOn",{objectId:d.objectId,functionDeclaration:`async function () { try { return !!(await (${r.toString()}).call(window)); } catch (e) { return false; } }`,returnByValue:!0,awaitPromise:!0})).result.value===!0}finally{e.send("Runtime.releaseObject",{objectId:d.objectId}).catch(()=>{})}}catch{return!1}finally{e.send("Runtime.releaseObject",{objectId:a.result.objectId}).catch(()=>{})}}state(e){let t=this.pages.get(e);return t||(t={navAt:Date.now(),url:e.url,cmp:null,refused:0,frames:new Set,topAttempts:0},this.pages.set(e,t)),t}reset(e,t){this.pages.set(e,{navAt:Date.now(),url:t,cmp:null,refused:0,frames:new Set,topAttempts:0})}emit(e,t){e==="error"&&this.emitter.listenerCount("error")===0||this.emitter.emit(e,t)}};var yh=["cmpDetected","popupFound","optOutResult","autoconsentDone","selfTestResult","error"],bh=["blocked","error"];async function An(n,e={}){let t=e.consent===!1?null:new ds(typeof e.consent=="object"?e.consent:{}),s=e.adblock===!1?null:await ls.create(typeof e.adblock=="object"?e.adblock:{}),o=[];if(e.onEvent){let r=e.onEvent;if(t)for(let a of yh)o.push(t.on(a,(c=>r({source:"consent",type:a,data:c}))));if(s)for(let a of bh)o.push(s.on(a,(c=>r({source:"adblock",type:a,data:c}))))}let i=l(async r=>{await Promise.all([t?.initSession(r),s?.initSession(r)])},"init");return o.push(n.addSessionInitializer(i)),{consent:t,adblock:s,detach(){for(let r of o)r();t?.dispose(),s?.dispose()}}}l(An,"attachInterrupts");var kh="pilotfish's open MCP makes no model calls: the MCP client's own model reads the page and decides the next step",vh=l(()=>{let n=l(async()=>{throw new Error(kh)},"refuse");return{messages:{create:n},beta:{messages:{create:n}}}},"noModelClient"),Mn=class{static{l(this,"ConfirmThrough")}inner;canAsk;constructor(e,t){this.inner=e,this.canAsk=t}async check(e){let t=await this.inner.check(e);return t.kind!=="confirm"||this.canAsk()?t:{kind:"deny",reason:`${t.reason}. This needs a person's confirmation, and this MCP client cannot ask for one (no elicitation support)`}}},Qe=class{static{l(this,"BrowserSession")}config;opts;browser=null;launching=null;interrupts=null;tabs=null;agent=null;queue=Promise.resolve();policy;asker;constructor(e,t={}){this.config=e,this.opts=t,this.policy=new Ne({allowedHosts:e.allowedHosts,allowPrivateNetwork:e.allowPrivateNetwork})}get launched(){return!!this.browser&&!this.browser.closed}async page(){return await this.ensure(),this.tabs.current}get tabTable(){return this.tabs}async ensure(){return this.browser&&!this.browser.closed?this.browser:(this.launching??=this.start().finally(()=>{this.launching=null}),this.launching)}async start(){let e=await Ts({...this.opts.launch,headless:this.config.headless});this.interrupts=await An(e,{consent:!0,adblock:!0}).catch(()=>null);let t=e.allPages()[0]??await e.newPage();return this.tabs=new De(t),this.browser=e,e.on("disconnected",()=>{this.browser===e&&this.reset()}),e}reset(){this.agent?.dispose(),this.agent=null,this.tabs?.dispose(),this.tabs=null,this.interrupts?.detach(),this.interrupts=null,this.browser=null}executor(){return this.agent??=new bt(this.tabs.current,{tabs:this.tabs,client:vh(),secrets:this.config.secrets,policy:new Mn(this.policy,()=>!!this.asker),consent:this.interrupts?.consent??void 0,allowScreenshots:this.config.allowScreenshots,askUser:l(e=>this.asker?.(e)??Promise.resolve(null),"askUser"),fastSettle:!0,enableQuery:!0,compactSnapshots:!0,autoDismiss:!0,awaitLoading:!0,actionSnapshotBand:0,snapshotMoreHint:"browser_scroll for the next screen, browser_get_text for the page's text, or browser_snapshot (whole_page) for every element"}),this.agent}async act(e,t,s={}){let o=this.queue.then(async()=>(await this.ensure(),this.executor().act(e,t,"",s)));return this.queue=o.catch(()=>{}),o}async obstacle(e={}){if(!this.launched)return null;let t=this.queue.then(()=>this.executor().obstacle(e));return this.queue=t.catch(()=>{}),t.catch(()=>null)}async close(){let e=this.browser??(this.launching?await this.launching.catch(()=>null):null);return e?(this.reset(),await e.close().catch(()=>{}),!0):!1}};import{McpServer as xh}from"@modelcontextprotocol/sdk/server/mcp.js";import{ListToolsRequestSchema as _h}from"@modelcontextprotocol/sdk/types.js";import{z}from"zod";var hs="0.1.42";var ps=Oe.click.shape.ref.describe('From the latest snapshot, e.g. "e12" or "f1e3"'),Hr=z.enum(["down","up","left","right"]),Sh={click:["ref"],type:["ref","text","submit"],select:["ref","values"],press:["key"],scroll:["direction"],wait:["seconds"]},$h={click:1,type:2,select:2,press:1,scroll:1,wait:1},Th=z.object({action:z.enum(["click","type","select","press","scroll","wait"]).describe("click, select, type take ref; type: text (submit: Enter after); select: values; press: key; scroll: direction; wait: seconds"),ref:ps.optional(),text:z.string().max(2e4).optional(),submit:z.boolean().optional(),values:z.array(z.string()).min(1).max(50).optional(),key:z.string().min(1).max(40).optional(),direction:Hr.optional(),seconds:z.number().min(.5).max(10).optional()}).strict().superRefine((n,e)=>{let t=Sh[n.action];for(let s of t.slice(0,$h[n.action]))n[s]===void 0&&e.addIssue({code:"custom",path:[s],message:`${n.action} needs ${s}`});for(let s of Object.keys(n))s!=="action"&&!t.includes(s)&&e.addIssue({code:"custom",path:[s],message:`${s} is not a field of ${n.action} (it takes ${t.join(", ")})`})}),ae={browser_navigate:z.object({url:z.url({protocol:/^https?$/}).describe("Absolute http(s) URL"),snapshot:z.boolean().optional().describe("Default true. false: no page snapshot, only what happened (title, counts). Only when this same reply also reads the page with browser_query and you will not act on it; keep it for a page you have not seen or whose tabs, sorts, filters or forms you may use.")}).strict(),browser_snapshot:z.object({whole_page:z.boolean().optional()}).strict(),browser_click:z.object({ref:ps}).strict(),browser_type:z.object({ref:ps,text:z.string().max(2e4),submit:z.boolean().optional().describe("Press Enter afterwards")}).strict(),browser_select:z.object({ref:ps,values:z.array(z.string()).min(1).max(50)}).strict(),browser_press:z.object({key:z.string().min(1).max(40).describe('e.g. "Enter", "Escape", "Tab", "ArrowDown", "Control+a"')}).strict(),browser_scroll:z.object({direction:Hr}).strict(),browser_screenshot:z.object({}).strict(),browser_get_text:z.object({max_chars:z.number().int().min(500).max(6e4).optional().describe("Default 20000. Ask for less when the start of the page is enough."),selector:z.string().min(1).max(300).optional().describe(`CSS selector: only the first match's text, e.g. "main" or "#results"`)}).strict(),browser_query:z.object({expression:z.string().min(1).max(4e3).describe("e.g. [...document.querySelectorAll('.result')].slice(0,10).map(e => e.innerText)")}).strict(),browser_find:z.object({query:z.string().min(1).max(300).describe('Words naming the element(s), e.g. "Sort by" or "price max input, Go button"')}).strict(),browser_wait:z.object({seconds:z.number().min(.5).max(10),until:z.string().max(120).optional().describe("Return once the page shows this text"),gone:z.string().max(120).optional().describe("Return once this text is gone")}).strict(),browser_resume:z.object({timeout_s:z.number().int().min(5).max(900).optional().describe("Default 300")}).strict(),browser_actions:z.object({actions:z.array(Th).min(1).max(10)}).strict(),browser_tabs:z.object({switch_to:z.string().min(1).max(10).optional().describe('Tab id to work in from now on, e.g. "t2"')}).strict(),browser_close:z.object({}).strict()};function Ce(n,e=!1){return{content:[{type:"text",text:n}],...e?{isError:!0}:{}}}l(Ce,"text");function Eh(n){let e=Object.keys(n.secrets),t=[e.length?`Secrets are typed as placeholders and never shown: ${e.map(s=>`{{${s}}}`).join(", ")}.`:"",n.allowedHosts.length?`Navigation is limited to: ${n.allowedHosts.join(", ")}.`:""].filter(Boolean);return t.length?t.join(`
|
|
455
455
|
`):void 0}l(Eh,"serverInstructions");function Rn(n={}){let e=n.config??n.session?.config??_t(),t=!n.session,s=n.session??new Qe(e,n),o=new xh({name:"pilotfish",version:n.version??hs},{capabilities:{logging:{}},instructions:Eh(e)}),i=Object.keys(e.secrets),r=i.length?` Secrets: ${i.map(_=>`{{${_}}}`).join(", ")}.`:"",a=l(()=>!!o.server.getClientCapabilities()?.elicitation?.form,"canElicit"),c=l(_=>a()?async E=>{let b=await o.server.elicitInput({message:E,requestedSchema:{type:"object",properties:{answer:{type:"string",title:"Answer",description:'Reply "yes" to allow an action'}},required:["answer"]}},{relatedRequestId:_.requestId,timeout:e.interventionTimeoutMs}).catch(()=>null);return b?.action==="accept"&&typeof b.content?.answer=="string"?b.content.answer:null}:void 0,"askerFor"),d=l(_=>_.replace(/in the live view/g,"in the pilotfish browser window").replace(/Please send the code, or type it/,"Please type the code"),"forWindow"),u=l(_=>_.needs==="solve_in_live_view"||_.needs==="login_in_live_view"||_.needs==="code"||_.needs==="credentials","byHand"),h=l((_,E="")=>[`NEEDS A PERSON (${_.category}${_.vendor?`, ${_.vendor}`:""}): ${d(_.message)}`,E,u(_)&&e.headless?"This browser is headless, so it cannot be done by hand here: tell the user, and that the pilotfish server needs PILOTFISH_HEADLESS=0 (a visible window) for steps like this one.":`Tell the user now, in your reply: what the page needs, and that the pilotfish browser window is open on it (${_.url}). Ask them to do it there and to tell you when it is done. Then call browser_resume: it waits for the page to move on and returns it.`,"Do not try to get past it yourself: pilotfish does not type passwords or codes it was not given, and does not solve CAPTCHAs."].filter(Boolean).join(`
|
|
456
456
|
`),"needsPerson"),p=l(async()=>{let _=await s.act("read_page",{}).catch(()=>null);return _?_.text||_.summary:""},"pageNow"),f=l(async(_,E=1e3)=>{let b=Date.now()+_,M=await s.obstacle({fresh:!0});for(;M&&Date.now()<b;)await new Promise(k=>setTimeout(k,E)),M=await s.obstacle({fresh:!0});return M},"untilClear"),g=l((_,E)=>({..._,content:[..._.content,{type:"text",text:E}]}),"withNote"),w=l(async(_,E)=>{let b=await s.obstacle();if(!b)return E;if(b.autoResolvable&&!b.neverAutomate&&(b=await f(12e3),!b))return g(E,`A browser check was showing and cleared by itself. The page now:
|
|
457
457
|
${await p()}`);if(b.neverAutomate)return g(E,`STOP: ${b.host} shows a bot check, and this site is never automated past one (ticket sellers: the US BOTS Act; UIDAI: the Aadhaar Act). Do not continue on it; tell the user.`);if(b.category==="hard_block"||b.needs==="none_possible")return g(E,`BLOCKED: ${d(b.message)} A person cannot fix this from the browser window: try another way (another page or site), or tell the user.`);if(a()&&!(u(b)&&e.headless)){let M=await o.server.elicitInput({message:`${d(b.message)} (${b.url})`,requestedSchema:{type:"object",properties:{done:{type:"boolean",title:"I have done it in the pilotfish browser window"}},required:["done"]}},{relatedRequestId:_.requestId,timeout:e.interventionTimeoutMs}).catch(()=>null);if(M?.action==="accept"&&M.content?.done!==!1){let k=await f(15e3);return k?g(E,h(k,"The person said it is done, but the page still shows it.")):g(E,`The person handled it. The page now:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gaiventures/pilotfish-mcp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.42",
|
|
4
4
|
"description": "Give any MCP agent a real Chrome on your own computer. Free, no account, no API key. mcprush.com-ba6a69f5121bd8a0089bb26a",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|