eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1 lines • 56.2 kB
JavaScript
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{A as n,C as r,Q as i,T as a,_ as o,b as s,c,g as l,k as u,l as d,m as f,s as p,u as m,v as h,x as g,y as _}from"../../_chunks/workflow/schemas-4CmFgxN_.js";import{A as v,P as y,Q as b,St as x,U as S,V as C,ct as ee,d as w,gt as te,j as ne,k as re,lt as ie,pt as ae,r as oe,s as se,st as ce,yt as le}from"../../_chunks/workflow/dist-C3919PVU.js";const ue={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var de;de||={};let T;T=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function fe(e){return(await T).getRandomValues(new Uint8Array(e))}async function pe(e){let t=``;for(;t.length<e;){let n=await fe(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function me(e){return await pe(e)}async function he(e){let t=await(await T).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function ge(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await me(e);return{code_verifier:t,code_challenge:await he(t)}}var E=`2026-07-28`,D=`2025-11-25`,_e=[E,D,`2025-06-18`,`2025-03-26`,`2024-11-05`],ve=g(r(a(),n())),ye=o({name:a(),version:a(),title:g(a())}),O=o({_meta:g(s({}).loose())}),k=O.extend({resultType:g(a())}),be=s({method:a(),params:g(O)}),xe=s({applyDefaults:g(m())}).loose(),Se=o({experimental:g(s({}).loose()),logging:g(s({}).loose()),completions:g(s({}).loose()),prompts:g(o({listChanged:g(m())})),resources:g(o({subscribe:g(m()),listChanged:g(m())})),tools:g(o({listChanged:g(m())})),elicitation:g(xe)});s({elicitation:g(xe)}).loose();var Ce=k.extend({supportedVersions:c(a()),capabilities:Se,instructions:g(a()),ttlMs:g(_()),cacheScope:g(u([l(`public`),l(`private`)]))}),we=k.extend({protocolVersion:a(),capabilities:Se,serverInfo:ye,instructions:g(a())}),A=k.extend({nextCursor:g(a())}),Te=s({name:a(),title:g(a()),description:g(a()),inputSchema:o({type:g(n()),properties:g(s({}).loose())}),outputSchema:g(s({}).loose()),annotations:g(s({title:g(a()),readOnlyHint:g(m()),destructiveHint:g(m()),idempotentHint:g(m()),openWorldHint:g(m())}).loose()),_meta:ve}).loose(),Ee=A.extend({tools:c(Te)}),De=s({type:l(`text`),text:a()}).loose(),Oe=s({type:l(`image`),data:d(),mimeType:a()}).loose(),ke=s({uri:a(),name:a(),title:g(a()),description:g(a()),mimeType:g(a()),size:g(_())}).loose(),Ae=A.extend({resources:c(ke)}),je=s({uri:a(),name:g(a()),title:g(a()),mimeType:g(a())}).loose(),Me=je.extend({text:a()}),Ne=je.extend({blob:d()}),Pe=s({type:l(`resource`),resource:u([Me,Ne])}).loose(),Fe=s({type:l(`resource_link`),uri:a(),name:a(),description:g(a()),mimeType:g(a())}).loose(),Ie=s({type:a()}).loose().refine(e=>![`text`,`image`,`resource`,`resource_link`].includes(e.type),{message:`Known content types must match their schema`}),Le=k.extend({content:c(u([De,Oe,Pe,Fe,Ie])),structuredContent:g(n()),isError:m().default(!1).optional()}),Re=k.extend({content:h().optional(),structuredContent:f(),isError:m().default(!1).optional()}).transform(e=>({...e,content:[{type:`text`,text:JSON.stringify(e.structuredContent)}]})).pipe(Le),ze=Le.or(Re).or(k.extend({toolResult:n().nonoptional()})),Be=s({uriTemplate:a(),name:a(),title:g(a()),description:g(a()),mimeType:g(a())}).loose(),Ve=k.extend({resourceTemplates:c(Be)}),He=k.extend({contents:c(u([Me,Ne]))}),Ue=s({type:l(`ref/prompt`),name:a()}).loose(),We=s({type:l(`ref/resource`),uri:a()}).loose(),Ge=s({name:a(),value:a()}).loose();O.extend({ref:u([Ue,We]),argument:Ge,context:g(s({arguments:r(a(),a())}).loose())});var Ke=k.extend({completion:s({values:c(a()).max(100),total:g(_().int()),hasMore:g(m())}).loose()}),qe=s({name:a(),description:g(a()),required:g(m())}).loose(),Je=s({name:a(),title:g(a()),description:g(a()),arguments:g(c(qe))}).loose(),Ye=A.extend({prompts:c(Je)}),Xe=s({role:u([l(`user`),l(`assistant`)]),content:u([De,Oe,Pe,Fe])}).loose(),Ze=k.extend({description:g(a()),messages:c(Xe)}),Qe=O.extend({message:a(),requestedSchema:n()}),j=be.extend({method:l(`elicitation/create`),params:Qe}),$e=k.extend({action:u([l(`accept`),l(`decline`),l(`cancel`)]),content:g(r(a(),n()))}),M=`2.0`,et=s({jsonrpc:l(M),id:u([a(),_().int()])}).merge(be).strict(),tt=s({jsonrpc:l(M),id:u([a(),_().int()]),result:k}).strict(),nt=s({jsonrpc:l(M),id:g(u([a(),_().int()])),error:s({code:_().int(),message:a(),data:g(n())})}).strict(),rt=s({jsonrpc:l(M)}).merge(s({method:a(),params:g(O)})).strict(),it=u([et,rt,tt,nt]);function N(e){return it.parse(e)}async function P(e){return N(await b({text:e}))}var at=`vercel.ai.error.AI_MCPClientError`,ot=Symbol.for(at),st,ct,F=class extends (ct=e,st=ot,ct){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[st]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,at)}},lt=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,I=a().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ue.custom,message:`URL must be parseable`,fatal:!0}),i}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ut=s({access_token:a(),id_token:a().optional(),token_type:a(),expires_in:_().optional(),scope:a().optional(),refresh_token:a().optional(),issuer:I.optional(),authorization_server:I.optional(),token_endpoint:I.optional()}).strip(),dt=o({resource:a().url(),authorization_servers:c(I).optional(),jwks_uri:a().url().optional(),scopes_supported:c(a()).optional(),bearer_methods_supported:c(a()).optional(),resource_signing_alg_values_supported:c(a()).optional(),resource_name:a().optional(),resource_documentation:a().optional(),resource_policy_uri:a().url().optional(),resource_tos_uri:a().url().optional(),tls_client_certificate_bound_access_tokens:m().optional(),authorization_details_types_supported:c(a()).optional(),dpop_signing_alg_values_supported:c(a()).optional(),dpop_bound_access_tokens_required:m().optional()}),ft=o({issuer:a(),authorization_endpoint:I,token_endpoint:I,registration_endpoint:I.optional(),authorization_response_iss_parameter_supported:m().optional(),client_id_metadata_document_supported:m().optional(),scopes_supported:c(a()).optional(),response_types_supported:c(a()),grant_types_supported:c(a()).optional(),code_challenge_methods_supported:c(a()).optional(),token_endpoint_auth_methods_supported:c(a()).optional(),token_endpoint_auth_signing_alg_values_supported:c(a()).optional()}),pt=o({issuer:a(),authorization_endpoint:I,token_endpoint:I,userinfo_endpoint:I.optional(),jwks_uri:I,registration_endpoint:I.optional(),authorization_response_iss_parameter_supported:m().optional(),client_id_metadata_document_supported:m().optional(),scopes_supported:c(a()).optional(),response_types_supported:c(a()),grant_types_supported:c(a()).optional(),subject_types_supported:c(a()),id_token_signing_alg_values_supported:c(a()),claims_supported:c(a()).optional(),token_endpoint_auth_methods_supported:c(a()).optional()}).merge(ft.pick({code_challenge_methods_supported:!0})),mt=s({client_id:a(),client_secret:a().optional(),client_id_issued_at:_().optional(),client_secret_expires_at:_().optional(),issuer:I.optional(),authorization_server:I.optional(),token_endpoint:I.optional()}).strip(),ht=s({redirect_uris:c(I),application_type:u([l(`native`),l(`web`)]).optional(),token_endpoint_auth_method:a().optional(),grant_types:c(a()).optional(),response_types:c(a()).optional(),client_name:a().optional(),client_uri:I.optional(),logo_uri:I.optional(),scope:a().optional(),contacts:c(a()).optional(),tos_uri:I.optional(),policy_uri:a().optional(),jwks_uri:I.optional(),jwks:p().optional(),software_id:a().optional(),software_version:a().optional(),software_statement:a().optional()}).strip(),gt=s({error:a(),error_description:a().optional(),error_uri:a().optional()}),_t=ht.merge(mt),vt=`vercel.ai.error.AI_MCPClientOAuthError`,yt=Symbol.for(vt),bt,xt,L=class extends (xt=e,bt=yt,xt){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[bt]=!0}static isInstance(t){return e.hasMarker(t,vt)}},R=class extends L{};R.errorCode=`server_error`;var z=class extends L{};z.errorCode=`invalid_client`;var B=class extends L{};B.errorCode=`invalid_grant`;var V=class extends L{};V.errorCode=`unauthorized_client`;var St={[R.errorCode]:R,[z.errorCode]:z,[B.errorCode]:B,[V.errorCode]:V};function Ct(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function H(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function wt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var U=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function W(e){return new URL(e).href}function G(e){let t=e.toLowerCase().replace(/\.+$/,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`127.0.0.1`||t===`[::1]`||t===`::1`}function K(e,{allowLoopback:t=!1}={}){if(!t||e.protocol!==`http:`&&e.protocol!==`https:`||!G(e.hostname))try{te(e.href)}catch(t){throw new L({message:`OAuth endpoint URL is not allowed: ${e.href}`,cause:t})}}function q(e){let t=new URL(e);return G(t.hostname)?t.origin:void 0}function Tt({callbackIssuer:e,expectedIssuer:t}){if(e!=null&&e!==t)throw new L({message:`OAuth authorization response issuer ${e} does not match expected issuer ${t}`})}function Et(e,t){return{issuer:t?.issuer??String(e),authorizationServerUrl:W(e),tokenEndpoint:W(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function Dt(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function Ot(e,t){return{...e,issuer:t.issuer,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function kt(e){if(e?.authorization_server&&e.token_endpoint)return{issuer:e.issuer,authorizationServerUrl:W(e.authorization_server),tokenEndpoint:W(e.token_endpoint)}}async function J({provider:e,clientInformation:t,tokens:n}){let r=kt(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{issuer:i.issuer,authorizationServerUrl:W(i.authorizationServerUrl),tokenEndpoint:W(i.tokenEndpoint)}:kt(t)}async function At({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(Ot(t,n)),!0):!1}function jt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new L({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function Y({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.issuer!=null&&t.issuer!=null&&e.issuer!==t.issuer||e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new L({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function X(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=t.match(/(?:^|[,\s])resource_metadata="([^"]*)"/i),a=t.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1],o;try{o=i?new URL(i[1]):void 0}catch{}return{resourceMetadataUrl:o,scope:a}}function Mt({scope:e,resourceMetadata:t,clientMetadata:n}){return e||(t?.scopes_supported)?.join(` `)||n.scope}function Nt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Z(e,t,n=fetch,r){try{return await ne({url:e.href,fetch:async(e,i)=>v({url:e,init:{...i,headers:new Headers(i?.headers).has(`MCP-Protocol-Version`)?t:void 0},fetch:n,trustedOrigin:r,redirect:`manual`}),headers:t,trustedOrigin:r})}catch(i){if(i instanceof TypeError)return t?Z(e,void 0,n,r):void 0;throw i}}async function Pt(e,t,n=fetch,r){return await Z(e,{"MCP-Protocol-Version":t},n,r)}function Ft(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function It(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??E,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Nt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Pt(o,a,n,r?.trustedOrigin);return!r?.metadataUrl&&Ft(s,i.pathname)&&(s=await Pt(new URL(`/.well-known/${t}`,i),a,n,r?.trustedOrigin)),s}async function Lt(e,t,n=fetch){let r=await It(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl,trustedOrigin:new URL(e).origin});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return dt.parse(await r.json())}function Rt(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function zt(e,t){if(!(e.issuer===t||t===new URL(t).origin&&e.issuer===`${t}/`))throw new L({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Bt(e,{fetchFn:t=fetch,protocolVersion:n=E,trustedOrigin:r}={}){let i={"MCP-Protocol-Version":n},a=Rt(e);for(let{url:e,type:n,expectedIssuer:o}of a){let a=await Z(e,i,t,r);if(a){if(!a.ok){if(a.status>=400&&a.status<500)continue;throw Error(`HTTP ${a.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=ft.parse(await a.json());return zt(e,o),e}{let t=pt.parse(await a.json());if(zt(t,o),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Vt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await ge(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,H(o)),{authorizationUrl:l,codeVerifier:d}}function Ht(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Ut(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Wt(i,a,n);return;case`client_secret_post`:Gt(i,a,r);return;case`none`:Kt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Wt(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Gt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Kt(e,t){t.set(`client_id`,e)}async function qt(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=gt.parse(await b({text:n}));return new(St[e]||R)({message:t||``,cause:r})}catch(e){return new R({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Jt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),d=q(e);if(K(u,{allowLoopback:u.origin===d}),t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let f=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),p=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(f,p,e,t):Ut(Ht(n,t?.token_endpoint_auth_methods_supported??[]),n,f,p),o&&p.set(`resource`,H(o));let m=await v({url:u,init:{method:`POST`,headers:f,body:p},fetch:c,trustedOrigin:d});if(!m.ok)throw await qt(m);return ut.parse(await m.json())}async function Yt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=q(e);K(c,{allowLoopback:c.origin===l});let u=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),d=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(u,d,e,t):Ut(Ht(n,t?.token_endpoint_auth_methods_supported??[]),n,u,d),i&&d.set(`resource`,H(i));let f=await v({url:c,init:{method:`POST`,headers:u,body:d},fetch:o,trustedOrigin:l});if(!f.ok)throw await qt(f);return ut.parse({refresh_token:r,...await f.json()})}async function Xt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=q(e);K(i,{allowLoopback:i.origin===a});let o=n.application_type??Zt(n.redirect_uris),s=await v({url:i,init:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,application_type:o})},fetch:r,trustedOrigin:a});if(!s.ok)throw await qt(s);return _t.parse(await s.json())}function Zt(e){return e.every(e=>{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&G(t.hostname)||t.protocol!==`http:`&&t.protocol!==`https:`})?`native`:`web`}async function Q(e,t){try{return await $t(e,t)}catch(n){if(n instanceof z||n instanceof V)return await e.invalidateCredentials?.call(e,`all`),await $t(e,t);if(n instanceof B)return await e.invalidateCredentials?.call(e,`tokens`),await $t(e,t);throw n}}async function Qt(e,t,n){let r=Ct(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!wt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function $t(e,{serverUrl:t,authorizationCode:n,callbackState:r,callbackIssuer:i,scope:a,resourceMetadataUrl:o,fetchFn:s}){let c,l,u,d;jt(t,o);try{c=await Lt(t,{resourceMetadataUrl:o},s),c.authorization_servers&&c.authorization_servers.length>0&&(l=c.authorization_servers[0])}catch{}n!==void 0&&(u=await Promise.resolve(e.clientInformation()),u&&(d=await J({provider:e,clientInformation:u}))),l||=d?.authorizationServerUrl??t;let f=new URL(t),p=new URL(l),m=f.origin,h=p.origin,g=h===m||G(f.hostname)&&G(p.hostname)?h:void 0;g||K(new URL(l));let _=await Qt(t,e,c);await e.validateAuthorizationServerURL?.call(e,t,l);let v=await Bt(l,{fetchFn:s,trustedOrigin:g}),y=Et(l,v),b=e.clientMetadata,x=Mt({scope:a,resourceMetadata:c,clientMetadata:b});if(n===void 0&&(u=await Promise.resolve(e.clientInformation())),u?.issuer!=null){let t=d??await J({provider:e,clientInformation:u});t&&Y({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y})}if(!u){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);u=Ot(await Xt(l,{metadata:v,clientMetadata:{...b,scope:x},fetchFn:s}),y),await e.saveClientInformation(u)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=d??await J({provider:e,clientInformation:u});if(!t)throw new L({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});Tt({callbackIssuer:i,expectedIssuer:t.issuer??v?.issuer??String(l)}),Y({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y});let a=await e.codeVerifier(),o=await Jt(l,{metadata:v,clientInformation:u,authorizationCode:n,codeVerifier:a,redirectUri:e.redirectUrl,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(Dt(o,y)),`AUTHORIZED`}let S=await e.tokens();if(S?.refresh_token){let t=await J({provider:e,clientInformation:u,tokens:S});t?Y({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:y}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Yt(l,{metadata:v,clientInformation:u,refreshToken:S.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(Dt(t,y)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof L)||e instanceof R))throw e}}let C=e.state?await e.state():void 0;C&&e.saveState&&await e.saveState(C);let{authorizationUrl:ee,codeVerifier:w}=await Vt(l,{metadata:v,clientInformation:u,state:C,redirectUrl:e.redirectUrl,scope:x,resource:_});if(!await At({provider:e,clientInformation:u,authorizationServerInformation:y}))throw new L({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(w),await e.redirectToAuthorization(ee),`REDIRECT`}function en(e){return e===void 0||e===`message`}var tn=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??D};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return le(t,`ai-sdk/${lt}`,y())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){let{resourceMetadataUrl:e,scope:r}=X(c);this.resourceMetadataUrl=e;try{if(await Q(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:r,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new U;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new F({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new F({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new F({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(en(s))try{let e=await P(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new F({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e,t){var n;if((n=t?.signal)==null||n.throwIfAborted(),!this.endpoint||!this.connected)throw new F({message:`MCP SSE Transport Error: Not connected`});let r=this.endpoint,i=this.abortController?.signal,a=t?.signal==null?i:i==null?t.signal:AbortSignal.any([i,t.signal]),o=async(n=!1)=>{var i;try{let t={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:a,redirect:this.redirectMode},i=await this.fetchFn(r.href,t);if(i.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=X(i);if(this.resourceMetadataUrl=e,await Q(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,scope:t,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new U;return o(!0)}if(!i.ok){let e=await i.text().catch(()=>null);throw new F({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${i.status}): ${e}`,statusCode:i.status,url:r.href,responseBody:e??void 0})}}catch(e){throw t?.signal?.aborted||(i=this.onerror)==null||i.call(this,e),e}};await o()}},nn=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,rn=/^=\?base64\?.*\?=$/;function an(e){return[...e].every(e=>{let t=e.charCodeAt(0);return t===9||t>=32&&t<=126})&&e.trim()===e&&!rn.test(e)?e:`=?base64?${w(new TextEncoder().encode(e))}?=`}function on(e){if(!C(e))return{success:!1,error:`inputSchema must be a JSON Schema object`};let t=[],n=new Set,r,i=(e,a,o)=>{if(r==null&&C(e)){if(`x-mcp-header`in e){if(!o||a.length===0){r=`x-mcp-header is not on a statically reachable property`;return}let i=e[`x-mcp-header`];if(typeof i!=`string`||!nn.test(i)){r=`x-mcp-header must be a non-empty HTTP token`;return}let s=i.toLowerCase();if(n.has(s)){r=`x-mcp-header value "${i}" is not unique`;return}let c=e.type;if(c!==`boolean`&&c!==`integer`&&c!==`string`){r=`x-mcp-header can only annotate boolean, integer, or string properties`;return}n.add(s),t.push({headerName:i,path:a,valueType:c})}for(let[t,n]of Object.entries(e))if(t!==`x-mcp-header`){if(t===`properties`&&C(n))for(let[e,t]of Object.entries(n))i(t,[...a,e],o);else i(n,a,!1)}}};return i(e,[],!0),r==null?{success:!0,bindings:t}:{success:!1,error:r}}function sn(e,t){let n=e;for(let e of t){if(!C(n))return;n=n[e]}return n}function cn({bindings:e,args:t}){let n={};for(let r of e){let e=sn(t,r.path);if(e!=null){if(r.valueType===`string`&&typeof e!=`string`||r.valueType===`boolean`&&typeof e!=`boolean`||r.valueType===`integer`&&!Number.isSafeInteger(e))throw TypeError(`Tool argument "${r.path.join(`.`)}" does not match its x-mcp-header type`);n[`Mcp-Param-${r.headerName}`]=an(String(e))}}return n}function ln(e){return e===void 0||e===`message`}var un=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.supportsProtocolVersionDiscovery=!0,this.supportsMcpToolParameterHeaders=!0,this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a??D,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){var t;if(this.protocolVersion=e,this.abortController){if(this.isModernProtocol()){(t=this.inboundSseConnection)==null||t.close(),this.inboundSseConnection=void 0;return}this.inboundSseConnection||this.startInboundSse()}}isModernProtocol(){return(this.protocolVersion??E)===E}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??D};if(!this.isModernProtocol()&&t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return le(n,`ai-sdk/${lt}`,y())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){if(this.isModernProtocol())return;let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e,t){return this.authProvider?(this.authPromise||=Q(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,scope:t,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new F({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.protocolVersion!=null&&this.protocolVersion!==E&&this.startInboundSse()}async close(e){var t,n,r,i,a;(t=this.inboundSseConnection)==null||t.close(),(n=this.abortController)==null||n.abort();try{if(!this.isModernProtocol()&&this.sessionId&&this.terminateSessionOnClose&&this.abortController){(r=e?.signal)==null||r.throwIfAborted();let t=await this.commonHeaders({base:{}});(i=e?.signal)==null||i.throwIfAborted(),await this.fetchFn(this.url.href,{method:`DELETE`,headers:t,signal:e?.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(a=this.onclose)==null||a.call(this)}async send(e,t){var n;(n=t?.signal)==null||n.throwIfAborted();let r=this.abortController?.signal,i=t?.signal==null?r:r==null?t.signal:AbortSignal.any([r,t.signal]),a=async(n=!1)=>{var r,o,s,c,l,u,d;try{let d=`method`in e&&e.method===`initialize`,f=d?void 0:this.sessionId,p={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,...this.isModernProtocol()?t?.headers:{},...this.isModernProtocol()&&`method`in e&&`id`in e?this.getStandardRequestHeaders(e):{}},includeSessionId:!d}),body:JSON.stringify(e),signal:i,redirect:this.redirectMode},m=await this.fetchFn(this.url.href,p);if(this.applySessionIdFromResponse(m),m.status===401&&this.authProvider&&!n){let{resourceMetadataUrl:e,scope:t}=X(m);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,t)!==`AUTHORIZED`)throw new U}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return a(!0)}if(m.status===202){!this.isModernProtocol()&&!this.inboundSseConnection&&this.startInboundSse();return}if(!m.ok){let t=await m.text().catch(()=>null);if(`id`in e&&t!=null){let n=await P(t).catch(()=>void 0);if(n!=null&&`error`in n){(o=this.onmessage)==null||o.call(this,n.id==null?{...n,id:e.id}:n);return}}let n=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${m.status}): ${t}`;m.status===404&&(!this.isModernProtocol()&&f?(this.expireSessionId(f),n+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):this.isModernProtocol()||(n+=". This server does not support HTTP transport. Try using `sse` transport instead"));let r=new F({message:n,statusCode:m.status,url:this.url.href,responseBody:t??void 0});throw(s=this.onerror)==null||s.call(this,r),r}if(!(`id`in e))return;let h=m.headers.get(`content-type`)||``;if(h.includes(`application/json`)){let e=await m.json(),t=Array.isArray(e)?e.map(e=>N(e)):[N(e)];for(let e of t)(c=this.onmessage)==null||c.call(this,e);return}if(h.includes(`text/event-stream`)){if(!m.body){let e=new F({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:m.status,url:this.url.href});throw(l=this.onerror)==null||l.call(this,e),e}let e=m.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader();(async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await e.read();if(t)return;let{event:a,data:o}=i;if(ln(a))try{let e=await P(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new F({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e)}})().catch(e=>{var n;t?.signal?.aborted||e instanceof Error&&e.name===`AbortError`||(n=this.onerror)==null||n.call(this,e)});return}let g=new F({message:`MCP HTTP Transport Error: Unexpected content type: ${h}`,statusCode:m.status,url:this.url.href});throw(u=this.onerror)==null||u.call(this,g),g}catch(e){throw t?.signal?.aborted||(d=this.onerror)==null||d.call(this,e),e}};await a()}getStandardRequestHeaders(e){let t={"Mcp-Method":e.method},n=e.params,r=e.method===`resources/read`?n?.uri:e.method===`tools/call`||e.method===`prompts/get`?n?.name:void 0;return typeof r==`string`&&(t[`Mcp-Name`]=an(r)),t}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new F({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.isModernProtocol()||this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;if(!this.isModernProtocol())try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){let{resourceMetadataUrl:e,scope:i}=X(s);this.resourceMetadataUrl=e;try{if(await this.authorizeOnce(this.resourceMetadataUrl,i)!==`AUTHORIZED`){let e=new U;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new F({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new x).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),ln(i))try{let t=await P(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new F({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{c.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function dn(e){switch(e.type){case`sse`:return new tn(e);case`http`:return new un({...e,initialProtocolVersion:e.initialProtocolVersion??E});default:throw new F({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function fn(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var pn=`io.modelcontextprotocol/ui`,$=`text/html;profile=mcp-app`,mn=`ui/resourceUri`,hn={extensions:{[pn]:{mimeTypes:[$]}}};function gn(e){let n=e?.ui;return t(n)?n:void 0}var _n=c(n()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),vn=o({connectDomains:_n,resourceDomains:_n,frameDomains:_n}),yn=o({prefersBorder:m().optional().catch(void 0),csp:vn.optional().catch(void 0),permissions:r(a(),n()).optional().catch(void 0)});function bn(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=yn.safeParse(n);return r.success?r.data:void 0}function xn(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Sn(e){let t=gn(e._meta),n=t?.resourceUri??e._meta?.[mn],r=xn(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function Cn(e){let t=[],n=[];for(let r of e.tools){let e=Sn(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function wn({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(se(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:$,html:r,meta:bn(n._meta)}}async function Tn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return wn({uri:t,resource:await e.readResource({uri:t,options:n})})}var En=`1.0.0`,Dn=0,On=1e3,kn=[-32020,-32021,-32022],An=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function jn(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function Mn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function Nn(e){let t=jn(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(F.isInstance(e)&&e.code!=null)return!1;let n=Mn(e);return n!=null&&An.includes(n)}function Pn(e){if(e==null)return Dn;if(!Number.isInteger(e))throw new F({message:`maxRetries must be an integer`});if(e<0)throw new F({message:`maxRetries must be >= 0`});return e}function Fn({timeout:e,maxTotalTimeout:t}){return e==null?t:t==null?e:Math.min(e,t)}function In(e,t){return t==null?e:new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,a)},a=()=>{i(),r(t.reason)};if(t.aborted){a();return}t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{i(),n(e)}).catch(e=>{i(),r(e)})})}function Ln({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function Rn(e){let t=new zn(e);return await t.init(),t}var zn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=En,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s,initializationOptions:c,protocolVersionDiscovery:l=!0}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:D,capabilities:{},serverInfo:this._serverInfo},this.protocolEra=`legacy`,this.protocolVersion=D,this.toolHeaderBindings=new Map,this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=Pn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,this.initializationOptions=c,this.protocolVersionDiscovery=l,this.transport=fn(e)?e:dn(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new F({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){let e=this.initializationOptions?.signal,t=this.initializationOptions?Fn(this.initializationOptions):void 0,n=t==null?void 0:new AbortController,r=e==null?n?.signal:n==null?e:AbortSignal.any([e,n.signal]),i,a;t!=null&&(i=setTimeout(()=>{a=new F({message:`MCP client initialization timed out after ${t}ms`}),n?.abort(a)},t));try{if(this.isClosed=!1,r?.throwIfAborted(),await In(this.transport.start(),r),this.initialInitializeResult){let e=we.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}if(this.protocolVersionDiscovery&&this.transport.supportsProtocolVersionDiscovery&&await this.tryProtocolDiscovery(r))return this;this.protocolEra=`legacy`,this.protocolVersion=D,this.setTransportProtocolVersion(this.protocolVersion);let e=await this.request({request:{method:`initialize`,params:{protocolVersion:D,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:we,options:{signal:r}});if(e===void 0)throw new F({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`},{signal:r}),this}catch(t){try{await In(this.transport.close({signal:r}),r)}catch{}throw this.onClose(),a??(e?.aborted?new F({message:`MCP client initialization was aborted`,cause:e.reason}):t)}finally{i!=null&&clearTimeout(i)}}async tryProtocolDiscovery(e){this.protocolEra=`modern`,this.protocolVersion=E,this.setTransportProtocolVersion(this.protocolVersion);try{let t=await this.request({request:{method:`server/discover`},resultSchema:Ce,options:{signal:e,timeout:On}});return this.applyDiscoverResult(t),!0}catch(e){if(F.isInstance(e)&&e.code!=null&&kn.includes(e.code))throw e;return!1}}applyDiscoverResult(e){if(!e.supportedVersions.includes(this.protocolVersion))throw new F({message:`Server does not support the requested protocol version: ${this.protocolVersion}`});let t=e._meta?.[`io.modelcontextprotocol/serverInfo`];typeof t==`object`&&t&&`name`in t&&typeof t.name==`string`&&`version`in t&&typeof t.version==`string`&&(this._serverInfo=t),this.serverCapabilities=e.capabilities,this._serverInstructions=e.instructions,this._initializeResult={protocolVersion:this.protocolVersion,capabilities:e.capabilities,serverInfo:this._serverInfo,instructions:e.instructions}}setTransportProtocolVersion(e){this.transport.setProtocolVersion?this.transport.setProtocolVersion(e):this.transport.protocolVersion=e}applyInitializeResult(e){if(!_e.includes(e.protocolVersion))throw new F({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this.protocolEra=`legacy`,this.protocolVersion=e.protocolVersion,this._serverInfo=e.serverInfo,this._initializeResult=e,this.setTransportProtocolVersion(e.protocolVersion),this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}send(e,t){return t==null?this.transport.send(e):this.transport.send(e,t)}assertCapability(e){switch(e){case`initialize`:case`server/discover`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new F({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new F({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new F({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new F({message:`Server does not support prompts`});break;default:throw new F({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new F({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=n==null?void 0:Fn(n),s=o==null?void 0:new AbortController,c=a==null?s?.signal:s==null?a:AbortSignal.any([a,s.signal]),l,u=this.requestMessageId++,d=this.protocolEra===`modern`?{...e,params:{...e.params,_meta:{...e.params?._meta,"io.modelcontextprotocol/protocolVersion":this.protocolVersion,"io.modelcontextprotocol/clientCapabilities":this.clientCapabilities,"io.modelcontextprotocol/clientInfo":this.clientInfo}}}:e,f={...d,jsonrpc:`2.0`,id:u},p=this.getToolRequestHeaders(d),m=()=>{i(new F({message:`Request was aborted`,cause:a?.reason}))},h=()=>{this.responseHandlers.delete(u),a?.removeEventListener(`abort`,_),l!=null&&clearTimeout(l)},g=e=>{h(),i(e)},_=()=>{h(),m()};this.responseHandlers.set(u,e=>{if(a?.aborted)return h(),m();if(e instanceof Error)return g(e);try{if(this.protocolEra===`modern`&&e.result.resultType==null)throw new F({message:`Modern MCP result is missing resultType`});if(e.result.resultType===`input_required`)throw new F({message:`Server requested additional input, but multi round-trip requests are not supported yet`});let n=t.parse(e.result);h(),r(n)}catch(e){let t=F.isInstance(e)?e:new F({message:`Failed to parse server response`,cause:e});g(t)}}),a?.addEventListener(`abort`,_,{once:!0}),o!=null&&(l=setTimeout(()=>{let e=new F({message:`Request timed out after ${o}ms`});s?.abort(e),g(e)},o));let v={...c==null?{}:{signal:c},...p==null?{}:{headers:p}};(Object.keys(v).length===0?this.send(f):this.send(f,v)).catch(e=>{g(e)})})}async listTools({params:e,options:t}={}){let n=await this.request({request:{method:`tools/list`,params:e},resultSchema:Ee,options:t});return this.prepareToolDefinitions(n,e?.cursor==null)}prepareToolDefinitions(e,t=!1){if(this.protocolEra!==`modern`||!this.transport.supportsMcpToolParameterHeaders)return e;t&&this.toolHeaderBindings.clear();let n=e.tools.filter(e=>{let t=on(e.inputSchema);return t.success?(this.toolHeaderBindings.set(e.name,t.bindings),!0):(this.onError(new F({message:`Ignoring MCP tool "${e.name}": ${t.error}`})),!1)});return{...e,tools:n}}getToolRequestHeaders(e){if(this.protocolEra!==`modern`||e.method!==`tools/call`||typeof e.params?.name!=`string`)return;let t=this.toolHeaderBindings.get(e.params.name);if(t==null||t.length===0)return;let n=e.params.arguments;if(typeof n==`object`&&n&&!Array.isArray(n))try{return cn({bindings:t,args:n})}catch(t){throw new F({message:`Failed to create MCP headers for tool "${e.params.name}"`,cause:t})}}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():ce({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:Nn,createRetryError:({message:e,errors:t})=>new F({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:ze,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ae,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:He,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:Ve,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Ye,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Ze,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:Ke,options:e})}async notification(e,t){let n={...e,jsonrpc:`2.0`};await In(this.send(n,t?.signal==null?void 0:{signal:t.signal}),t?.signal)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools(),n=[...t.tools];for(;t.nextCursor!=null;)t=await this.listTools({params:{cursor:t.nextCursor}}),n.push(...t.tools);return this.toolsFromDefinitions({...t,tools:n},{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){e=this.prepareToolDefinitions(e);let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=Sn({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...s==null?{}:{annotations:{...s.title==null?{}:{title:s.title},...s.readOnlyHint==null?{}:{readOnlyHint:s.readOnlyHint},...s.destructiveHint==null?{}:{destructiveHint:s.destructiveHint},...s.idempotentHint==null?{}:{idempotentHint:s.idempotentHint},...s.openWorldHint==null?{}:{openWorldHint:s.openWorldHint}}},...d?.resourceUri==null?{}:{app:{...d,mimeType:$}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?re({description:a,title:e,metadata:f,inputSchema:S({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Ln}):ae({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Ln}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await ie({value:e.structuredContent,schema:oe(t)});if(!r.success)throw new F({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await ee({text:r.text,schema:t});if(!e.success)throw new F({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new F({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==j)throw new F({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=j.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=$e.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new F({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){if(e.id==null){this.onError(new F({message:`Protocol error: Received a response without a message ID: ${JSON.stringify(e)}`}));return}let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new F({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new F({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Bn=new TextEncoder;function Vn(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map(Vn).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Vn(t[e])}`).join(`,`)}}`}function Hn(e){return w(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function Un(e){let t=await crypto.subtle.digest(`SHA-256`,Bn.encode(Vn({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return Hn(new Uint8Array(t))}function Wn(e,t){return e!==t}export{$e as ElicitResultSchema,j as ElicitationRequestSchema,$ as MCP_APP_MIME_TYPE,U as UnauthorizedError,Q as auth,Rn as createMCPClient,Rn as experimental_createMCPClient,Wn as detectMCPAppResourceDrift,Un as fingerprintMCPAppResource,hn as mcpAppClientCapabilities,Tn as readMCPAppResource,Cn as splitMCPAppTools,N as validateJSONRPCMessage};