@gram-ai/elements 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/assistant-ui/d3-renderer.d.ts +5 -0
- package/dist/elements.cjs +37 -26
- package/dist/elements.css +1 -1
- package/dist/elements.js +18701 -6890
- package/dist/{models-cel0aeUV.js → index-DxNldiiY.js} +281 -281
- package/dist/{models-BuM4eiir.cjs → index-IZN-i8ZU.cjs} +9 -9
- package/dist/server.cjs +1 -1
- package/dist/server.js +1 -1
- package/package.json +2 -1
package/dist/server.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./models-BuM4eiir.cjs");var Os=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},xe="1.9.0",tn=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ms(e){var t=new Set([e]),r=new Set,n=e.match(tn);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(c){return c===e};function o(i){return r.add(i),!1}function l(i){return t.add(i),!0}return function(c){if(t.has(c))return!0;if(r.has(c))return!1;var u=c.match(tn);if(!u)return o(c);var d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return d.prerelease!=null||s.major!==d.major?o(c):s.major===0?s.minor===d.minor&&s.patch<=d.patch?l(c):o(c):s.minor<=d.minor?l(c):o(c)}}var Ns=Ms(xe),$s=xe.split(".")[0],We=Symbol.for("opentelemetry.js.api."+$s),Ye=Os;function Er(e,t,r,n){var s;n===void 0&&(n=!1);var o=Ye[We]=(s=Ye[We])!==null&&s!==void 0?s:{version:xe};if(!n&&o[e]){var l=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(l.stack||l.message),!1}if(o.version!==xe){var l=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+xe);return r.error(l.stack||l.message),!1}return o[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+xe+"."),!0}function Xe(e){var t,r,n=(t=Ye[We])===null||t===void 0?void 0:t.version;if(!(!n||!Ns(n)))return(r=Ye[We])===null||r===void 0?void 0:r[e]}function Sr(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+xe+".");var r=Ye[We];r&&delete r[e]}var js=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){l={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Ds=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Us=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("verbose",this._namespace,t)},e})();function Be(e,t,r){var n=Xe("diag");if(n)return r.unshift(t),n[e].apply(n,Ds([],js(r),!1))}var Q;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Q||(Q={}));function qs(e,t){e<Q.NONE?e=Q.NONE:e>Q.ALL&&(e=Q.ALL),t=t||{};function r(n,s){var o=t[n];return typeof o=="function"&&e>=s?o.bind(t):function(){}}return{error:r("error",Q.ERROR),warn:r("warn",Q.WARN),info:r("info",Q.INFO),debug:r("debug",Q.DEBUG),verbose:r("verbose",Q.VERBOSE)}}var Fs=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){l={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Ls=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Vs="diag",vt=(function(){function e(){function t(s){return function(){for(var o=[],l=0;l<arguments.length;l++)o[l]=arguments[l];var i=Xe("diag");if(i)return i[s].apply(i,Ls([],Fs(o),!1))}}var r=this,n=function(s,o){var l,i,c;if(o===void 0&&(o={logLevel:Q.INFO}),s===r){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((l=u.stack)!==null&&l!==void 0?l:u.message),!1}typeof o=="number"&&(o={logLevel:o});var d=Xe("diag"),p=qs((i=o.logLevel)!==null&&i!==void 0?i:Q.INFO,s);if(d&&!o.suppressOverrideMessage){var h=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+h),p.warn("Current logger will overwrite one already registered from "+h)}return Er("diag",p,r,!0)};r.setLogger=n,r.disable=function(){Sr(Vs,r)},r.createComponentLogger=function(s){return new Us(s)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function Hs(e){return Symbol.for(e)}var Bs=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var o=new e(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=function(n){var s=new e(r._currentContext);return s._currentContext.delete(n),s}}return e})(),Zs=new Bs,Ks=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){l={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Gs=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Js=(function(){function e(){}return e.prototype.active=function(){return Zs},e.prototype.with=function(t,r,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return r.call.apply(r,Gs([n],Ks(s),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),zs=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){l={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Ws=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Gt="context",Ys=new Js,ra=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Er(Gt,t,vt.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var s,o=[],l=3;l<arguments.length;l++)o[l-3]=arguments[l];return(s=this._getContextManager()).with.apply(s,Ws([t,r,n],zs(o),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return Xe(Gt)||Ys},e.prototype.disable=function(){this._getContextManager().disable(),Sr(Gt,vt.instance())},e})(),ur;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(ur||(ur={}));var na="0000000000000000",aa="00000000000000000000000000000000",Xs={traceId:aa,spanId:na,traceFlags:ur.NONE},Je=(function(){function e(t){t===void 0&&(t=Xs),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,r){},e})(),xr=Hs("OpenTelemetry Context Key SPAN");function Rr(e){return e.getValue(xr)||void 0}function Qs(){return Rr(ra.getInstance().active())}function Ar(e,t){return e.setValue(xr,t)}function ei(e){return e.deleteValue(xr)}function ti(e,t){return Ar(e,new Je(t))}function oa(e){var t;return(t=Rr(e))===null||t===void 0?void 0:t.spanContext()}var ri=/^([0-9a-f]{32})$/i,ni=/^[0-9a-f]{16}$/i;function ai(e){return ri.test(e)&&e!==aa}function oi(e){return ni.test(e)&&e!==na}function sa(e){return ai(e.traceId)&&oi(e.spanId)}function si(e){return new Je(e)}var Jt=ra.getInstance(),ia=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Jt.active());var s=!!r?.root;if(s)return new Je;var o=n&&oa(n);return ii(o)&&sa(o)?new Je(o):new Je},e.prototype.startActiveSpan=function(t,r,n,s){var o,l,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(o=r,i=n):(o=r,l=n,i=s);var c=l??Jt.active(),u=this.startSpan(t,o,c),d=Ar(c,u);return Jt.with(d,i,void 0,u)}},e})();function ii(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var li=new ia,ui=(function(){function e(t,r,n,s){this._provider=t,this.name=r,this.version=n,this.options=s}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):li},e})(),ci=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new ia},e})(),di=new ci,rn=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var s;return(s=this.getDelegateTracer(t,r,n))!==null&&s!==void 0?s:new ui(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:di},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(t,r,n)},e})(),yt;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(yt||(yt={}));var zt="trace",pi=(function(){function e(){this._proxyTracerProvider=new rn,this.wrapSpanContext=si,this.isSpanContextValid=sa,this.deleteSpan=ei,this.getSpan=Rr,this.getActiveSpan=Qs,this.getSpanContext=oa,this.setSpan=Ar,this.setSpanContext=ti}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Er(zt,this._proxyTracerProvider,vt.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return Xe(zt)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Sr(zt,vt.instance()),this._proxyTracerProvider=new rn},e})(),fi=pi.getInstance();let Cr;Cr=globalThis.crypto;async function mi(e){return(await Cr).getRandomValues(new Uint8Array(e))}async function hi(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const s=await mi(e-n.length);for(const o of s)o<r&&(n+=t[o%t.length])}return n}async function gi(e){return await hi(e)}async function vi(e){const t=await(await Cr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function yi(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await gi(e),r=await vi(t);return{code_verifier:t,code_challenge:r}}var _i="AI_MCPClientError",la=`vercel.ai.error.${_i}`,bi=Symbol.for(la),nn,an,j=class extends(an=a.AISDKError,nn=bi,an){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:s}){super({name:e,message:t,cause:r}),this[nn]=!0,this.data=n,this.code=s}static isInstance(e){return a.AISDKError.hasMarker(e,la)}},De="2025-06-18",wi=[De,"2025-03-26","2024-11-05"],Ti=a.looseObject({name:a.string(),version:a.string()}),kt=a.looseObject({_meta:a.optional(a.object({}).loose())}),be=kt,ua=a.object({method:a.string(),params:a.optional(kt)}),ca=a.object({applyDefaults:a.optional(a.boolean())}).loose(),Ii=a.looseObject({experimental:a.optional(a.object({}).loose()),logging:a.optional(a.object({}).loose()),prompts:a.optional(a.looseObject({listChanged:a.optional(a.boolean())})),resources:a.optional(a.looseObject({subscribe:a.optional(a.boolean()),listChanged:a.optional(a.boolean())})),tools:a.optional(a.looseObject({listChanged:a.optional(a.boolean())})),elicitation:a.optional(ca)});a.object({elicitation:a.optional(ca)}).loose();var Ei=be.extend({protocolVersion:a.string(),capabilities:Ii,serverInfo:Ti,instructions:a.optional(a.string())}),Pr=be.extend({nextCursor:a.optional(a.string())}),Si=a.object({name:a.string(),description:a.optional(a.string()),inputSchema:a.object({type:a.literal("object"),properties:a.optional(a.object({}).loose())}).loose()}).loose(),xi=Pr.extend({tools:a.array(Si)}),da=a.object({type:a.literal("text"),text:a.string()}).loose(),pa=a.object({type:a.literal("image"),data:a.base64(),mimeType:a.string()}).loose(),Ri=a.object({uri:a.string(),name:a.string(),title:a.optional(a.string()),description:a.optional(a.string()),mimeType:a.optional(a.string()),size:a.optional(a.number())}).loose(),Ai=Pr.extend({resources:a.array(Ri)}),fa=a.object({uri:a.string(),name:a.optional(a.string()),title:a.optional(a.string()),mimeType:a.optional(a.string())}).loose(),ma=fa.extend({text:a.string()}),ha=fa.extend({blob:a.base64()}),ga=a.object({type:a.literal("resource"),resource:a.union([ma,ha])}).loose(),Ci=be.extend({content:a.array(a.union([da,pa,ga])),isError:a.boolean().default(!1).optional()}).or(be.extend({toolResult:a.unknown()})),Pi=a.object({uriTemplate:a.string(),name:a.string(),title:a.optional(a.string()),description:a.optional(a.string()),mimeType:a.optional(a.string())}).loose(),ki=be.extend({resourceTemplates:a.array(Pi)}),Oi=be.extend({contents:a.array(a.union([ma,ha]))}),Mi=a.object({name:a.string(),description:a.optional(a.string()),required:a.optional(a.boolean())}).loose(),Ni=a.object({name:a.string(),title:a.optional(a.string()),description:a.optional(a.string()),arguments:a.optional(a.array(Mi))}).loose(),$i=Pr.extend({prompts:a.array(Ni)}),ji=a.object({role:a.union([a.literal("user"),a.literal("assistant")]),content:a.union([da,pa,ga])}).loose(),Di=be.extend({description:a.optional(a.string()),messages:a.array(ji)}),Ui=kt.extend({message:a.string(),requestedSchema:a.unknown()}),on=ua.extend({method:a.literal("elicitation/create"),params:Ui}),qi=be.extend({action:a.union([a.literal("accept"),a.literal("decline"),a.literal("cancel")]),content:a.optional(a.record(a.string(),a.unknown()))}),Ot="2.0",Fi=a.object({jsonrpc:a.literal(Ot),id:a.union([a.string(),a.number().int()])}).merge(ua).strict(),Li=a.object({jsonrpc:a.literal(Ot),id:a.union([a.string(),a.number().int()]),result:be}).strict(),Vi=a.object({jsonrpc:a.literal(Ot),id:a.union([a.string(),a.number().int()]),error:a.object({code:a.number().int(),message:a.string(),data:a.optional(a.unknown())})}).strict(),Hi=a.object({jsonrpc:a.literal(Ot)}).merge(a.object({method:a.string(),params:a.optional(kt)})).strict(),Ge=a.union([Fi,Hi,Li,Vi]),va=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",ya=a.object({access_token:a.string(),id_token:a.string().optional(),token_type:a.string(),expires_in:a.number().optional(),scope:a.string().optional(),refresh_token:a.string().optional()}).strip(),X=a.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:a.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),a.NEVER}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Bi=a.object({resource:a.string().url(),authorization_servers:a.array(X).optional(),jwks_uri:a.string().url().optional(),scopes_supported:a.array(a.string()).optional(),bearer_methods_supported:a.array(a.string()).optional(),resource_signing_alg_values_supported:a.array(a.string()).optional(),resource_name:a.string().optional(),resource_documentation:a.string().optional(),resource_policy_uri:a.string().url().optional(),resource_tos_uri:a.string().url().optional(),tls_client_certificate_bound_access_tokens:a.boolean().optional(),authorization_details_types_supported:a.array(a.string()).optional(),dpop_signing_alg_values_supported:a.array(a.string()).optional(),dpop_bound_access_tokens_required:a.boolean().optional()}).passthrough(),_a=a.object({issuer:a.string(),authorization_endpoint:X,token_endpoint:X,registration_endpoint:X.optional(),scopes_supported:a.array(a.string()).optional(),response_types_supported:a.array(a.string()),grant_types_supported:a.array(a.string()).optional(),code_challenge_methods_supported:a.array(a.string()),token_endpoint_auth_methods_supported:a.array(a.string()).optional(),token_endpoint_auth_signing_alg_values_supported:a.array(a.string()).optional()}).passthrough(),Zi=a.object({issuer:a.string(),authorization_endpoint:X,token_endpoint:X,userinfo_endpoint:X.optional(),jwks_uri:X,registration_endpoint:X.optional(),scopes_supported:a.array(a.string()).optional(),response_types_supported:a.array(a.string()),grant_types_supported:a.array(a.string()).optional(),subject_types_supported:a.array(a.string()),id_token_signing_alg_values_supported:a.array(a.string()),claims_supported:a.array(a.string()).optional(),token_endpoint_auth_methods_supported:a.array(a.string()).optional()}).passthrough(),Ki=Zi.merge(_a.pick({code_challenge_methods_supported:!0})),Gi=a.object({client_id:a.string(),client_secret:a.string().optional(),client_id_issued_at:a.number().optional(),client_secret_expires_at:a.number().optional()}).strip(),Ji=a.object({redirect_uris:a.array(X),token_endpoint_auth_method:a.string().optional(),grant_types:a.array(a.string()).optional(),response_types:a.array(a.string()).optional(),client_name:a.string().optional(),client_uri:X.optional(),logo_uri:X.optional(),scope:a.string().optional(),contacts:a.array(a.string()).optional(),tos_uri:X.optional(),policy_uri:a.string().optional(),jwks_uri:X.optional(),jwks:a.any().optional(),software_id:a.string().optional(),software_version:a.string().optional(),software_statement:a.string().optional()}).strip(),zi=a.object({error:a.string(),error_description:a.string().optional(),error_uri:a.string().optional()}),Wi=Ji.merge(Gi),Yi="AI_MCPClientOAuthError",ba=`vercel.ai.error.${Yi}`,Xi=Symbol.for(ba),sn,ln,st=class extends(ln=a.AISDKError,sn=Xi,ln){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[sn]=!0}static isInstance(e){return a.AISDKError.hasMarker(e,ba)}},je=class extends st{};je.errorCode="server_error";var _t=class extends st{};_t.errorCode="invalid_client";var bt=class extends st{};bt.errorCode="invalid_grant";var wt=class extends st{};wt.errorCode="unauthorized_client";var Qi={[je.errorCode]:je,[_t.errorCode]:_t,[bt.errorCode]:bt,[wt.errorCode]:wt};function el(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function tl({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}var Tt=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function It(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,s]=r.split(" ");if(n.toLowerCase()!=="bearer"||!s)return;const o=/resource_metadata="([^"]*)"/,l=r.match(o);if(l)try{return new URL(l[1])}catch{return}}function rl(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function kr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?kr(e,void 0,r):void 0;throw n}}async function un(e,t,r=fetch){return await kr(e,{"MCP-Protocol-Version":t},r)}function nl(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function al(e,t,r,n){var s,o;const l=new URL(e),i=(s=n?.protocolVersion)!=null?s:De;let c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{const d=rl(t,l.pathname);c=new URL(d,(o=n?.metadataServerUrl)!=null?o:l),c.search=l.search}let u=await un(c,i,r);if(!n?.metadataUrl&&nl(u,l.pathname)){const d=new URL(`/.well-known/${t}`,l);u=await un(d,i,r)}return u}async function ol(e,t,r=fetch){const n=await al(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Bi.parse(await n.json())}function sl(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function il(e,{fetchFn:t=fetch,protocolVersion:r=De}={}){var n;const s={"MCP-Protocol-Version":r},o=sl(e);for(const{url:l,type:i}of o){const c=await kr(l,s,t);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${l}`)}if(i==="oauth")return _a.parse(await c.json());{const u=Ki.parse(await c.json());if(!((n=u.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${l}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function ll(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:l}){const i="code",c="S256";let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else u=new URL("/authorize",e);const d=await yi(),p=d.code_verifier,h=d.code_challenge;return u.searchParams.set("response_type",i),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",h),u.searchParams.set("code_challenge_method",c),u.searchParams.set("redirect_uri",String(n)),o&&u.searchParams.set("state",o),s&&u.searchParams.set("scope",s),s?.includes("offline_access")&&u.searchParams.append("prompt","consent"),l&&u.searchParams.set("resource",l.href),{authorizationUrl:u,codeVerifier:p}}function wa(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Ta(e,t,r,n){const{client_id:s,client_secret:o}=t;switch(e){case"client_secret_basic":ul(s,o,r);return;case"client_secret_post":cl(s,o,n);return;case"none":dl(s,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function ul(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function cl(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function dl(e,t){t.set("client_id",e)}async function Or(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=zi.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:l}=n,i=Qi[s]||je;return new i({message:o||"",cause:l})}catch(n){const s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new je({message:s})}}async function pl(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:o,resource:l,addClientAuthentication:i,fetchFn:c}){var u;const d="authorization_code",p=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:d,code:n,code_verifier:s,redirect_uri:String(o)});if(i)i(h,f,e,t);else{const v=(u=t?.token_endpoint_auth_methods_supported)!=null?u:[],_=wa(r,v);Ta(_,r,h,f)}l&&f.set("resource",l.href);const m=await(c??fetch)(p,{method:"POST",headers:h,body:f});if(!m.ok)throw await Or(m);return ya.parse(await m.json())}async function fl(e,{metadata:t,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:l}){var i;const c="refresh_token";let u;if(t){if(u=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",e);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),p=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(d,p,e,t);else{const f=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],m=wa(r,f);Ta(m,r,d,p)}s&&p.set("resource",s.href);const h=await(l??fetch)(u,{method:"POST",headers:d,body:p});if(!h.ok)throw await Or(h);return ya.parse({refresh_token:n,...await h.json()})}async function ml(e,{metadata:t,clientMetadata:r,fetchFn:n}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await Or(o);return Wi.parse(await o.json())}async function Et(e,t){var r,n;try{return await Wt(e,t)}catch(s){if(s instanceof _t||s instanceof wt)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Wt(e,t);if(s instanceof bt)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Wt(e,t);throw s}}async function hl(e,t,r){const n=el(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!tl({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function Wt(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let l,i;try{l=await ol(t,{resourceMetadataUrl:s},o),l.authorization_servers&&l.authorization_servers.length>0&&(i=l.authorization_servers[0])}catch{}i||(i=t);const c=await hl(t,e,l),u=await il(i,{fetchFn:o});let d=await Promise.resolve(e.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const v=await ml(i,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(v),d=v}if(r!==void 0){const v=await e.codeVerifier(),_=await pl(i,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:v,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(_),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const v=await fl(i,{metadata:u,clientInformation:d,refreshToken:p.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof st)||v instanceof je))throw v}const h=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:m}=await ll(i,{metadata:u,clientInformation:d,state:h,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(f),"REDIRECT"}var gl=class{constructor({url:e,headers:t,authProvider:r}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":De};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return a.withUserAgentSuffix(t,`ai-sdk/${va}`,a.getRuntimeEnvironmentUserAgent())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var s,o,l,i,c;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),d=await fetch(this.url.href,{headers:u,signal:(s=this.abortController)==null?void 0:s.signal});if(d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=It(d);try{if(await Et(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Tt;return(o=this.onerror)==null||o.call(this,v),t(v)}}catch(m){return(l=this.onerror)==null||l.call(this,m),t(m)}return r(!0)}if(!d.ok||!d.body){let m=`MCP SSE Transport Error: ${d.status} ${d.statusText}`;d.status===405&&(m+=". This server does not support SSE transport. Try using `http` transport instead");const v=new j({message:m});return(i=this.onerror)==null||i.call(this,v),t(v)}const h=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new a.EventSourceParserStream).getReader(),f=async()=>{var m,v,_;try{for(;;){const{done:y,value:w}=await h.read();if(y){if(this.connected)throw this.connected=!1,new j({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:b,data:g}=w;if(b==="endpoint"){if(this.endpoint=new URL(g,this.url),this.endpoint.origin!==this.url.origin)throw new j({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(b==="message")try{const E=Ge.parse(JSON.parse(g));(m=this.onmessage)==null||m.call(this,E)}catch(E){const S=new j({message:"MCP SSE Transport Error: Failed to parse message",cause:E});(v=this.onerror)==null||v.call(this,S)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(_=this.onerror)==null||_.call(this,y),t(y)}};this.sseConnection={close:()=>h.cancel()},f()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(c=this.onerror)==null||c.call(this,u),t(u)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new j({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var s,o,l,i,c;try{const d={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(s=this.abortController)==null?void 0:s.signal},p=await fetch(t,d);if(p.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=It(p);try{if(await Et(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new Tt;(o=this.onerror)==null||o.call(this,f);return}}catch(h){(l=this.onerror)==null||l.call(this,h);return}return r(!0)}if(!p.ok){const h=await p.text().catch(()=>null),f=new j({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${p.status}): ${h}`});(i=this.onerror)==null||i.call(this,f);return}}catch(u){(c=this.onerror)==null||c.call(this,u);return}};await r()}},vl=class{constructor({url:e,headers:t,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":De};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return a.withUserAgentSuffix(t,`ai-sdk/${va}`,a.getRuntimeEnvironmentUserAgent())}async start(){if(this.abortController)throw new j({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,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,s,o,l,i,c,u;try{const p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},h=await fetch(this.url,p),f=h.headers.get("mcp-session-id");if(f&&(this.sessionId=f),h.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=It(h);try{if(await Et(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Tt}catch(_){throw(s=this.onerror)==null||s.call(this,_),_}return t(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const _=await h.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${_}`;h.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const w=new j({message:y});throw(o=this.onerror)==null||o.call(this,w),w}const m=h.headers.get("content-type")||"";if(m.includes("application/json")){const _=await h.json(),y=Array.isArray(_)?_.map(w=>Ge.parse(w)):[Ge.parse(_)];for(const w of y)(l=this.onmessage)==null||l.call(this,w);return}if(m.includes("text/event-stream")){if(!h.body){const b=new j({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,b),b}const y=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new a.EventSourceParserStream).getReader();(async()=>{var b,g,E;try{for(;;){const{done:S,value:I}=await y.read();if(S)return;const{event:x,data:P}=I;if(x==="message")try{const F=Ge.parse(JSON.parse(P));(b=this.onmessage)==null||b.call(this,F)}catch(F){const K=new j({message:"MCP HTTP Transport Error: Failed to parse message",cause:F});(g=this.onerror)==null||g.call(this,K)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(E=this.onerror)==null||E.call(this,S)}})();return}const v=new j({message:`MCP HTTP Transport Error: Unexpected content type: ${m}`});throw(c=this.onerror)==null||c.call(this,v),v}catch(d){throw(u=this.onerror)==null||u.call(this,d),d}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new j({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,s,o,l,i;try{const c=await this.commonHeaders({Accept:"text/event-stream"});t&&(c["last-event-id"]=t);const u=await fetch(this.url.href,{method:"GET",headers:c,signal:(r=this.abortController)==null?void 0:r.signal}),d=u.headers.get("mcp-session-id");if(d&&(this.sessionId=d),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=It(u);try{if(await Et(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Tt;(n=this.onerror)==null||n.call(this,v);return}}catch(m){(s=this.onerror)==null||s.call(this,m);return}return this.openInboundSse(!0,t)}if(u.status===405)return;if(!u.ok||!u.body){const m=new j({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(o=this.onerror)==null||o.call(this,m);return}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new a.EventSourceParserStream).getReader(),f=async()=>{var m,v,_,y;try{for(;;){const{done:w,value:b}=await h.read();if(w)return;const{event:g,data:E,id:S}=b;if(S&&(this.lastInboundEventId=S),g==="message")try{const I=Ge.parse(JSON.parse(E));(m=this.onmessage)==null||m.call(this,I)}catch(I){const x=new j({message:"MCP HTTP Transport Error: Failed to parse message",cause:I});(v=this.onerror)==null||v.call(this,x)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(_=this.onerror)==null||_.call(this,w),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,f()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function yl(e){switch(e.type){case"sse":return new gl(e);case"http":return new vl(e);default:throw new j({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function _l(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var bl="1.0.0";async function wl(e){const t=new Tl(e);return await t.init(),t}var Tl=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=bl,onUncaughtError:n,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=s??{},_l(e)?this.transport=e:this.transport=yl(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new j({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:De,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Ei});if(e===void 0)throw new j({message:"Server sent invalid initialize result"});if(!wi.includes(e.protocolVersion))throw new j({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new j({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new j({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new j({message:"Server does not support prompts"});break;default:throw new j({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,s)=>{if(this.isClosed)return s(new j({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const o=r?.signal;o?.throwIfAborted();const l=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:l},c=()=>{this.responseHandlers.delete(l)};this.responseHandlers.set(l,u=>{if(o?.aborted)return s(new j({message:"Request was aborted",cause:o.reason}));if(u instanceof Error)return s(u);try{const d=t.parse(u.result);n(d)}catch(d){const p=new j({message:"Failed to parse server response",cause:d});s(p)}}),this.transport.send(i).catch(u=>{c(),s(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:xi,options:t})}catch(r){throw r}}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:Ci,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:Ai,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:Oi,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:ki,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:$i,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:Di,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const r={};try{const n=await this.listTools();for(const{name:s,description:o,inputSchema:l}of n.tools){if(e!=="automatic"&&!(s in e))continue;const i=this,c=async(d,p)=>{var h;return(h=p?.abortSignal)==null||h.throwIfAborted(),i.callTool({name:s,args:d,options:p})},u=e==="automatic"?a.dynamicTool({description:o,inputSchema:a.jsonSchema({...l,properties:(t=l.properties)!=null?t:{},additionalProperties:!1}),execute:c}):a.tool({description:o,inputSchema:e[s].inputSchema,execute:c});r[s]=u}return r}catch(n){throw n}}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})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==on)throw new j({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{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}const t=on.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{const r=await this.elicitationRequestHandler(t.data),n=qi.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new j({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new j({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new j({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Il=Object.defineProperty,El=Object.defineProperties,Sl=Object.getOwnPropertyDescriptors,cn=Object.getOwnPropertySymbols,xl=Object.prototype.hasOwnProperty,Rl=Object.prototype.propertyIsEnumerable,dn=(e,t,r)=>t in e?Il(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,D=(e,t)=>{for(var r in t||(t={}))xl.call(t,r)&&dn(e,r,t[r]);if(cn)for(var r of cn(t))Rl.call(t,r)&&dn(e,r,t[r]);return e},St=(e,t)=>El(e,Sl(t)),Ia="vercel.ai.error",Al=Symbol.for(Ia),Ea,Cl=class Sa extends Error{constructor({name:t,message:r,cause:n}){super(r),this[Ea]=!0,this.name=t,this.cause=n}static isInstance(t){return Sa.hasMarker(t,Ia)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};Ea=Al;var B=Cl,xa="AI_APICallError",Ra=`vercel.ai.error.${xa}`,Pl=Symbol.for(Ra),Aa,ce=class extends B{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:o,cause:l,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:c}){super({name:xa,message:e,cause:l}),this[Aa]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=o,this.isRetryable=i,this.data=c}static isInstance(e){return B.hasMarker(e,Ra)}};Aa=Pl;var Ca="AI_EmptyResponseBodyError",Pa=`vercel.ai.error.${Ca}`,kl=Symbol.for(Pa),ka,Ol=class extends B{constructor({message:e="Empty response body"}={}){super({name:Ca,message:e}),this[ka]=!0}static isInstance(e){return B.hasMarker(e,Pa)}};ka=kl;function Oa(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Ma="AI_InvalidArgumentError",Na=`vercel.ai.error.${Ma}`,Ml=Symbol.for(Na),$a,ja=class extends B{constructor({message:t,cause:r,argument:n}){super({name:Ma,message:t,cause:r}),this[$a]=!0,this.argument=n}static isInstance(t){return B.hasMarker(t,Na)}};$a=Ml;var Da="AI_InvalidPromptError",Ua=`vercel.ai.error.${Da}`,Nl=Symbol.for(Ua),qa,$l=class extends B{constructor({prompt:e,message:t,cause:r}){super({name:Da,message:`Invalid prompt: ${t}`,cause:r}),this[qa]=!0,this.prompt=e}static isInstance(e){return B.hasMarker(e,Ua)}};qa=Nl;var Fa="AI_InvalidResponseDataError",La=`vercel.ai.error.${Fa}`,jl=Symbol.for(La),Va,Ze=class extends B{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Fa,message:t}),this[Va]=!0,this.data=e}static isInstance(e){return B.hasMarker(e,La)}};Va=jl;var Ha="AI_JSONParseError",Ba=`vercel.ai.error.${Ha}`,Dl=Symbol.for(Ba),Za,xt=class extends B{constructor({text:e,cause:t}){super({name:Ha,message:`JSON parsing failed: Text: ${e}.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./index-IZN-i8ZU.cjs");var Os=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},xe="1.9.0",tn=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ms(e){var t=new Set([e]),r=new Set,n=e.match(tn);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(c){return c===e};function o(i){return r.add(i),!1}function l(i){return t.add(i),!0}return function(c){if(t.has(c))return!0;if(r.has(c))return!1;var u=c.match(tn);if(!u)return o(c);var d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return d.prerelease!=null||s.major!==d.major?o(c):s.major===0?s.minor===d.minor&&s.patch<=d.patch?l(c):o(c):s.minor<=d.minor?l(c):o(c)}}var Ns=Ms(xe),$s=xe.split(".")[0],We=Symbol.for("opentelemetry.js.api."+$s),Ye=Os;function Er(e,t,r,n){var s;n===void 0&&(n=!1);var o=Ye[We]=(s=Ye[We])!==null&&s!==void 0?s:{version:xe};if(!n&&o[e]){var l=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(l.stack||l.message),!1}if(o.version!==xe){var l=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+xe);return r.error(l.stack||l.message),!1}return o[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+xe+"."),!0}function Xe(e){var t,r,n=(t=Ye[We])===null||t===void 0?void 0:t.version;if(!(!n||!Ns(n)))return(r=Ye[We])===null||r===void 0?void 0:r[e]}function Sr(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+xe+".");var r=Ye[We];r&&delete r[e]}var js=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){l={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Ds=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Us=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Be("verbose",this._namespace,t)},e})();function Be(e,t,r){var n=Xe("diag");if(n)return r.unshift(t),n[e].apply(n,Ds([],js(r),!1))}var Q;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Q||(Q={}));function qs(e,t){e<Q.NONE?e=Q.NONE:e>Q.ALL&&(e=Q.ALL),t=t||{};function r(n,s){var o=t[n];return typeof o=="function"&&e>=s?o.bind(t):function(){}}return{error:r("error",Q.ERROR),warn:r("warn",Q.WARN),info:r("info",Q.INFO),debug:r("debug",Q.DEBUG),verbose:r("verbose",Q.VERBOSE)}}var Fs=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){l={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Ls=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Vs="diag",vt=(function(){function e(){function t(s){return function(){for(var o=[],l=0;l<arguments.length;l++)o[l]=arguments[l];var i=Xe("diag");if(i)return i[s].apply(i,Ls([],Fs(o),!1))}}var r=this,n=function(s,o){var l,i,c;if(o===void 0&&(o={logLevel:Q.INFO}),s===r){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((l=u.stack)!==null&&l!==void 0?l:u.message),!1}typeof o=="number"&&(o={logLevel:o});var d=Xe("diag"),p=qs((i=o.logLevel)!==null&&i!==void 0?i:Q.INFO,s);if(d&&!o.suppressOverrideMessage){var h=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+h),p.warn("Current logger will overwrite one already registered from "+h)}return Er("diag",p,r,!0)};r.setLogger=n,r.disable=function(){Sr(Vs,r)},r.createComponentLogger=function(s){return new Us(s)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function Hs(e){return Symbol.for(e)}var Bs=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var o=new e(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=function(n){var s=new e(r._currentContext);return s._currentContext.delete(n),s}}return e})(),Zs=new Bs,Ks=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){l={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Gs=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Js=(function(){function e(){}return e.prototype.active=function(){return Zs},e.prototype.with=function(t,r,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return r.call.apply(r,Gs([n],Ks(s),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),zs=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),s,o=[],l;try{for(;(t===void 0||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){l={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(l)throw l.error}}return o},Ws=function(e,t,r){if(r||arguments.length===2)for(var n=0,s=t.length,o;n<s;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},Gt="context",Ys=new Js,ra=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Er(Gt,t,vt.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var s,o=[],l=3;l<arguments.length;l++)o[l-3]=arguments[l];return(s=this._getContextManager()).with.apply(s,Ws([t,r,n],zs(o),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return Xe(Gt)||Ys},e.prototype.disable=function(){this._getContextManager().disable(),Sr(Gt,vt.instance())},e})(),ur;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(ur||(ur={}));var na="0000000000000000",aa="00000000000000000000000000000000",Xs={traceId:aa,spanId:na,traceFlags:ur.NONE},Je=(function(){function e(t){t===void 0&&(t=Xs),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,r){},e})(),xr=Hs("OpenTelemetry Context Key SPAN");function Rr(e){return e.getValue(xr)||void 0}function Qs(){return Rr(ra.getInstance().active())}function Ar(e,t){return e.setValue(xr,t)}function ei(e){return e.deleteValue(xr)}function ti(e,t){return Ar(e,new Je(t))}function oa(e){var t;return(t=Rr(e))===null||t===void 0?void 0:t.spanContext()}var ri=/^([0-9a-f]{32})$/i,ni=/^[0-9a-f]{16}$/i;function ai(e){return ri.test(e)&&e!==aa}function oi(e){return ni.test(e)&&e!==na}function sa(e){return ai(e.traceId)&&oi(e.spanId)}function si(e){return new Je(e)}var Jt=ra.getInstance(),ia=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Jt.active());var s=!!r?.root;if(s)return new Je;var o=n&&oa(n);return ii(o)&&sa(o)?new Je(o):new Je},e.prototype.startActiveSpan=function(t,r,n,s){var o,l,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(o=r,i=n):(o=r,l=n,i=s);var c=l??Jt.active(),u=this.startSpan(t,o,c),d=Ar(c,u);return Jt.with(d,i,void 0,u)}},e})();function ii(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var li=new ia,ui=(function(){function e(t,r,n,s){this._provider=t,this.name=r,this.version=n,this.options=s}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):li},e})(),ci=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new ia},e})(),di=new ci,rn=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var s;return(s=this.getDelegateTracer(t,r,n))!==null&&s!==void 0?s:new ui(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:di},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(t,r,n)},e})(),yt;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(yt||(yt={}));var zt="trace",pi=(function(){function e(){this._proxyTracerProvider=new rn,this.wrapSpanContext=si,this.isSpanContextValid=sa,this.deleteSpan=ei,this.getSpan=Rr,this.getActiveSpan=Qs,this.getSpanContext=oa,this.setSpan=Ar,this.setSpanContext=ti}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Er(zt,this._proxyTracerProvider,vt.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return Xe(zt)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Sr(zt,vt.instance()),this._proxyTracerProvider=new rn},e})(),fi=pi.getInstance();let Cr;Cr=globalThis.crypto;async function mi(e){return(await Cr).getRandomValues(new Uint8Array(e))}async function hi(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const s=await mi(e-n.length);for(const o of s)o<r&&(n+=t[o%t.length])}return n}async function gi(e){return await hi(e)}async function vi(e){const t=await(await Cr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function yi(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await gi(e),r=await vi(t);return{code_verifier:t,code_challenge:r}}var _i="AI_MCPClientError",la=`vercel.ai.error.${_i}`,bi=Symbol.for(la),nn,an,j=class extends(an=a.AISDKError,nn=bi,an){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:s}){super({name:e,message:t,cause:r}),this[nn]=!0,this.data=n,this.code=s}static isInstance(e){return a.AISDKError.hasMarker(e,la)}},De="2025-06-18",wi=[De,"2025-03-26","2024-11-05"],Ti=a.looseObject({name:a.string(),version:a.string()}),kt=a.looseObject({_meta:a.optional(a.object({}).loose())}),be=kt,ua=a.object({method:a.string(),params:a.optional(kt)}),ca=a.object({applyDefaults:a.optional(a.boolean())}).loose(),Ii=a.looseObject({experimental:a.optional(a.object({}).loose()),logging:a.optional(a.object({}).loose()),prompts:a.optional(a.looseObject({listChanged:a.optional(a.boolean())})),resources:a.optional(a.looseObject({subscribe:a.optional(a.boolean()),listChanged:a.optional(a.boolean())})),tools:a.optional(a.looseObject({listChanged:a.optional(a.boolean())})),elicitation:a.optional(ca)});a.object({elicitation:a.optional(ca)}).loose();var Ei=be.extend({protocolVersion:a.string(),capabilities:Ii,serverInfo:Ti,instructions:a.optional(a.string())}),Pr=be.extend({nextCursor:a.optional(a.string())}),Si=a.object({name:a.string(),description:a.optional(a.string()),inputSchema:a.object({type:a.literal("object"),properties:a.optional(a.object({}).loose())}).loose()}).loose(),xi=Pr.extend({tools:a.array(Si)}),da=a.object({type:a.literal("text"),text:a.string()}).loose(),pa=a.object({type:a.literal("image"),data:a.base64(),mimeType:a.string()}).loose(),Ri=a.object({uri:a.string(),name:a.string(),title:a.optional(a.string()),description:a.optional(a.string()),mimeType:a.optional(a.string()),size:a.optional(a.number())}).loose(),Ai=Pr.extend({resources:a.array(Ri)}),fa=a.object({uri:a.string(),name:a.optional(a.string()),title:a.optional(a.string()),mimeType:a.optional(a.string())}).loose(),ma=fa.extend({text:a.string()}),ha=fa.extend({blob:a.base64()}),ga=a.object({type:a.literal("resource"),resource:a.union([ma,ha])}).loose(),Ci=be.extend({content:a.array(a.union([da,pa,ga])),isError:a.boolean().default(!1).optional()}).or(be.extend({toolResult:a.unknown()})),Pi=a.object({uriTemplate:a.string(),name:a.string(),title:a.optional(a.string()),description:a.optional(a.string()),mimeType:a.optional(a.string())}).loose(),ki=be.extend({resourceTemplates:a.array(Pi)}),Oi=be.extend({contents:a.array(a.union([ma,ha]))}),Mi=a.object({name:a.string(),description:a.optional(a.string()),required:a.optional(a.boolean())}).loose(),Ni=a.object({name:a.string(),title:a.optional(a.string()),description:a.optional(a.string()),arguments:a.optional(a.array(Mi))}).loose(),$i=Pr.extend({prompts:a.array(Ni)}),ji=a.object({role:a.union([a.literal("user"),a.literal("assistant")]),content:a.union([da,pa,ga])}).loose(),Di=be.extend({description:a.optional(a.string()),messages:a.array(ji)}),Ui=kt.extend({message:a.string(),requestedSchema:a.unknown()}),on=ua.extend({method:a.literal("elicitation/create"),params:Ui}),qi=be.extend({action:a.union([a.literal("accept"),a.literal("decline"),a.literal("cancel")]),content:a.optional(a.record(a.string(),a.unknown()))}),Ot="2.0",Fi=a.object({jsonrpc:a.literal(Ot),id:a.union([a.string(),a.number().int()])}).merge(ua).strict(),Li=a.object({jsonrpc:a.literal(Ot),id:a.union([a.string(),a.number().int()]),result:be}).strict(),Vi=a.object({jsonrpc:a.literal(Ot),id:a.union([a.string(),a.number().int()]),error:a.object({code:a.number().int(),message:a.string(),data:a.optional(a.unknown())})}).strict(),Hi=a.object({jsonrpc:a.literal(Ot)}).merge(a.object({method:a.string(),params:a.optional(kt)})).strict(),Ge=a.union([Fi,Hi,Li,Vi]),va=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",ya=a.object({access_token:a.string(),id_token:a.string().optional(),token_type:a.string(),expires_in:a.number().optional(),scope:a.string().optional(),refresh_token:a.string().optional()}).strip(),X=a.string().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:a.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),a.NEVER}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Bi=a.object({resource:a.string().url(),authorization_servers:a.array(X).optional(),jwks_uri:a.string().url().optional(),scopes_supported:a.array(a.string()).optional(),bearer_methods_supported:a.array(a.string()).optional(),resource_signing_alg_values_supported:a.array(a.string()).optional(),resource_name:a.string().optional(),resource_documentation:a.string().optional(),resource_policy_uri:a.string().url().optional(),resource_tos_uri:a.string().url().optional(),tls_client_certificate_bound_access_tokens:a.boolean().optional(),authorization_details_types_supported:a.array(a.string()).optional(),dpop_signing_alg_values_supported:a.array(a.string()).optional(),dpop_bound_access_tokens_required:a.boolean().optional()}).passthrough(),_a=a.object({issuer:a.string(),authorization_endpoint:X,token_endpoint:X,registration_endpoint:X.optional(),scopes_supported:a.array(a.string()).optional(),response_types_supported:a.array(a.string()),grant_types_supported:a.array(a.string()).optional(),code_challenge_methods_supported:a.array(a.string()),token_endpoint_auth_methods_supported:a.array(a.string()).optional(),token_endpoint_auth_signing_alg_values_supported:a.array(a.string()).optional()}).passthrough(),Zi=a.object({issuer:a.string(),authorization_endpoint:X,token_endpoint:X,userinfo_endpoint:X.optional(),jwks_uri:X,registration_endpoint:X.optional(),scopes_supported:a.array(a.string()).optional(),response_types_supported:a.array(a.string()),grant_types_supported:a.array(a.string()).optional(),subject_types_supported:a.array(a.string()),id_token_signing_alg_values_supported:a.array(a.string()),claims_supported:a.array(a.string()).optional(),token_endpoint_auth_methods_supported:a.array(a.string()).optional()}).passthrough(),Ki=Zi.merge(_a.pick({code_challenge_methods_supported:!0})),Gi=a.object({client_id:a.string(),client_secret:a.string().optional(),client_id_issued_at:a.number().optional(),client_secret_expires_at:a.number().optional()}).strip(),Ji=a.object({redirect_uris:a.array(X),token_endpoint_auth_method:a.string().optional(),grant_types:a.array(a.string()).optional(),response_types:a.array(a.string()).optional(),client_name:a.string().optional(),client_uri:X.optional(),logo_uri:X.optional(),scope:a.string().optional(),contacts:a.array(a.string()).optional(),tos_uri:X.optional(),policy_uri:a.string().optional(),jwks_uri:X.optional(),jwks:a.any().optional(),software_id:a.string().optional(),software_version:a.string().optional(),software_statement:a.string().optional()}).strip(),zi=a.object({error:a.string(),error_description:a.string().optional(),error_uri:a.string().optional()}),Wi=Ji.merge(Gi),Yi="AI_MCPClientOAuthError",ba=`vercel.ai.error.${Yi}`,Xi=Symbol.for(ba),sn,ln,st=class extends(ln=a.AISDKError,sn=Xi,ln){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[sn]=!0}static isInstance(e){return a.AISDKError.hasMarker(e,ba)}},je=class extends st{};je.errorCode="server_error";var _t=class extends st{};_t.errorCode="invalid_client";var bt=class extends st{};bt.errorCode="invalid_grant";var wt=class extends st{};wt.errorCode="unauthorized_client";var Qi={[je.errorCode]:je,[_t.errorCode]:_t,[bt.errorCode]:bt,[wt.errorCode]:wt};function el(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function tl({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}var Tt=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function It(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,s]=r.split(" ");if(n.toLowerCase()!=="bearer"||!s)return;const o=/resource_metadata="([^"]*)"/,l=r.match(o);if(l)try{return new URL(l[1])}catch{return}}function rl(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function kr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?kr(e,void 0,r):void 0;throw n}}async function un(e,t,r=fetch){return await kr(e,{"MCP-Protocol-Version":t},r)}function nl(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function al(e,t,r,n){var s,o;const l=new URL(e),i=(s=n?.protocolVersion)!=null?s:De;let c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{const d=rl(t,l.pathname);c=new URL(d,(o=n?.metadataServerUrl)!=null?o:l),c.search=l.search}let u=await un(c,i,r);if(!n?.metadataUrl&&nl(u,l.pathname)){const d=new URL(`/.well-known/${t}`,l);u=await un(d,i,r)}return u}async function ol(e,t,r=fetch){const n=await al(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Bi.parse(await n.json())}function sl(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function il(e,{fetchFn:t=fetch,protocolVersion:r=De}={}){var n;const s={"MCP-Protocol-Version":r},o=sl(e);for(const{url:l,type:i}of o){const c=await kr(l,s,t);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${l}`)}if(i==="oauth")return _a.parse(await c.json());{const u=Ki.parse(await c.json());if(!((n=u.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${l}: does not support S256 code challenge method required by MCP specification`);return u}}}}async function ll(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:l}){const i="code",c="S256";let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else u=new URL("/authorize",e);const d=await yi(),p=d.code_verifier,h=d.code_challenge;return u.searchParams.set("response_type",i),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",h),u.searchParams.set("code_challenge_method",c),u.searchParams.set("redirect_uri",String(n)),o&&u.searchParams.set("state",o),s&&u.searchParams.set("scope",s),s?.includes("offline_access")&&u.searchParams.append("prompt","consent"),l&&u.searchParams.set("resource",l.href),{authorizationUrl:u,codeVerifier:p}}function wa(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Ta(e,t,r,n){const{client_id:s,client_secret:o}=t;switch(e){case"client_secret_basic":ul(s,o,r);return;case"client_secret_post":cl(s,o,n);return;case"none":dl(s,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function ul(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function cl(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function dl(e,t){t.set("client_id",e)}async function Or(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=zi.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:l}=n,i=Qi[s]||je;return new i({message:o||"",cause:l})}catch(n){const s=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new je({message:s})}}async function pl(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:o,resource:l,addClientAuthentication:i,fetchFn:c}){var u;const d="authorization_code",p=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:d,code:n,code_verifier:s,redirect_uri:String(o)});if(i)i(h,f,e,t);else{const v=(u=t?.token_endpoint_auth_methods_supported)!=null?u:[],_=wa(r,v);Ta(_,r,h,f)}l&&f.set("resource",l.href);const m=await(c??fetch)(p,{method:"POST",headers:h,body:f});if(!m.ok)throw await Or(m);return ya.parse(await m.json())}async function fl(e,{metadata:t,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:l}){var i;const c="refresh_token";let u;if(t){if(u=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",e);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),p=new URLSearchParams({grant_type:c,refresh_token:n});if(o)o(d,p,e,t);else{const f=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],m=wa(r,f);Ta(m,r,d,p)}s&&p.set("resource",s.href);const h=await(l??fetch)(u,{method:"POST",headers:d,body:p});if(!h.ok)throw await Or(h);return ya.parse({refresh_token:n,...await h.json()})}async function ml(e,{metadata:t,clientMetadata:r,fetchFn:n}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await Or(o);return Wi.parse(await o.json())}async function Et(e,t){var r,n;try{return await Wt(e,t)}catch(s){if(s instanceof _t||s instanceof wt)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Wt(e,t);if(s instanceof bt)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Wt(e,t);throw s}}async function hl(e,t,r){const n=el(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!tl({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function Wt(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let l,i;try{l=await ol(t,{resourceMetadataUrl:s},o),l.authorization_servers&&l.authorization_servers.length>0&&(i=l.authorization_servers[0])}catch{}i||(i=t);const c=await hl(t,e,l),u=await il(i,{fetchFn:o});let d=await Promise.resolve(e.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const v=await ml(i,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(v),d=v}if(r!==void 0){const v=await e.codeVerifier(),_=await pl(i,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:v,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(_),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const v=await fl(i,{metadata:u,clientInformation:d,refreshToken:p.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof st)||v instanceof je))throw v}const h=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:m}=await ll(i,{metadata:u,clientInformation:d,state:h,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(f),"REDIRECT"}var gl=class{constructor({url:e,headers:t,authProvider:r}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":De};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return a.withUserAgentSuffix(t,`ai-sdk/${va}`,a.getRuntimeEnvironmentUserAgent())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var s,o,l,i,c;try{const u=await this.commonHeaders({Accept:"text/event-stream"}),d=await fetch(this.url.href,{headers:u,signal:(s=this.abortController)==null?void 0:s.signal});if(d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=It(d);try{if(await Et(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Tt;return(o=this.onerror)==null||o.call(this,v),t(v)}}catch(m){return(l=this.onerror)==null||l.call(this,m),t(m)}return r(!0)}if(!d.ok||!d.body){let m=`MCP SSE Transport Error: ${d.status} ${d.statusText}`;d.status===405&&(m+=". This server does not support SSE transport. Try using `http` transport instead");const v=new j({message:m});return(i=this.onerror)==null||i.call(this,v),t(v)}const h=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new a.EventSourceParserStream).getReader(),f=async()=>{var m,v,_;try{for(;;){const{done:y,value:w}=await h.read();if(y){if(this.connected)throw this.connected=!1,new j({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:b,data:g}=w;if(b==="endpoint"){if(this.endpoint=new URL(g,this.url),this.endpoint.origin!==this.url.origin)throw new j({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(b==="message")try{const E=Ge.parse(JSON.parse(g));(m=this.onmessage)==null||m.call(this,E)}catch(E){const S=new j({message:"MCP SSE Transport Error: Failed to parse message",cause:E});(v=this.onerror)==null||v.call(this,S)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(_=this.onerror)==null||_.call(this,y),t(y)}};this.sseConnection={close:()=>h.cancel()},f()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(c=this.onerror)==null||c.call(this,u),t(u)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new j({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var s,o,l,i,c;try{const d={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(s=this.abortController)==null?void 0:s.signal},p=await fetch(t,d);if(p.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=It(p);try{if(await Et(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new Tt;(o=this.onerror)==null||o.call(this,f);return}}catch(h){(l=this.onerror)==null||l.call(this,h);return}return r(!0)}if(!p.ok){const h=await p.text().catch(()=>null),f=new j({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${p.status}): ${h}`});(i=this.onerror)==null||i.call(this,f);return}}catch(u){(c=this.onerror)==null||c.call(this,u);return}};await r()}},vl=class{constructor({url:e,headers:t,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":De};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return a.withUserAgentSuffix(t,`ai-sdk/${va}`,a.getRuntimeEnvironmentUserAgent())}async start(){if(this.abortController)throw new j({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,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,s,o,l,i,c,u;try{const p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},h=await fetch(this.url,p),f=h.headers.get("mcp-session-id");if(f&&(this.sessionId=f),h.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=It(h);try{if(await Et(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Tt}catch(_){throw(s=this.onerror)==null||s.call(this,_),_}return t(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const _=await h.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${_}`;h.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const w=new j({message:y});throw(o=this.onerror)==null||o.call(this,w),w}const m=h.headers.get("content-type")||"";if(m.includes("application/json")){const _=await h.json(),y=Array.isArray(_)?_.map(w=>Ge.parse(w)):[Ge.parse(_)];for(const w of y)(l=this.onmessage)==null||l.call(this,w);return}if(m.includes("text/event-stream")){if(!h.body){const b=new j({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,b),b}const y=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new a.EventSourceParserStream).getReader();(async()=>{var b,g,E;try{for(;;){const{done:S,value:I}=await y.read();if(S)return;const{event:x,data:P}=I;if(x==="message")try{const F=Ge.parse(JSON.parse(P));(b=this.onmessage)==null||b.call(this,F)}catch(F){const K=new j({message:"MCP HTTP Transport Error: Failed to parse message",cause:F});(g=this.onerror)==null||g.call(this,K)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(E=this.onerror)==null||E.call(this,S)}})();return}const v=new j({message:`MCP HTTP Transport Error: Unexpected content type: ${m}`});throw(c=this.onerror)==null||c.call(this,v),v}catch(d){throw(u=this.onerror)==null||u.call(this,d),d}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new j({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,s,o,l,i;try{const c=await this.commonHeaders({Accept:"text/event-stream"});t&&(c["last-event-id"]=t);const u=await fetch(this.url.href,{method:"GET",headers:c,signal:(r=this.abortController)==null?void 0:r.signal}),d=u.headers.get("mcp-session-id");if(d&&(this.sessionId=d),u.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=It(u);try{if(await Et(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Tt;(n=this.onerror)==null||n.call(this,v);return}}catch(m){(s=this.onerror)==null||s.call(this,m);return}return this.openInboundSse(!0,t)}if(u.status===405)return;if(!u.ok||!u.body){const m=new j({message:`MCP HTTP Transport Error: GET SSE failed: ${u.status} ${u.statusText}`});(o=this.onerror)==null||o.call(this,m);return}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new a.EventSourceParserStream).getReader(),f=async()=>{var m,v,_,y;try{for(;;){const{done:w,value:b}=await h.read();if(w)return;const{event:g,data:E,id:S}=b;if(S&&(this.lastInboundEventId=S),g==="message")try{const I=Ge.parse(JSON.parse(E));(m=this.onmessage)==null||m.call(this,I)}catch(I){const x=new j({message:"MCP HTTP Transport Error: Failed to parse message",cause:I});(v=this.onerror)==null||v.call(this,x)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(_=this.onerror)==null||_.call(this,w),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,f()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function yl(e){switch(e.type){case"sse":return new gl(e);case"http":return new vl(e);default:throw new j({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function _l(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var bl="1.0.0";async function wl(e){const t=new Tl(e);return await t.init(),t}var Tl=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=bl,onUncaughtError:n,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=s??{},_l(e)?this.transport=e:this.transport=yl(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new j({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:De,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Ei});if(e===void 0)throw new j({message:"Server sent invalid initialize result"});if(!wi.includes(e.protocolVersion))throw new j({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new j({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new j({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new j({message:"Server does not support prompts"});break;default:throw new j({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,s)=>{if(this.isClosed)return s(new j({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const o=r?.signal;o?.throwIfAborted();const l=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:l},c=()=>{this.responseHandlers.delete(l)};this.responseHandlers.set(l,u=>{if(o?.aborted)return s(new j({message:"Request was aborted",cause:o.reason}));if(u instanceof Error)return s(u);try{const d=t.parse(u.result);n(d)}catch(d){const p=new j({message:"Failed to parse server response",cause:d});s(p)}}),this.transport.send(i).catch(u=>{c(),s(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:xi,options:t})}catch(r){throw r}}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:Ci,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:Ai,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:Oi,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:ki,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:$i,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:Di,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const r={};try{const n=await this.listTools();for(const{name:s,description:o,inputSchema:l}of n.tools){if(e!=="automatic"&&!(s in e))continue;const i=this,c=async(d,p)=>{var h;return(h=p?.abortSignal)==null||h.throwIfAborted(),i.callTool({name:s,args:d,options:p})},u=e==="automatic"?a.dynamicTool({description:o,inputSchema:a.jsonSchema({...l,properties:(t=l.properties)!=null?t:{},additionalProperties:!1}),execute:c}):a.tool({description:o,inputSchema:e[s].inputSchema,execute:c});r[s]=u}return r}catch(n){throw n}}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})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==on)throw new j({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{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}const t=on.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{const r=await this.elicitationRequestHandler(t.data),n=qi.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new j({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new j({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new j({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Il=Object.defineProperty,El=Object.defineProperties,Sl=Object.getOwnPropertyDescriptors,cn=Object.getOwnPropertySymbols,xl=Object.prototype.hasOwnProperty,Rl=Object.prototype.propertyIsEnumerable,dn=(e,t,r)=>t in e?Il(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,D=(e,t)=>{for(var r in t||(t={}))xl.call(t,r)&&dn(e,r,t[r]);if(cn)for(var r of cn(t))Rl.call(t,r)&&dn(e,r,t[r]);return e},St=(e,t)=>El(e,Sl(t)),Ia="vercel.ai.error",Al=Symbol.for(Ia),Ea,Cl=class Sa extends Error{constructor({name:t,message:r,cause:n}){super(r),this[Ea]=!0,this.name=t,this.cause=n}static isInstance(t){return Sa.hasMarker(t,Ia)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};Ea=Al;var B=Cl,xa="AI_APICallError",Ra=`vercel.ai.error.${xa}`,Pl=Symbol.for(Ra),Aa,ce=class extends B{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:o,cause:l,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:c}){super({name:xa,message:e,cause:l}),this[Aa]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=o,this.isRetryable=i,this.data=c}static isInstance(e){return B.hasMarker(e,Ra)}};Aa=Pl;var Ca="AI_EmptyResponseBodyError",Pa=`vercel.ai.error.${Ca}`,kl=Symbol.for(Pa),ka,Ol=class extends B{constructor({message:e="Empty response body"}={}){super({name:Ca,message:e}),this[ka]=!0}static isInstance(e){return B.hasMarker(e,Pa)}};ka=kl;function Oa(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Ma="AI_InvalidArgumentError",Na=`vercel.ai.error.${Ma}`,Ml=Symbol.for(Na),$a,ja=class extends B{constructor({message:t,cause:r,argument:n}){super({name:Ma,message:t,cause:r}),this[$a]=!0,this.argument=n}static isInstance(t){return B.hasMarker(t,Na)}};$a=Ml;var Da="AI_InvalidPromptError",Ua=`vercel.ai.error.${Da}`,Nl=Symbol.for(Ua),qa,$l=class extends B{constructor({prompt:e,message:t,cause:r}){super({name:Da,message:`Invalid prompt: ${t}`,cause:r}),this[qa]=!0,this.prompt=e}static isInstance(e){return B.hasMarker(e,Ua)}};qa=Nl;var Fa="AI_InvalidResponseDataError",La=`vercel.ai.error.${Fa}`,jl=Symbol.for(La),Va,Ze=class extends B{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Fa,message:t}),this[Va]=!0,this.data=e}static isInstance(e){return B.hasMarker(e,La)}};Va=jl;var Ha="AI_JSONParseError",Ba=`vercel.ai.error.${Ha}`,Dl=Symbol.for(Ba),Za,xt=class extends B{constructor({text:e,cause:t}){super({name:Ha,message:`JSON parsing failed: Text: ${e}.
|
|
2
2
|
Error message: ${Oa(t)}`,cause:t}),this[Za]=!0,this.text=e}static isInstance(e){return B.hasMarker(e,Ba)}};Za=Dl;var Ka="AI_LoadAPIKeyError",Ga=`vercel.ai.error.${Ka}`,Ul=Symbol.for(Ga),Ja,dt=class extends B{constructor({message:e}){super({name:Ka,message:e}),this[Ja]=!0}static isInstance(e){return B.hasMarker(e,Ga)}};Ja=Ul;var za="AI_NoContentGeneratedError",Wa=`vercel.ai.error.${za}`,ql=Symbol.for(Wa),Ya,Xa=class extends B{constructor({message:e="No content generated."}={}){super({name:za,message:e}),this[Ya]=!0}static isInstance(e){return B.hasMarker(e,Wa)}};Ya=ql;var Qa="AI_TypeValidationError",eo=`vercel.ai.error.${Qa}`,Fl=Symbol.for(eo),to,Ll=class cr extends B{constructor({value:t,cause:r}){super({name:Qa,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
3
3
|
Error message: ${Oa(r)}`,cause:r}),this[to]=!0,this.value=t}static isInstance(t){return B.hasMarker(t,eo)}static wrap({value:t,cause:r}){return cr.isInstance(r)&&r.value===t?r:new cr({value:t,cause:r})}};to=Fl;var Qe=Ll,ro="AI_UnsupportedFunctionalityError",no=`vercel.ai.error.${ro}`,Vl=Symbol.for(no),ao,Ie=class extends B{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:ro,message:t}),this[ao]=!0,this.functionality=e}static isInstance(e){return B.hasMarker(e,no)}};ao=Vl;var pn=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Yt(e){}function Hl(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Yt,onError:r=Yt,onRetry:n=Yt,onComment:s}=e;let o="",l=!0,i,c="",u="";function d(v){const _=l?v.replace(/^\xEF\xBB\xBF/,""):v,[y,w]=Bl(`${o}${_}`);for(const b of y)p(b);o=w,l=!1}function p(v){if(v===""){f();return}if(v.startsWith(":")){s&&s(v.slice(v.startsWith(": ")?2:1));return}const _=v.indexOf(":");if(_!==-1){const y=v.slice(0,_),w=v[_+1]===" "?2:1,b=v.slice(_+w);h(y,b,v);return}h(v,"",v)}function h(v,_,y){switch(v){case"event":u=_;break;case"data":c=`${c}${_}
|
|
4
4
|
`;break;case"id":i=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new pn(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:y}));break;default:r(new pn(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:_,line:y}));break}}function f(){c.length>0&&t({id:i,event:u||void 0,data:c.endsWith(`
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { fe as ze, gl as ri, gm as ai, gn as ni, fr as v, gj as J, fs as $, fM as c, ev as I, ez as _e, fZ as D, f_ as Re, fd as C, fB as De, g9 as In, ga as Sn, go as Mt, ew as En, fq as R, eu as Oe, dR as oi, aQ as si, eS as Kt, gp as ii, gq as dt, gr as Nt, gs as se, gt as li, fI as ui, dc as ci, gu as M, gv as di, gw as Yt, f0 as $t, eH as pi, fc as fi, fn as hi, eM as mi, gx as Ze, gk as gi } from "./
|
|
1
|
+
import { fe as ze, gl as ri, gm as ai, gn as ni, fr as v, gj as J, fs as $, fM as c, ev as I, ez as _e, fZ as D, f_ as Re, fd as C, fB as De, g9 as In, ga as Sn, go as Mt, ew as En, fq as R, eu as Oe, dR as oi, aQ as si, eS as Kt, gp as ii, gq as dt, gr as Nt, gs as se, gt as li, fI as ui, dc as ci, gu as M, gv as di, gw as Yt, f0 as $t, eH as pi, fc as fi, fn as hi, eM as mi, gx as Ze, gk as gi } from "./index-DxNldiiY.js";
|
|
2
2
|
var vi = typeof globalThis == "object" ? globalThis : typeof self == "object" ? self : typeof window == "object" ? window : typeof global == "object" ? global : {}, qe = "1.9.0", Ta = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
|
|
3
3
|
function yi(e) {
|
|
4
4
|
var t = /* @__PURE__ */ new Set([e]), r = /* @__PURE__ */ new Set(), a = e.match(Ta);
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@gram-ai/elements",
|
|
3
3
|
"description": "Gram Elements is a library of UI primitives for building chat-like experiences for MCP Servers.",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"version": "1.
|
|
5
|
+
"version": "1.6.0",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": {
|
|
@@ -92,6 +92,7 @@
|
|
|
92
92
|
"assistant-stream": "^0.2.42",
|
|
93
93
|
"class-variance-authority": "^0.7.1",
|
|
94
94
|
"clsx": "^2.1.1",
|
|
95
|
+
"d3": "^7.9.0",
|
|
95
96
|
"lucide-react": "^0.544.0",
|
|
96
97
|
"tailwind-merge": "^3.3.1",
|
|
97
98
|
"tw-shimmer": "^0.4.0",
|