eve 0.24.0 → 0.24.2

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.
Files changed (136) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/src/cli/run.js +2 -2
  3. package/dist/src/cli/vercel-service-output.d.ts +4 -0
  4. package/dist/src/cli/vercel-service-output.js +1 -0
  5. package/dist/src/compiled/.vendor-stamp.json +11 -11
  6. package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +1 -1
  7. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  8. package/dist/src/compiled/@ai-sdk/google/index.d.ts +7 -0
  9. package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
  10. package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +42 -1
  11. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  12. package/dist/src/compiled/@ai-sdk/openai/index.d.ts +34 -6
  13. package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
  14. package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
  15. package/dist/src/compiled/@ai-sdk/provider/index.d.ts +245 -3
  16. package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +273 -15
  17. package/dist/src/compiled/@workflow/core/index.js +1 -1
  18. package/dist/src/compiled/@workflow/core/runtime/start.d.ts +12 -0
  19. package/dist/src/compiled/@workflow/core/runtime.js +1 -1
  20. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  21. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  22. package/dist/src/compiled/@workflow/world/analytics.d.ts +56 -21
  23. package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
  24. package/dist/src/compiled/@workflow/world/interfaces.d.ts +46 -0
  25. package/dist/src/compiled/@workflow/world/queue.d.ts +12 -0
  26. package/dist/src/compiled/@workflow/world-local/index.js +3 -3
  27. package/dist/src/compiled/@workflow/world-vercel/index.js +16 -16
  28. package/dist/src/compiled/_chunks/workflow/attribute-changes-MGTOG_uX.js +20 -0
  29. package/dist/src/compiled/_chunks/workflow/{dist-CQenixFf.js → dist-Blxnyb7-.js} +2 -2
  30. package/dist/src/compiled/_chunks/workflow/dist-zLevmMyU.js +77 -0
  31. package/dist/src/compiled/_chunks/workflow/{resume-hook-BH01MfRF.js → resume-hook-DHP5ql3-.js} +1 -1
  32. package/dist/src/compiled/_chunks/workflow/run-D8hv1ptT.js +1 -0
  33. package/dist/src/compiled/_chunks/workflow/{sleep-BkAHCD_s.js → sleep-uA9pS-PT.js} +1 -1
  34. package/dist/src/compiler/artifacts.d.ts +7 -6
  35. package/dist/src/compiler/artifacts.js +1 -1
  36. package/dist/src/compiler/compile-agent.d.ts +15 -2
  37. package/dist/src/compiler/compile-agent.js +3 -3
  38. package/dist/src/execution/sandbox/prewarm.d.ts +1 -0
  39. package/dist/src/execution/sandbox/prewarm.js +1 -1
  40. package/dist/src/harness/compaction-prompt.d.ts +16 -0
  41. package/dist/src/harness/compaction-prompt.js +24 -0
  42. package/dist/src/harness/compaction.d.ts +2 -1
  43. package/dist/src/harness/compaction.js +1 -4
  44. package/dist/src/harness/input-requests.d.ts +1 -0
  45. package/dist/src/harness/input-requests.js +1 -1
  46. package/dist/src/harness/instrumentation-runtime-context.d.ts +1 -1
  47. package/dist/src/harness/tool-loop.js +3 -1
  48. package/dist/src/internal/application/build-workspace.d.ts +36 -0
  49. package/dist/src/internal/application/build-workspace.js +1 -0
  50. package/dist/src/internal/application/compiled-artifacts.d.ts +5 -0
  51. package/dist/src/internal/application/compiled-artifacts.js +4 -3
  52. package/dist/src/internal/application/output-publication-artifacts.d.ts +7 -0
  53. package/dist/src/internal/application/output-publication-artifacts.js +1 -0
  54. package/dist/src/internal/application/output-publication-journal.d.ts +30 -0
  55. package/dist/src/internal/application/output-publication-journal.js +1 -0
  56. package/dist/src/internal/application/output-publication-lock.d.ts +10 -0
  57. package/dist/src/internal/application/output-publication-lock.js +1 -0
  58. package/dist/src/internal/application/output-publication.d.ts +33 -0
  59. package/dist/src/internal/application/output-publication.js +1 -0
  60. package/dist/src/internal/application/package.js +1 -1
  61. package/dist/src/internal/application/paths.d.ts +2 -0
  62. package/dist/src/internal/application/paths.js +1 -1
  63. package/dist/src/internal/application/production-compiler-artifacts.d.ts +4 -0
  64. package/dist/src/internal/application/production-compiler-artifacts.js +1 -0
  65. package/dist/src/internal/application/tsconfig-dependencies.js +1 -1
  66. package/dist/src/internal/authored-directive-prologue.d.ts +4 -0
  67. package/dist/src/internal/authored-directive-prologue.js +1 -0
  68. package/dist/src/internal/authored-module-loader.d.ts +15 -5
  69. package/dist/src/internal/authored-module-loader.js +4 -2
  70. package/dist/src/internal/authored-module-map-loader.js +1 -1
  71. package/dist/src/internal/authored-package-boundary.d.ts +25 -0
  72. package/dist/src/internal/authored-package-boundary.js +1 -0
  73. package/dist/src/internal/authored-package-tsconfig-paths.js +1 -1
  74. package/dist/src/internal/bundler/nitro-node-file-trace.d.ts +10 -0
  75. package/dist/src/internal/bundler/nitro-node-file-trace.js +1 -0
  76. package/dist/src/internal/materialize-authored-external-dependencies.d.ts +10 -0
  77. package/dist/src/internal/materialize-authored-external-dependencies.js +2 -0
  78. package/dist/src/internal/materialized-authored-modules.d.ts +15 -0
  79. package/dist/src/internal/materialized-authored-modules.js +1 -0
  80. package/dist/src/internal/nitro/dev-runtime-artifacts.d.ts +1 -9
  81. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  82. package/dist/src/internal/nitro/development-generation.d.ts +12 -0
  83. package/dist/src/internal/nitro/development-generation.js +1 -0
  84. package/dist/src/internal/nitro/host/artifacts-config.d.ts +9 -11
  85. package/dist/src/internal/nitro/host/artifacts-config.js +1 -1
  86. package/dist/src/internal/nitro/host/build-application.js +1 -1
  87. package/dist/src/internal/nitro/host/build-vercel-agent-summary.d.ts +1 -7
  88. package/dist/src/internal/nitro/host/build-vercel-agent-summary.js +1 -1
  89. package/dist/src/internal/nitro/host/channel-routes.d.ts +3 -3
  90. package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +9 -5
  91. package/dist/src/internal/nitro/host/configure-nitro-routes.js +3 -3
  92. package/dist/src/internal/nitro/host/copy-host-middleware.d.ts +12 -0
  93. package/dist/src/internal/nitro/host/copy-host-middleware.js +1 -0
  94. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +18 -10
  95. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  96. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  97. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.d.ts +2 -2
  98. package/dist/src/internal/nitro/host/dispatch-schedule-in-dev.js +1 -1
  99. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +13 -5
  100. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  101. package/dist/src/internal/nitro/host/schedule-task-routes.d.ts +3 -3
  102. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  103. package/dist/src/internal/nitro/host/types.d.ts +4 -0
  104. package/dist/src/internal/nitro/routes/agent-info/load-agent-info-data.d.ts +3 -6
  105. package/dist/src/internal/nitro/routes/agent-info/load-agent-info-data.js +1 -1
  106. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  107. package/dist/src/internal/nitro/routes/dev-schedule-dispatch.d.ts +2 -2
  108. package/dist/src/internal/nitro/routes/info.d.ts +1 -6
  109. package/dist/src/internal/nitro/routes/info.js +1 -1
  110. package/dist/src/internal/nitro/routes/runtime-artifacts.d.ts +9 -5
  111. package/dist/src/internal/nitro/routes/runtime-artifacts.js +1 -1
  112. package/dist/src/internal/workflow-bundle/build-queue.d.ts +1 -0
  113. package/dist/src/internal/workflow-bundle/build-queue.js +1 -0
  114. package/dist/src/internal/workflow-bundle/builder-support.d.ts +0 -1
  115. package/dist/src/internal/workflow-bundle/builder-support.js +2 -2
  116. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  117. package/dist/src/internal/workflow-bundle/nitro-step-entry.d.ts +1 -0
  118. package/dist/src/internal/workflow-bundle/nitro-step-entry.js +2 -2
  119. package/dist/src/public/instrumentation/index.d.ts +3 -3
  120. package/dist/src/public/next/vercel-output-config.js +1 -1
  121. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  122. package/dist/src/setup/scaffold/create/project.js +2 -2
  123. package/dist/src/setup/scaffold/update/channels.js +1 -1
  124. package/dist/src/shared/atomic-write-file.d.ts +11 -0
  125. package/dist/src/shared/atomic-write-file.js +1 -0
  126. package/dist/src/shared/guards.d.ts +7 -0
  127. package/dist/src/shared/guards.js +1 -1
  128. package/dist/src/shared/path-exists.d.ts +9 -0
  129. package/dist/src/shared/path-exists.js +1 -0
  130. package/docs/agent-config.md +1 -1
  131. package/docs/concepts/default-harness.md +1 -1
  132. package/docs/reference/cli.md +4 -2
  133. package/package.json +14 -14
  134. package/dist/src/compiled/_chunks/workflow/attribute-changes-Dmf_myUv.js +0 -20
  135. package/dist/src/compiled/_chunks/workflow/dist-D7CzPkf8.js +0 -77
  136. package/dist/src/compiled/_chunks/workflow/run-CL3mguvM.js +0 -1
@@ -66,6 +66,7 @@ declare const JSONRPCMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
66
66
  }, z.core.$strip>;
67
67
  }, z.core.$strict>]>;
68
68
  type JSONRPCMessage = z.infer<typeof JSONRPCMessageSchema>;
69
+ declare function validateJSONRPCMessage(message: unknown): JSONRPCMessage;
69
70
 
70
71
  /**
71
72
  * OAuth 2.1 token response
@@ -374,6 +375,7 @@ declare const InitializeResultSchema: z.ZodObject<{
374
375
  capabilities: z.ZodObject<{
375
376
  experimental: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
376
377
  logging: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
378
+ completions: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
377
379
  prompts: z.ZodOptional<z.ZodObject<{
378
380
  listChanged: z.ZodOptional<z.ZodBoolean>;
379
381
  }, z.core.$loose>>;
@@ -499,6 +501,33 @@ declare const ReadResourceResultSchema: z.ZodObject<{
499
501
  }, z.core.$loose>]>>;
500
502
  }, z.core.$loose>;
501
503
  type ReadResourceResult = z.infer<typeof ReadResourceResultSchema>;
504
+ declare const CompleteRequestParamsSchema: z.ZodObject<{
505
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
506
+ ref: z.ZodUnion<readonly [z.ZodObject<{
507
+ type: z.ZodLiteral<"ref/prompt">;
508
+ name: z.ZodString;
509
+ }, z.core.$loose>, z.ZodObject<{
510
+ type: z.ZodLiteral<"ref/resource">;
511
+ uri: z.ZodString;
512
+ }, z.core.$loose>]>;
513
+ argument: z.ZodObject<{
514
+ name: z.ZodString;
515
+ value: z.ZodString;
516
+ }, z.core.$loose>;
517
+ context: z.ZodOptional<z.ZodObject<{
518
+ arguments: z.ZodRecord<z.ZodString, z.ZodString>;
519
+ }, z.core.$loose>>;
520
+ }, z.core.$loose>;
521
+ type CompleteRequestParams = z.infer<typeof CompleteRequestParamsSchema>;
522
+ declare const CompleteResultSchema: z.ZodObject<{
523
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
524
+ completion: z.ZodObject<{
525
+ values: z.ZodArray<z.ZodString>;
526
+ total: z.ZodOptional<z.ZodNumber>;
527
+ hasMore: z.ZodOptional<z.ZodBoolean>;
528
+ }, z.core.$loose>;
529
+ }, z.core.$loose>;
530
+ type CompleteResult = z.infer<typeof CompleteResultSchema>;
502
531
  declare const ListPromptsResultSchema: z.ZodObject<{
503
532
  _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
504
533
  nextCursor: z.ZodOptional<z.ZodString>;
@@ -572,6 +601,15 @@ interface MCPClientConfig {
572
601
  transport: MCPTransportConfig | MCPTransport;
573
602
  /** Optional callback for uncaught errors */
574
603
  onUncaughtError?: (error: unknown) => void;
604
+ /**
605
+ * Maximum number of retries for transient MCP tool call failures.
606
+ *
607
+ * Set to 0 to disable retries. Retries only apply to tools/call requests.
608
+ * JSON-RPC application errors, such as invalid params, are not retried.
609
+ *
610
+ * @default 0
611
+ */
612
+ maxRetries?: number;
575
613
  /**
576
614
  * Initialize result from a previous MCP session. When provided, the client
577
615
  * starts the transport and reuses this metadata without sending a new
@@ -660,6 +698,9 @@ interface MCPClient {
660
698
  arguments?: Record<string, unknown>;
661
699
  options?: RequestOptions;
662
700
  }): Promise<GetPromptResult>;
701
+ complete(args: CompleteRequestParams & {
702
+ options?: RequestOptions;
703
+ }): Promise<CompleteResult>;
663
704
  onElicitationRequest(schema: typeof ElicitationRequestSchema, handler: (request: ElicitationRequest) => Promise<ElicitResult> | ElicitResult): void;
664
705
  close: () => Promise<void>;
665
706
  }
@@ -721,4 +762,4 @@ declare function readMCPAppResource({ client, uri, options, }: {
721
762
  options?: RequestOptions;
722
763
  }): Promise<MCPAppResource>;
723
764
 
724
- export { type CallToolResult, type Configuration, type ElicitResult, ElicitResultSchema, type ElicitationRequest, ElicitationRequestSchema, type InitializeResult, type JSONRPCError, type JSONRPCMessage, type JSONRPCNotification, type JSONRPCRequest, type JSONRPCResponse, type ListToolsResult, type MCPAppResource, type MCPAppResourceCSP, type MCPAppResourceMeta, type MCPClient, type ClientCapabilities as MCPClientCapabilities, type MCPClientConfig, type MCPTransport, MCP_APP_MIME_TYPE, type McpProviderMetadata, type OAuthAuthorizationServerInformation, type OAuthClientInformation, type OAuthClientMetadata, type OAuthClientProvider, type OAuthTokens, UnauthorizedError, auth, createMCPClient, type MCPClient as experimental_MCPClient, type ClientCapabilities as experimental_MCPClientCapabilities, type MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, mcpAppClientCapabilities, readMCPAppResource, splitMCPAppTools };
765
+ export { type CallToolResult, type CompleteRequestParams, type CompleteResult, type Configuration, type ElicitResult, ElicitResultSchema, type ElicitationRequest, ElicitationRequestSchema, type InitializeResult, type JSONRPCError, type JSONRPCMessage, type JSONRPCNotification, type JSONRPCRequest, type JSONRPCResponse, type ListToolsResult, type MCPAppResource, type MCPAppResourceCSP, type MCPAppResourceMeta, type MCPClient, type ClientCapabilities as MCPClientCapabilities, type MCPClientConfig, type MCPTransport, MCP_APP_MIME_TYPE, type McpProviderMetadata, type OAuthAuthorizationServerInformation, type OAuthClientInformation, type OAuthClientMetadata, type OAuthClientProvider, type OAuthTokens, UnauthorizedError, auth, createMCPClient, type MCPClient as experimental_MCPClient, type ClientCapabilities as experimental_MCPClientCapabilities, type MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, mcpAppClientCapabilities, readMCPAppResource, splitMCPAppTools, validateJSONRPCMessage };
@@ -1 +1 @@
1
- import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{$ as n,I as r,J as i,K as a,S as o,U as s,W as c,_t as l,at as u,bt as d,dt as f,ft as p,ht as m,i as ee,it as h,k as te,lt as g,mt as ne,n as re,ot as _,pt as v,rt as ie,ut as y,vt as b,y as ae}from"../../_chunks/workflow/dist-D7CzPkf8.js";const oe={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var se;se||={};let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ce(e){return(await x).getRandomValues(new Uint8Array(e))}async function le(e){let t=``;for(;t.length<e;){let n=await ce(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ue(e){return await le(e)}async function de(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function fe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ue(e);return{code_verifier:t,code_challenge:await de(t)}}var pe=`vercel.ai.error.AI_MCPClientError`,me=Symbol.for(pe),he,ge,S=class extends (ge=e,he=me,ge){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[he]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,pe)}},C=`2025-11-25`,_e=[C,`2025-06-18`,`2025-03-26`,`2024-11-05`],ve=v(ne(m(),b())),ye=y({name:m(),version:m(),title:v(m())}),w=y({_meta:v(p({}).loose())}),T=w,be=p({method:m(),params:v(w)}),xe=p({applyDefaults:v(_())}).loose(),Se=y({experimental:v(p({}).loose()),logging:v(p({}).loose()),prompts:v(y({listChanged:v(_())})),resources:v(y({subscribe:v(_()),listChanged:v(_())})),tools:v(y({listChanged:v(_())})),elicitation:v(xe)});p({elicitation:v(xe)}).loose();var E=T.extend({protocolVersion:m(),capabilities:Se,serverInfo:ye,instructions:v(m())}),D=T.extend({nextCursor:v(m())}),Ce=p({name:m(),title:v(m()),description:v(m()),inputSchema:p({type:g(`object`),properties:v(p({}).loose())}).loose(),outputSchema:v(p({}).loose()),annotations:v(p({title:v(m())}).loose()),_meta:ve}).loose(),we=D.extend({tools:h(Ce)}),O=p({type:g(`text`),text:m()}).loose(),k=p({type:g(`image`),data:u(),mimeType:m()}).loose(),Te=p({uri:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m()),size:v(f())}).loose(),Ee=D.extend({resources:h(Te)}),A=p({uri:m(),name:v(m()),title:v(m()),mimeType:v(m())}).loose(),j=A.extend({text:m()}),M=A.extend({blob:u()}),De=p({type:g(`resource`),resource:l([j,M])}).loose(),Oe=p({type:g(`resource_link`),uri:m(),name:m(),description:v(m()),mimeType:v(m())}).loose(),ke=T.extend({content:h(l([O,k,De,Oe])),structuredContent:v(b()),isError:_().default(!1).optional()}).or(T.extend({toolResult:b()})),Ae=p({uriTemplate:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m())}).loose(),je=T.extend({resourceTemplates:h(Ae)}),Me=T.extend({contents:h(l([j,M]))}),Ne=p({name:m(),description:v(m()),required:v(_())}).loose(),Pe=p({name:m(),title:v(m()),description:v(m()),arguments:v(h(Ne))}).loose(),Fe=D.extend({prompts:h(Pe)}),Ie=p({role:l([g(`user`),g(`assistant`)]),content:l([O,k,De,Oe])}).loose(),Le=T.extend({description:v(m()),messages:h(Ie)}),Re=w.extend({message:m(),requestedSchema:b()}),N=be.extend({method:g(`elicitation/create`),params:Re}),ze=T.extend({action:l([g(`accept`),g(`decline`),g(`cancel`)]),content:v(ne(m(),b()))}),P=`2.0`,Be=p({jsonrpc:g(P),id:l([m(),f().int()])}).merge(be).strict(),Ve=p({jsonrpc:g(P),id:l([m(),f().int()]),result:T}).strict(),He=p({jsonrpc:g(P),id:l([m(),f().int()]),error:p({code:f().int(),message:m(),data:v(b())})}).strict(),F=l([Be,p({jsonrpc:g(P)}).merge(p({method:m(),params:v(w)})).strict(),Ve,He]);async function I(e){return F.parse(await r({text:e}))}var Ue=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,L=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:oe.custom,message:`URL must be parseable`,fatal:!0}),d}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),We=p({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Ge=p({resource:m().url(),authorization_servers:h(L).optional(),jwks_uri:m().url().optional(),scopes_supported:h(m()).optional(),bearer_methods_supported:h(m()).optional(),resource_signing_alg_values_supported:h(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:_().optional(),authorization_details_types_supported:h(m()).optional(),dpop_signing_alg_values_supported:h(m()).optional(),dpop_bound_access_tokens_required:_().optional()}).passthrough(),R=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),code_challenge_methods_supported:h(m()),token_endpoint_auth_methods_supported:h(m()).optional(),token_endpoint_auth_signing_alg_values_supported:h(m()).optional()}).passthrough(),Ke=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,userinfo_endpoint:L.optional(),jwks_uri:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),subject_types_supported:h(m()),id_token_signing_alg_values_supported:h(m()),claims_supported:h(m()).optional(),token_endpoint_auth_methods_supported:h(m()).optional()}).passthrough().merge(R.pick({code_challenge_methods_supported:!0})),qe=p({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Je=p({redirect_uris:h(L),token_endpoint_auth_method:m().optional(),grant_types:h(m()).optional(),response_types:h(m()).optional(),client_name:m().optional(),client_uri:L.optional(),logo_uri:L.optional(),scope:m().optional(),contacts:h(m()).optional(),tos_uri:L.optional(),policy_uri:m().optional(),jwks_uri:L.optional(),jwks:ie().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),Ye=p({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xe=Je.merge(qe),Ze=`vercel.ai.error.AI_MCPClientOAuthError`,Qe=Symbol.for(Ze),$e,et,z=class extends (et=e,$e=Qe,et){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[$e]=!0}static isInstance(t){return e.hasMarker(t,Ze)}},B=class extends z{};B.errorCode=`server_error`;var V=class extends z{};V.errorCode=`invalid_client`;var H=class extends z{};H.errorCode=`invalid_grant`;var U=class extends z{};U.errorCode=`unauthorized_client`;var tt={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function nt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function W(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function rt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var G=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function K(e){return new URL(e).href}function it(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function st(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function ct({provider:e,clientInformation:t,tokens:n}){let r=st(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:st(t)}async function lt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ot(t,n)),!0):!1}function ut(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new z({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function dt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new z({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function q(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function ft(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function pt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function ht(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await pt(o,a,n);return!r?.metadataUrl&&mt(s,i.pathname)&&(s=await pt(new URL(`/.well-known/${t}`,i),a,n)),s}async function gt(e,t,n=fetch){let r=await ht(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Ge.parse(await r.json())}function _t(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function vt(e,t){if(e.issuer!==t)throw new z({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function yt(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=_t(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=R.parse(await i.json());return vt(e,a),e}else{let t=Ke.parse(await i.json());if(vt(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function bt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await fe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,W(o)),{authorizationUrl:l,codeVerifier:d}}function xt(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function St(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ct(i,a,n);return;case`client_secret_post`:wt(i,a,r);return;case`none`:Tt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ct(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function wt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Tt(e,t){t.set(`client_id`,e)}async function Y(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:i}=Ye.parse(await r({text:n}));return new(tt[e]||B)({message:t||``,cause:i})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Et(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,W(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return We.parse(await p.json())}async function Dt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):St(xt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,W(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return We.parse({refresh_token:r,...await d.json()})}async function Ot(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Xe.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function kt(e,t,n){let r=nt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!rt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ut(t,a);try{s=await gt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await kt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await yt(c,{fetchFn:o}),d=it(c,u),f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);f=ot(await Ot(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await ct({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Et(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await ct({provider:e,clientInformation:f,tokens:p});t?dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Dt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof z)||e instanceof B))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:ee,codeVerifier:h}=await bt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await lt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(ee),`REDIRECT`}function At(e){return e===void 0||e===`message`}var jt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??C};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return i(t,`ai-sdk/${Ue}`,o())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let r=async(i=!1)=>{var a,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(a=this.onerror)==null||a.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return r(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new S({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new S({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new S({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(At(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new S({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.call(this,e),t(e)}};r()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new S({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new S({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function Mt(e){return e===void 0||e===`message`}var Nt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??C};if(t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return i(n,`ai-sdk/${Ue}`,o())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new S({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(r=!1)=>{var i,a,o,s,c,l;try{let l=`method`in e&&e.method===`initialize`,u=l?void 0:this.sessionId,d={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!l}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},f=await this.fetchFn(this.url.href,d);if(this.applySessionIdFromResponse(f),f.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(f);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(i=this.onerror)==null||i.call(this,e),e}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){let e=await f.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${e}`;f.status===404&&(u?(this.expireSessionId(u),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new S({message:t,statusCode:f.status,url:this.url.href,responseBody:e??void 0});throw(a=this.onerror)==null||a.call(this,n),n}if(!(`id`in e))return;let p=f.headers.get(`content-type`)||``;if(p.includes(`application/json`)){let e=await f.json(),t=Array.isArray(e)?e.map(e=>F.parse(e)):[F.parse(e)];for(let e of t)(o=this.onmessage)==null||o.call(this,e);return}if(p.includes(`text/event-stream`)){if(!f.body){let e=new S({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:f.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,e),e}let e=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(Mt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new S({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let m=new S({message:`MCP HTTP Transport Error: Unexpected content type: ${p}`,statusCode:f.status,url:this.url.href});throw(c=this.onerror)==null||c.call(this,m),m}catch(e){throw(l=this.onerror)==null||l.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new S({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var r,i,a,o;try{let o=this.sessionId,s=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(s[`last-event-id`]=t);let c=await this.fetchFn(this.url.href,{method:`GET`,headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(c),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(c);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(r=this.onerror)==null||r.call(this,e);return}}catch(e){(i=this.onerror)==null||i.call(this,e);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){c.status===404&&o&&this.expireSessionId(o);let e=new S({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`,statusCode:c.status,url:this.url.href});(a=this.onerror)==null||a.call(this,e);return}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Mt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new S({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>l.cancel()},this.inboundReconnectAttempts=0,u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Pt(e){switch(e.type){case`sse`:return new jt(e);case`http`:return new Nt(e);default:throw new S({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ft(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var It=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Lt=`ui/resourceUri`,Rt={extensions:{[It]:{mimeTypes:[Q]}}};function zt(e){let n=e?.ui;return t(n)?n:void 0}function Bt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Vt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Ht(e){let t=zt(e._meta),n=t?.resourceUri??e._meta?.[Lt],r=Vt(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function Ut(e){let t=[],n=[];for(let r of e.tools){let e=Ht(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function Wt({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(ee(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Bt(n._meta)}}async function Gt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Wt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Kt=`1.0.0`;function qt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function $(e){let t=new Jt(e);return await t.init(),t}var Jt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Kt,onUncaughtError:i,capabilities:a,initialInitializeResult:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:C,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},this.initialInitializeResult=o,Ft(e)?this.transport=e:this.transport=Pt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new S({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=E.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:C,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:E});if(e===void 0)throw new S({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!_e.includes(e.protocolVersion))throw new S({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new S({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new S({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new S({message:`Server does not support prompts`});break;default:throw new S({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new S({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new S({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new S({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:we,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:ke,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ee,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Me,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:je,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Le,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,f=Ht({_meta:l}),p={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...f?.resourceUri==null?{}:{app:{...f,mimeType:Q}}},m=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?ae({description:o,title:e,metadata:p,inputSchema:te({...s,properties:s.properties??{},additionalProperties:!1}),execute:m,toModelOutput:qt}):a({description:o,title:e,metadata:p,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:m,toModelOutput:qt}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await c({value:e.structuredContent,schema:re(t)});if(!r.success)throw new S({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await s({text:r.text,schema:t});if(!e.success)throw new S({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new S({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==N)throw new S({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=N.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=ze.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new S({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new S({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new S({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,G as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Rt as mcpAppClientCapabilities,Gt as readMCPAppResource,Ut as splitMCPAppTools};
1
+ import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{A as n,C as r,Ct as i,Et as a,G as o,K as s,L as c,W as l,X as u,_t as d,a as f,at as p,b as m,bt as h,dt as g,et as ee,ft as _,gt as v,ht as y,lt as te,n as ne,ut as b,vt as x,wt as S,xt as C,yt as w}from"../../_chunks/workflow/dist-zLevmMyU.js";const re={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var ie;ie||={};let T;T=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ae(e){return(await T).getRandomValues(new Uint8Array(e))}async function oe(e){let t=``;for(;t.length<e;){let n=await ae(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function se(e){return await oe(e)}async function ce(e){let t=await(await T).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function le(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await se(e);return{code_verifier:t,code_challenge:await ce(t)}}var E=`2025-11-25`,ue=[E,`2025-06-18`,`2025-03-26`,`2024-11-05`],de=w(h(C(),S())),fe=v({name:C(),version:C(),title:w(C())}),D=v({_meta:w(x({}).loose())}),O=D,pe=x({method:C(),params:w(D)}),me=x({applyDefaults:w(_())}).loose(),he=v({experimental:w(x({}).loose()),logging:w(x({}).loose()),completions:w(x({}).loose()),prompts:w(v({listChanged:w(_())})),resources:w(v({subscribe:w(_()),listChanged:w(_())})),tools:w(v({listChanged:w(_())})),elicitation:w(me)});x({elicitation:w(me)}).loose();var ge=O.extend({protocolVersion:C(),capabilities:he,serverInfo:fe,instructions:w(C())}),k=O.extend({nextCursor:w(C())}),_e=x({name:C(),title:w(C()),description:w(C()),inputSchema:x({type:y(`object`),properties:w(x({}).loose())}).loose(),outputSchema:w(x({}).loose()),annotations:w(x({title:w(C())}).loose()),_meta:de}).loose(),ve=k.extend({tools:b(_e)}),ye=x({type:y(`text`),text:C()}).loose(),be=x({type:y(`image`),data:g(),mimeType:C()}).loose(),xe=x({uri:C(),name:C(),title:w(C()),description:w(C()),mimeType:w(C()),size:w(d())}).loose(),Se=k.extend({resources:b(xe)}),A=x({uri:C(),name:w(C()),title:w(C()),mimeType:w(C())}).loose(),j=A.extend({text:C()}),M=A.extend({blob:g()}),Ce=x({type:y(`resource`),resource:i([j,M])}).loose(),we=x({type:y(`resource_link`),uri:C(),name:C(),description:w(C()),mimeType:w(C())}).loose(),Te=O.extend({content:b(i([ye,be,Ce,we])),structuredContent:w(S()),isError:_().default(!1).optional()}).or(O.extend({toolResult:S()})),Ee=x({uriTemplate:C(),name:C(),title:w(C()),description:w(C()),mimeType:w(C())}).loose(),De=O.extend({resourceTemplates:b(Ee)}),Oe=O.extend({contents:b(i([j,M]))}),ke=x({type:y(`ref/prompt`),name:C()}).loose(),Ae=x({type:y(`ref/resource`),uri:C()}).loose(),je=x({name:C(),value:C()}).loose();D.extend({ref:i([ke,Ae]),argument:je,context:w(x({arguments:h(C(),C())}).loose())});var Me=O.extend({completion:x({values:b(C()).max(100),total:w(d().int()),hasMore:w(_())}).loose()}),Ne=x({name:C(),description:w(C()),required:w(_())}).loose(),Pe=x({name:C(),title:w(C()),description:w(C()),arguments:w(b(Ne))}).loose(),Fe=k.extend({prompts:b(Pe)}),Ie=x({role:i([y(`user`),y(`assistant`)]),content:i([ye,be,Ce,we])}).loose(),Le=O.extend({description:w(C()),messages:b(Ie)}),Re=D.extend({message:C(),requestedSchema:S()}),N=pe.extend({method:y(`elicitation/create`),params:Re}),ze=O.extend({action:i([y(`accept`),y(`decline`),y(`cancel`)]),content:w(h(C(),S()))}),P=`2.0`,Be=x({jsonrpc:y(P),id:i([C(),d().int()])}).merge(pe).strict(),Ve=x({jsonrpc:y(P),id:i([C(),d().int()]),result:O}).strict(),He=x({jsonrpc:y(P),id:i([C(),d().int()]),error:x({code:d().int(),message:C(),data:w(S())})}).strict(),Ue=i([Be,x({jsonrpc:y(P)}).merge(x({method:C(),params:w(D)})).strict(),Ve,He]);function F(e){return Ue.parse(e)}async function I(e){return F(await c({text:e}))}var We=`vercel.ai.error.AI_MCPClientError`,Ge=Symbol.for(We),Ke,L,R=class extends (L=e,Ke=Ge,L){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Ke]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,We)}},qe=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,z=C().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:re.custom,message:`URL must be parseable`,fatal:!0}),a}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Je=x({access_token:C(),id_token:C().optional(),token_type:C(),expires_in:d().optional(),scope:C().optional(),refresh_token:C().optional(),authorization_server:z.optional(),token_endpoint:z.optional()}).strip(),Ye=v({resource:C().url(),authorization_servers:b(z).optional(),jwks_uri:C().url().optional(),scopes_supported:b(C()).optional(),bearer_methods_supported:b(C()).optional(),resource_signing_alg_values_supported:b(C()).optional(),resource_name:C().optional(),resource_documentation:C().optional(),resource_policy_uri:C().url().optional(),resource_tos_uri:C().url().optional(),tls_client_certificate_bound_access_tokens:_().optional(),authorization_details_types_supported:b(C()).optional(),dpop_signing_alg_values_supported:b(C()).optional(),dpop_bound_access_tokens_required:_().optional()}),Xe=v({issuer:C(),authorization_endpoint:z,token_endpoint:z,registration_endpoint:z.optional(),scopes_supported:b(C()).optional(),response_types_supported:b(C()),grant_types_supported:b(C()).optional(),code_challenge_methods_supported:b(C()),token_endpoint_auth_methods_supported:b(C()).optional(),token_endpoint_auth_signing_alg_values_supported:b(C()).optional()}),Ze=v({issuer:C(),authorization_endpoint:z,token_endpoint:z,userinfo_endpoint:z.optional(),jwks_uri:z,registration_endpoint:z.optional(),scopes_supported:b(C()).optional(),response_types_supported:b(C()),grant_types_supported:b(C()).optional(),subject_types_supported:b(C()),id_token_signing_alg_values_supported:b(C()),claims_supported:b(C()).optional(),token_endpoint_auth_methods_supported:b(C()).optional()}).merge(Xe.pick({code_challenge_methods_supported:!0})),Qe=x({client_id:C(),client_secret:C().optional(),client_id_issued_at:d().optional(),client_secret_expires_at:d().optional(),authorization_server:z.optional(),token_endpoint:z.optional()}).strip(),$e=x({redirect_uris:b(z),token_endpoint_auth_method:C().optional(),grant_types:b(C()).optional(),response_types:b(C()).optional(),client_name:C().optional(),client_uri:z.optional(),logo_uri:z.optional(),scope:C().optional(),contacts:b(C()).optional(),tos_uri:z.optional(),policy_uri:C().optional(),jwks_uri:z.optional(),jwks:te().optional(),software_id:C().optional(),software_version:C().optional(),software_statement:C().optional()}).strip(),et=x({error:C(),error_description:C().optional(),error_uri:C().optional()}),tt=$e.merge(Qe),nt=`vercel.ai.error.AI_MCPClientOAuthError`,rt=Symbol.for(nt),it,at,B=class extends (at=e,it=rt,at){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[it]=!0}static isInstance(t){return e.hasMarker(t,nt)}},V=class extends B{};V.errorCode=`server_error`;var H=class extends B{};H.errorCode=`invalid_client`;var U=class extends B{};U.errorCode=`invalid_grant`;var W=class extends B{};W.errorCode=`unauthorized_client`;var ot={[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U,[W.errorCode]:W};function st(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function G(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function ct({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var K=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function q(e){return new URL(e).href}function lt(e,t){return{authorizationServerUrl:q(e),tokenEndpoint:q(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function ut(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function dt(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ft(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:q(e.authorization_server),tokenEndpoint:q(e.token_endpoint)}}async function pt({provider:e,clientInformation:t,tokens:n}){let r=ft(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:q(i.authorizationServerUrl),tokenEndpoint:q(i.tokenEndpoint)}:ft(t)}async function mt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(dt(t,n)),!0):!1}function ht(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new B({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function gt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new B({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function J(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function _t(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Y(e,void 0,n):void 0;throw r}}async function vt(e,t,n=fetch){return await Y(e,{"MCP-Protocol-Version":t},n)}function yt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function bt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??E,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=_t(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await vt(o,a,n);return!r?.metadataUrl&&yt(s,i.pathname)&&(s=await vt(new URL(`/.well-known/${t}`,i),a,n)),s}async function xt(e,t,n=fetch){let r=await bt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Ye.parse(await r.json())}function St(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function Ct(e,t){if(e.issuer!==t)throw new B({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function wt(e,{fetchFn:t=fetch,protocolVersion:n=E}={}){let r={"MCP-Protocol-Version":n},i=St(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await Y(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=Xe.parse(await i.json());return Ct(e,a),e}else{let t=Ze.parse(await i.json());if(Ct(t,a),!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function Tt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await le(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,G(o)),{authorizationUrl:l,codeVerifier:d}}function Et(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Dt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ot(i,a,n);return;case`client_secret_post`:kt(i,a,r);return;case`none`:At(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ot(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function kt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function At(e,t){t.set(`client_id`,e)}async function X(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=et.parse(await c({text:n}));return new(ot[e]||V)({message:t||``,cause:r})}catch(e){return new V({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function jt(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?await s(d,f,e,t):Dt(Et(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,G(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await X(p);return Je.parse(await p.json())}async function Mt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?await a(l,u,e,t):Dt(Et(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,G(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await X(d);return Je.parse({refresh_token:r,...await d.json()})}async function Nt(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await X(a);return tt.parse(await a.json())}async function Z(e,t){try{return await Q(e,t)}catch(n){if(n instanceof H||n instanceof W)return await e.invalidateCredentials?.call(e,`all`),await Q(e,t);if(n instanceof U)return await e.invalidateCredentials?.call(e,`tokens`),await Q(e,t);throw n}}async function Pt(e,t,n){let r=st(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ct({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Q(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ht(t,a);try{s=await xt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await Pt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await wt(c,{fetchFn:o}),d=lt(c,u),f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);f=dt(await Nt(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await pt({provider:e,clientInformation:f});if(!t)throw new B({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});gt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await jt(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(ut(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await pt({provider:e,clientInformation:f,tokens:p});t?gt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Mt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(ut(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof B)||e instanceof V))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:g}=await Tt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await mt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new B({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),`REDIRECT`}function Ft(e){return e===void 0||e===`message`}var It=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??E};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return ee(t,`ai-sdk/${qe}`,r())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=J(c);try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new R({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new R({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new R({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Ft(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new R({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,this.endpoint=void 0,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new R({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=J(c);try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new R({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function Lt(e){return e===void 0||e===`message`}var Rt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??E};if(t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return ee(n,`ai-sdk/${qe}`,r())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new R({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.startInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c=`method`in e&&e.method===`initialize`,l=c?void 0:this.sessionId,u={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!c}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},d=await this.fetchFn(this.url.href,u);if(this.applySessionIdFromResponse(d),d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=J(d);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new K}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(d.status===202){this.inboundSseConnection||this.startInboundSse();return}if(!d.ok){let e=await d.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${d.status}): ${e}`;d.status===404&&(l?(this.expireSessionId(l),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new R({message:t,statusCode:d.status,url:this.url.href,responseBody:e??void 0});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let f=d.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await d.json(),t=Array.isArray(e)?e.map(e=>F(e)):[F(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(f.includes(`text/event-stream`)){if(!d.body){let e=new R({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:d.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(Lt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new R({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)});return}let m=new R({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:d.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,m),m}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new R({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=J(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new K;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new R({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Lt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new R({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>{c.cancel().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function zt(e){switch(e.type){case`sse`:return new It(e);case`http`:return new Rt(e);default:throw new R({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Bt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Vt=`io.modelcontextprotocol/ui`,$=`text/html;profile=mcp-app`,Ht=`ui/resourceUri`,Ut={extensions:{[Vt]:{mimeTypes:[$]}}};function Wt(e){let n=e?.ui;return t(n)?n:void 0}function Gt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Kt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function qt(e){let t=Wt(e._meta),n=t?.resourceUri??e._meta?.[Ht],r=Kt(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function Jt(e){let t=[],n=[];for(let r of e.tools){let e=qt(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function Yt({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(f(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:$,html:r,meta:Gt(n._meta)}}async function Xt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Yt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Zt=`1.0.0`,Qt=0,$t=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function en(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function tn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function nn(e){let t=en(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(R.isInstance(e)&&e.code!=null)return!1;let n=tn(e);return n!=null&&$t.includes(n)}function rn(e){if(e==null)return Qt;if(!Number.isInteger(e))throw new R({message:`maxRetries must be an integer`});if(e<0)throw new R({message:`maxRetries must be >= 0`});return e}function an({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function on(e){let t=new sn(e);return await t.init(),t}var sn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Zt,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:E,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=rn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,Bt(e)?this.transport=e:this.transport=zt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new R({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=ge.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:E,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:ge});if(e===void 0)throw new R({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!ue.includes(e.protocolVersion))throw new R({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new R({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new R({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new R({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new R({message:`Server does not support prompts`});break;default:throw new R({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new R({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{i(new R({message:`Request was aborted`,cause:a?.reason}))},l=()=>{this.responseHandlers.delete(o),a?.removeEventListener(`abort`,d)},u=e=>{l(),i(e)},d=()=>{l(),c()};this.responseHandlers.set(o,e=>{if(a?.aborted)return l(),c();if(e instanceof Error)return u(e);try{let n=t.parse(e.result);l(),r(n)}catch(e){u(new R({message:`Failed to parse server response`,cause:e}))}}),a?.addEventListener(`abort`,d,{once:!0}),this.transport.send(s).catch(e=>{u(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:ve,options:t})}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():l({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:nn,createRetryError:({message:e,errors:t})=>new R({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Te,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Se,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Oe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:De,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Le,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:Me,options:e})}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let r={};for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let d=this,f=t===`automatic`?void 0:t[i]?.outputSchema,p=qt({_meta:l}),h={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...p?.resourceUri==null?{}:{app:{...p,mimeType:$}}},g=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let r=await d.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return r.isError||f==null?r:d.extractStructuredContent(r,f,i)};r[i]={...t===`automatic`?m({description:o,title:e,metadata:h,inputSchema:n({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:an}):u({description:o,title:e,metadata:h,inputSchema:t[i].inputSchema,...f==null?{}:{outputSchema:f},execute:g,toModelOutput:an}),_meta:l}}return r}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await s({value:e.structuredContent,schema:ne(t)});if(!r.success)throw new R({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await o({text:r.text,schema:t});if(!e.success)throw new R({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new R({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==N)throw new R({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=N.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=ze.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new R({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new R({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new R({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,$ as MCP_APP_MIME_TYPE,K as UnauthorizedError,Z as auth,on as createMCPClient,on as experimental_createMCPClient,Ut as mcpAppClientCapabilities,Xt as readMCPAppResource,Jt as splitMCPAppTools,F as validateJSONRPCMessage};
@@ -1,15 +1,15 @@
1
1
  import * as _ai_sdk_provider from '#compiled/@ai-sdk/provider/index.js';
2
2
  import { JSONValue, ProviderV4, LanguageModelV4, EmbeddingModelV4, ImageModelV4, TranscriptionModelV4, SpeechModelV4, Experimental_RealtimeFactoryV4, FilesV4, SkillsV4, Experimental_RealtimeModelV4, Experimental_RealtimeModelV4ClientSecretOptions, Experimental_RealtimeModelV4ClientSecretResult, Experimental_RealtimeModelV4ServerEvent, Experimental_RealtimeModelV4ClientEvent, Experimental_RealtimeModelV4SessionConfig } from '#compiled/@ai-sdk/provider/index.js';
3
3
  import * as _ai_sdk_provider_utils from '#compiled/@ai-sdk/provider-utils/index.js';
4
- import { InferSchema, FetchFunction } from '#compiled/@ai-sdk/provider-utils/index.js';
4
+ import { InferSchema, FetchFunction, WebSocketConstructor } from '#compiled/@ai-sdk/provider-utils/index.js';
5
5
 
6
- type OpenAIChatModelId = 'o1' | 'o1-2024-12-17' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-audio-preview-2025-06-03' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4o-mini-audio-preview' | 'gpt-4o-mini-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-16k' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-5.1' | 'gpt-5.1-2025-11-13' | 'gpt-5.1-chat-latest' | 'gpt-5.2' | 'gpt-5.2-2025-12-11' | 'gpt-5.2-chat-latest' | 'gpt-5.2-pro' | 'gpt-5.2-pro-2025-12-11' | 'gpt-5.3-chat-latest' | 'gpt-5.4' | 'gpt-5.4-2026-03-05' | 'gpt-5.4-mini' | 'gpt-5.4-mini-2026-03-17' | 'gpt-5.4-nano' | 'gpt-5.4-nano-2026-03-17' | 'gpt-5.4-pro' | 'gpt-5.4-pro-2026-03-05' | 'gpt-5.5' | 'gpt-5.5-2026-04-23' | (string & {});
6
+ type OpenAIChatModelId = 'o1' | 'o1-2024-12-17' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-audio-preview-2025-06-03' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4o-mini-audio-preview' | 'gpt-4o-mini-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-16k' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-5.1' | 'gpt-5.1-2025-11-13' | 'gpt-5.1-chat-latest' | 'gpt-5.2' | 'gpt-5.2-2025-12-11' | 'gpt-5.2-chat-latest' | 'gpt-5.2-pro' | 'gpt-5.2-pro-2025-12-11' | 'gpt-5.3-chat-latest' | 'gpt-5.4' | 'gpt-5.4-2026-03-05' | 'gpt-5.4-mini' | 'gpt-5.4-mini-2026-03-17' | 'gpt-5.4-nano' | 'gpt-5.4-nano-2026-03-17' | 'gpt-5.4-pro' | 'gpt-5.4-pro-2026-03-05' | 'gpt-5.5' | 'gpt-5.5-2026-04-23' | 'gpt-5.6' | 'gpt-5.6-luna' | 'gpt-5.6-sol' | 'gpt-5.6-terra' | (string & {});
7
7
  declare const openaiLanguageModelChatOptions: _ai_sdk_provider_utils.LazySchema<{
8
8
  logitBias?: Record<number, number> | undefined;
9
9
  logprobs?: number | boolean | undefined;
10
10
  parallelToolCalls?: boolean | undefined;
11
11
  user?: string | undefined;
12
- reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | undefined;
12
+ reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | undefined;
13
13
  maxCompletionTokens?: number | undefined;
14
14
  store?: boolean | undefined;
15
15
  metadata?: Record<string, string> | undefined;
@@ -18,6 +18,10 @@ declare const openaiLanguageModelChatOptions: _ai_sdk_provider_utils.LazySchema<
18
18
  strictJsonSchema?: boolean | undefined;
19
19
  textVerbosity?: "low" | "medium" | "high" | undefined;
20
20
  promptCacheKey?: string | undefined;
21
+ promptCacheOptions?: {
22
+ mode?: "explicit" | "implicit" | undefined;
23
+ ttl?: "30m" | undefined;
24
+ } | undefined;
21
25
  promptCacheRetention?: "in_memory" | "24h" | undefined;
22
26
  safetyIdentifier?: string | undefined;
23
27
  systemMessageMode?: "remove" | "system" | "developer" | undefined;
@@ -244,6 +248,7 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
244
248
  output_tokens: number;
245
249
  input_tokens_details?: {
246
250
  cached_tokens?: number | null | undefined;
251
+ cache_write_tokens?: number | null | undefined;
247
252
  orchestration_input_tokens?: number | null | undefined;
248
253
  orchestration_input_cached_tokens?: number | null | undefined;
249
254
  } | null | undefined;
@@ -255,6 +260,9 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
255
260
  incomplete_details?: {
256
261
  reason: string;
257
262
  } | null | undefined;
263
+ reasoning?: {
264
+ context?: string | null | undefined;
265
+ } | null | undefined;
258
266
  service_tier?: string | null | undefined;
259
267
  };
260
268
  } | {
@@ -273,6 +281,7 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
273
281
  output_tokens: number;
274
282
  input_tokens_details?: {
275
283
  cached_tokens?: number | null | undefined;
284
+ cache_write_tokens?: number | null | undefined;
276
285
  orchestration_input_tokens?: number | null | undefined;
277
286
  orchestration_input_cached_tokens?: number | null | undefined;
278
287
  } | null | undefined;
@@ -281,6 +290,9 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
281
290
  orchestration_output_tokens?: number | null | undefined;
282
291
  } | null | undefined;
283
292
  } | null | undefined;
293
+ reasoning?: {
294
+ context?: string | null | undefined;
295
+ } | null | undefined;
284
296
  service_tier?: string | null | undefined;
285
297
  };
286
298
  } | {
@@ -1061,10 +1073,10 @@ declare const openaiTools: {
1061
1073
  }, {}>;
1062
1074
  };
1063
1075
 
1064
- type OpenAIResponsesModelId = 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-mini-2024-07-18' | 'gpt-4o-mini' | 'gpt-4o' | 'gpt-5.1' | 'gpt-5.1-2025-11-13' | 'gpt-5.1-chat-latest' | 'gpt-5.1-codex-mini' | 'gpt-5.1-codex' | 'gpt-5.1-codex-max' | 'gpt-5.2' | 'gpt-5.2-2025-12-11' | 'gpt-5.2-chat-latest' | 'gpt-5.2-pro' | 'gpt-5.2-pro-2025-12-11' | 'gpt-5.2-codex' | 'gpt-5.3-chat-latest' | 'gpt-5.3-codex' | 'gpt-5.4' | 'gpt-5.4-2026-03-05' | 'gpt-5.4-mini' | 'gpt-5.4-mini-2026-03-17' | 'gpt-5.4-nano' | 'gpt-5.4-nano-2026-03-17' | 'gpt-5.4-pro' | 'gpt-5.4-pro-2026-03-05' | 'gpt-5.5' | 'gpt-5.5-2026-04-23' | 'gpt-5-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-5-codex' | 'gpt-5-mini-2025-08-07' | 'gpt-5-mini' | 'gpt-5-nano-2025-08-07' | 'gpt-5-nano' | 'gpt-5-pro-2025-10-06' | 'gpt-5-pro' | 'gpt-5' | 'o1-2024-12-17' | 'o1' | 'o3-2025-04-16' | 'o3-mini-2025-01-31' | 'o3-mini' | 'o3' | 'o4-mini' | 'o4-mini-2025-04-16' | (string & {});
1076
+ type OpenAIResponsesModelId = 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-mini-2024-07-18' | 'gpt-4o-mini' | 'gpt-4o' | 'gpt-5.1' | 'gpt-5.1-2025-11-13' | 'gpt-5.1-chat-latest' | 'gpt-5.1-codex-mini' | 'gpt-5.1-codex' | 'gpt-5.1-codex-max' | 'gpt-5.2' | 'gpt-5.2-2025-12-11' | 'gpt-5.2-chat-latest' | 'gpt-5.2-pro' | 'gpt-5.2-pro-2025-12-11' | 'gpt-5.2-codex' | 'gpt-5.3-chat-latest' | 'gpt-5.3-codex' | 'gpt-5.4' | 'gpt-5.4-2026-03-05' | 'gpt-5.4-mini' | 'gpt-5.4-mini-2026-03-17' | 'gpt-5.4-nano' | 'gpt-5.4-nano-2026-03-17' | 'gpt-5.4-pro' | 'gpt-5.4-pro-2026-03-05' | 'gpt-5.5' | 'gpt-5.5-2026-04-23' | 'gpt-5.6' | 'gpt-5.6-luna' | 'gpt-5.6-sol' | 'gpt-5.6-terra' | 'gpt-5-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-5-codex' | 'gpt-5-mini-2025-08-07' | 'gpt-5-mini' | 'gpt-5-nano-2025-08-07' | 'gpt-5-nano' | 'gpt-5-pro-2025-10-06' | 'gpt-5-pro' | 'gpt-5' | 'o1-2024-12-17' | 'o1' | 'o3-2025-04-16' | 'o3-mini-2025-01-31' | 'o3-mini' | 'o3' | 'o4-mini' | 'o4-mini-2025-04-16' | (string & {});
1065
1077
  declare const openaiLanguageModelResponsesOptionsSchema: _ai_sdk_provider_utils.LazySchema<{
1066
1078
  conversation?: string | null | undefined;
1067
- include?: ("file_search_call.results" | "message.output_text.logprobs" | "reasoning.encrypted_content")[] | null | undefined;
1079
+ include?: ("web_search_call.results" | "file_search_call.results" | "message.output_text.logprobs" | "reasoning.encrypted_content")[] | null | undefined;
1068
1080
  instructions?: string | null | undefined;
1069
1081
  logprobs?: number | boolean | undefined;
1070
1082
  maxToolCalls?: number | null | undefined;
@@ -1072,8 +1084,14 @@ declare const openaiLanguageModelResponsesOptionsSchema: _ai_sdk_provider_utils.
1072
1084
  parallelToolCalls?: boolean | null | undefined;
1073
1085
  previousResponseId?: string | null | undefined;
1074
1086
  promptCacheKey?: string | null | undefined;
1087
+ promptCacheOptions?: {
1088
+ mode?: "explicit" | "implicit" | undefined;
1089
+ ttl?: "30m" | undefined;
1090
+ } | undefined;
1075
1091
  promptCacheRetention?: "in_memory" | "24h" | null | undefined;
1076
1092
  reasoningEffort?: string | null | undefined;
1093
+ reasoningMode?: "standard" | "pro" | undefined;
1094
+ reasoningContext?: "auto" | "current_turn" | "all_turns" | undefined;
1077
1095
  reasoningSummary?: string | null | undefined;
1078
1096
  safetyIdentifier?: string | null | undefined;
1079
1097
  serviceTier?: "default" | "auto" | "flex" | "priority" | null | undefined;
@@ -1103,13 +1121,17 @@ declare const openaiSpeechModelOptionsSchema: _ai_sdk_provider_utils.LazySchema<
1103
1121
  }>;
1104
1122
  type OpenAISpeechModelOptions = InferSchema<typeof openaiSpeechModelOptionsSchema>;
1105
1123
 
1106
- type OpenAITranscriptionModelId = 'whisper-1' | 'gpt-4o-mini-transcribe' | 'gpt-4o-mini-transcribe-2025-03-20' | 'gpt-4o-mini-transcribe-2025-12-15' | 'gpt-4o-transcribe' | 'gpt-4o-transcribe-diarize' | (string & {});
1124
+ type OpenAITranscriptionModelId = 'whisper-1' | 'gpt-4o-mini-transcribe' | 'gpt-4o-mini-transcribe-2025-03-20' | 'gpt-4o-mini-transcribe-2025-12-15' | 'gpt-4o-transcribe' | 'gpt-4o-transcribe-diarize' | 'gpt-realtime-whisper' | (string & {});
1107
1125
  declare const openAITranscriptionModelOptions: _ai_sdk_provider_utils.LazySchema<{
1108
1126
  include?: string[] | undefined;
1109
1127
  language?: string | undefined;
1110
1128
  prompt?: string | undefined;
1111
1129
  temperature?: number | undefined;
1112
1130
  timestampGranularities?: ("word" | "segment")[] | undefined;
1131
+ streaming?: {
1132
+ delay?: "minimal" | "low" | "medium" | "high" | "xhigh" | undefined;
1133
+ include?: string[] | undefined;
1134
+ } | undefined;
1113
1135
  }>;
1114
1136
  type OpenAITranscriptionModelOptions = InferSchema<typeof openAITranscriptionModelOptions>;
1115
1137
 
@@ -1211,6 +1233,11 @@ interface OpenAIProviderSettings {
1211
1233
  * or to provide a custom fetch implementation for e.g. testing.
1212
1234
  */
1213
1235
  fetch?: FetchFunction;
1236
+ /**
1237
+ * Custom WebSocket implementation. This is useful for testing or for
1238
+ * runtimes that need a WebSocket constructor with header support.
1239
+ */
1240
+ webSocket?: WebSocketConstructor;
1214
1241
  }
1215
1242
  /**
1216
1243
  * Create an OpenAI provider instance.
@@ -1260,6 +1287,7 @@ type ResponsesProviderMetadata = {
1260
1287
  responseId: string | null | undefined;
1261
1288
  logprobs?: Array<OpenAIResponsesLogprobs>;
1262
1289
  serviceTier?: string;
1290
+ reasoningContext?: string;
1263
1291
  };
1264
1292
  type ResponsesReasoningProviderMetadata = {
1265
1293
  itemId: string;