UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

1 lines 40.1 kB
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{Bi as n}from"../../_chunks/workflow/core-CXJbIkCL.js";import{At as r,Dt as i,En as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,Zn as f,dn as p,fn as m,wn as h}from"../../_chunks/workflow/schemas-iG9Z4s4o.js";import{n as ee}from"../../_chunks/workflow/compat-DLpWymPP.js";import{$ as g,I as te,J as _,K as ne,S as v,U as re,W as ie,i as ae,k as oe,n as se,y as ce}from"../../_chunks/workflow/dist-DTchiX0N.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await y).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var me=`vercel.ai.error.AI_MCPClientError`,he=Symbol.for(me),ge,_e,b=class extends (_e=e,ge=he,_e){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[ge]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,me)}},x=`2025-11-25`,ve=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=a(s(c(),f())),be=m({name:c(),version:c(),title:a(c())}),S=m({_meta:a(l({}).loose())}),C=S,xe=l({method:c(),params:a(S)}),Se=l({applyDefaults:a(r())}).loose(),Ce=m({experimental:a(l({}).loose()),logging:a(l({}).loose()),prompts:a(m({listChanged:a(r())})),resources:a(m({subscribe:a(r()),listChanged:a(r())})),tools:a(m({listChanged:a(r())})),elicitation:a(Se)});l({elicitation:a(Se)}).loose();var we=C.extend({protocolVersion:c(),capabilities:Ce,serverInfo:be,instructions:a(c())}),w=C.extend({nextCursor:a(c())}),Te=l({name:c(),title:a(c()),description:a(c()),inputSchema:l({type:p(`object`),properties:a(l({}).loose())}).loose(),outputSchema:a(l({}).loose()),annotations:a(l({title:a(c())}).loose()),_meta:ye}).loose(),Ee=w.extend({tools:o(Te)}),De=l({type:p(`text`),text:c()}).loose(),T=l({type:p(`image`),data:i(),mimeType:c()}).loose(),Oe=l({uri:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c()),size:a(h())}).loose(),ke=w.extend({resources:o(Oe)}),E=l({uri:c(),name:a(c()),title:a(c()),mimeType:a(c())}).loose(),D=E.extend({text:c()}),O=E.extend({blob:i()}),Ae=l({type:p(`resource`),resource:d([D,O])}).loose(),je=l({type:p(`resource_link`),uri:c(),name:c(),description:a(c()),mimeType:a(c())}).loose(),Me=C.extend({content:o(d([De,T,Ae,je])),structuredContent:a(f()),isError:r().default(!1).optional()}).or(C.extend({toolResult:f()})),Ne=l({uriTemplate:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c())}).loose(),Pe=C.extend({resourceTemplates:o(Ne)}),Fe=C.extend({contents:o(d([D,O]))}),Ie=l({name:c(),description:a(c()),required:a(r())}).loose(),Le=l({name:c(),title:a(c()),description:a(c()),arguments:a(o(Ie))}).loose(),Re=w.extend({prompts:o(Le)}),ze=l({role:d([p(`user`),p(`assistant`)]),content:d([De,T,Ae,je])}).loose(),Be=C.extend({description:a(c()),messages:o(ze)}),Ve=S.extend({message:c(),requestedSchema:f()}),k=xe.extend({method:p(`elicitation/create`),params:Ve}),He=C.extend({action:d([p(`accept`),p(`decline`),p(`cancel`)]),content:a(s(c(),f()))}),A=`2.0`,Ue=l({jsonrpc:p(A),id:d([c(),h().int()])}).merge(xe).strict(),We=l({jsonrpc:p(A),id:d([c(),h().int()]),result:C}).strict(),Ge=l({jsonrpc:p(A),id:d([c(),h().int()]),error:l({code:h().int(),message:c(),data:a(f())})}).strict(),j=d([Ue,l({jsonrpc:p(A)}).merge(l({method:c(),params:a(S)})).strict(),We,Ge]);async function M(e){return j.parse(await te({text:e}))}var Ke=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,N=c().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ee.custom,message:`URL must be parseable`,fatal:!0}),n}).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`}),P=l({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:h().optional(),scope:c().optional(),refresh_token:c().optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),qe=l({resource:c().url(),authorization_servers:o(N).optional(),jwks_uri:c().url().optional(),scopes_supported:o(c()).optional(),bearer_methods_supported:o(c()).optional(),resource_signing_alg_values_supported:o(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(c()).optional(),dpop_signing_alg_values_supported:o(c()).optional(),dpop_bound_access_tokens_required:r().optional()}).passthrough(),F=l({issuer:c(),authorization_endpoint:N,token_endpoint:N,registration_endpoint:N.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),code_challenge_methods_supported:o(c()),token_endpoint_auth_methods_supported:o(c()).optional(),token_endpoint_auth_signing_alg_values_supported:o(c()).optional()}).passthrough(),Je=l({issuer:c(),authorization_endpoint:N,token_endpoint:N,userinfo_endpoint:N.optional(),jwks_uri:N,registration_endpoint:N.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),subject_types_supported:o(c()),id_token_signing_alg_values_supported:o(c()),claims_supported:o(c()).optional(),token_endpoint_auth_methods_supported:o(c()).optional()}).passthrough().merge(F.pick({code_challenge_methods_supported:!0})),Ye=l({client_id:c(),client_secret:c().optional(),client_id_issued_at:h().optional(),client_secret_expires_at:h().optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),Xe=l({redirect_uris:o(N),token_endpoint_auth_method:c().optional(),grant_types:o(c()).optional(),response_types:o(c()).optional(),client_name:c().optional(),client_uri:N.optional(),logo_uri:N.optional(),scope:c().optional(),contacts:o(c()).optional(),tos_uri:N.optional(),policy_uri:c().optional(),jwks_uri:N.optional(),jwks:u().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ze=l({error:c(),error_description:c().optional(),error_uri:c().optional()}),Qe=Xe.merge(Ye),I=`vercel.ai.error.AI_MCPClientOAuthError`,$e=Symbol.for(I),L,R,z=class extends (R=e,L=$e,R){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[L]=!0}static isInstance(t){return e.hasMarker(t,I)}},B=class extends z{};B.errorCode=`server_error`;var V=class extends z{};V.errorCode=`invalid_client`;var H=class extends z{};H.errorCode=`invalid_grant`;var U=class extends z{};U.errorCode=`unauthorized_client`;var et={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function tt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function W(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function nt({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 G=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function K(e){return new URL(e).href}function rt(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function it(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function st({provider:e,clientInformation:t,tokens:n}){let r=ot(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:ot(t)}async function ct({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(at(t,n)),!0):!1}function lt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new z({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function ut({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new z({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function q(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(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function dt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function ft(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function pt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function mt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=dt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await ft(o,a,n);return!r?.metadataUrl&&pt(s,i.pathname)&&(s=await ft(new URL(`/.well-known/${t}`,i),a,n)),s}async function ht(e,t,n=fetch){let r=await mt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});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 qe.parse(await r.json())}function gt(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 _t(e,t){if(e.issuer!==t)throw new z({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function vt(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=gt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=F.parse(await i.json());return _t(e,a),e}else{let t=Je.parse(await i.json());if(_t(t,a),!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 yt(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 pe(),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`,W(o)),{authorizationUrl:l,codeVerifier:d}}function Y(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 bt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:xt(i,a,n);return;case`client_secret_post`:St(i,a,r);return;case`none`:Ct(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function xt(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 St(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ct(e,t){t.set(`client_id`,e)}async function X(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}=Ze.parse(await te({text:n}));return new(et[e]||B)({message:t||``,cause:r})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function wt(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);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):bt(Y(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,W(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await X(p);return P.parse(await p.json())}async function Tt(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=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):bt(Y(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,W(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await X(d);return P.parse({refresh_token:r,...await d.json()})}async function Et(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=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await X(a);return Qe.parse(await a.json())}async function Z(e,t){try{return await Q(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Q(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Q(e,t);throw n}}async function Dt(e,t,n){let r=tt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!nt({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 Q(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;lt(t,a);try{s=await ht(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await Dt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await vt(c,{fetchFn:o}),d=rt(c,u),f=await Promise.resolve(e.clientInformation());if(!f){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`);f=at(await Et(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}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=await st({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});ut({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await wt(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(it(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await st({provider:e,clientInformation:f,tokens:p});t?ut({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Tt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(it(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof z)||e instanceof B))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:ee}=await yt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await ct({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(h),`REDIRECT`}function Ot(e){return e===void 0||e===`message`}var kt=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??x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Ke}`,v())}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){this.resourceMetadataUrl=q(c);try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;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 b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).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 b({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 b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Ot(s))try{let e=await M(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new b({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){if(!this.endpoint||!this.connected)throw new b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function At(e){return e===void 0||e===`message`}var jt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){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.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Ke}`,v())}authorizeOnce(e){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=q(l);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t,statusCode:l.status,url:this.url.href,responseBody:e??void 0});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>j.parse(e)):[j.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:l.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(At(a))try{let e=await M(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`,statusCode:l.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await 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 b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(o);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(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(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`,statusCode:o.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).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),At(i))try{let t=await M(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({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()},this.inboundReconnectAttempts=0,l()}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 Mt(e){switch(e.type){case`sse`:return new kt(e);case`http`:return new jt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Nt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Pt=`io.modelcontextprotocol/ui`,$=`text/html;profile=mcp-app`,Ft=`ui/resourceUri`,It={extensions:{[Pt]:{mimeTypes:[$]}}};function Lt(e){let n=e?.ui;return t(n)?n:void 0}function Rt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function zt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Bt(e){let t=Lt(e._meta),n=t?.resourceUri??e._meta?.[Ft],r=zt(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 Vt(e){let t=[],n=[];for(let r of e.tools){let e=Bt(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 Ht({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(ae(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:$,html:r,meta:Rt(n._meta)}}async function Ut({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Ht({uri:t,resource:await e.readResource({uri:t,options:n})})}var Wt=`1.0.0`;function Gt({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 Kt(e){let t=new qt(e);return await t.init(),t}var qt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Wt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},Nt(e)?this.transport=e:this.transport=Mt(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 b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:we});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ve.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:Ee,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Me,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:ke,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Fe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:Pe,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Re,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:Be,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){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=Bt({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...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`?ce({description:a,title:e,metadata:f,inputSchema:oe({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Gt}):ne({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Gt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await ie({value:e.structuredContent,schema:se(t)});if(!r.success)throw new b({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 re({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({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})}onElicitationRequest(e,t){if(e!==k)throw new b({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=k.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=He.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 b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{He as ElicitResultSchema,k as ElicitationRequestSchema,$ as MCP_APP_MIME_TYPE,G as UnauthorizedError,Z as auth,Kt as createMCPClient,Kt as experimental_createMCPClient,It as mcpAppClientCapabilities,Ut as readMCPAppResource,Vt as splitMCPAppTools};