mcp-use 2.0.0 → 2.0.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.
package/README.md ADDED
@@ -0,0 +1,379 @@
1
+ <div align="center">
2
+ <a href="https://mcp-use.com">
3
+ <img alt="mcp-use" src="./docs/logo/banner-mcp-use.webp" width="100%">
4
+ </a>
5
+ <br /><br />
6
+
7
+ <div id="user-content-toc">
8
+ <ul align="center" style="list-style: none;">
9
+ <summary>
10
+ <h1>The TypeScript framework for MCP</h1>
11
+ <h3>Build, test, and ship MCP servers, ChatGPT plugins, Claude connectors</h3>
12
+ </summary>
13
+ </ul>
14
+ </div>
15
+
16
+
17
+ <p>
18
+ Fully Typed, native Views and MCP Apps support, built-in Inspector and first class Agent experience.
19
+ </p>
20
+
21
+ <p>
22
+ <a href="https://docs.mcp-use.com/v2/typescript/getting-started/welcome"><strong>Documentation</strong></a>
23
+ · <a href="https://inspector.mcp-use.com/inspector"><strong>Inspector</strong></a>
24
+ · <a href="#examples"><strong>Examples</strong></a>
25
+ · <a href="https://manufact.com"><strong>Deploy</strong></a>
26
+ </p>
27
+
28
+ <p>
29
+ <a href="https://www.npmjs.com/package/mcp-use">
30
+ <img src="https://img.shields.io/npm/v/mcp-use.svg?label=npm&amp;color=orange" alt="npm version">
31
+ </a>
32
+ <a href="https://www.npmjs.com/package/mcp-use">
33
+ <img src="https://img.shields.io/npm/dw/mcp-use.svg" alt="npm downloads">
34
+ </a>
35
+ <a href="https://manufact.com">
36
+ <img src="https://img.shields.io/badge/made%20by-manufact.com-blue" alt="made by manufact.com">
37
+ </a>
38
+ <a href="https://github.com/mcp-use/mcp-use/blob/main/LICENSE">
39
+ <img src="https://img.shields.io/github/license/mcp-use/mcp-use" alt="MIT license">
40
+ </a>
41
+ <a href="https://discord.gg/XkNkSkMz3V">
42
+ <img src="https://dcbadge.limes.pink/api/server/XkNkSkMz3V?style=flat" alt="Discord">
43
+ </a>
44
+ </p>
45
+ <br /><br />
46
+ </div>
47
+
48
+ > [!NOTE]
49
+ > **Migrating from v1? Give it to your agent:** [Read the migration guide →](https://docs.mcp-use.com/v2/server/migration)
50
+ >
51
+ > ```text
52
+ > Migrate this mcp-use project to v2 following
53
+ > https://docs.mcp-use.com/v2/typescript/server/migration
54
+ > ```
55
+ >
56
+ > [Read the migration guide →](https://docs.mcp-use.com/v2/typescript/server/migration)
57
+
58
+ ## Get started
59
+
60
+ ### Start with your agent
61
+
62
+ ```text
63
+ Build an MCP server: https://mcp-use.com/prompt.md
64
+ ```
65
+
66
+ [Read the prompt →](https://mcp-use.com/prompt.md)
67
+
68
+ ### Start with code
69
+
70
+ ```bash
71
+ npx -y create-mcp-use-app@latest
72
+ ```
73
+
74
+ Run `npm run dev` in the generated project · open [`http://localhost:3000/mcp/inspector`](http://localhost:3000/mcp/inspector)
75
+
76
+ [TS Docs](https://docs.mcp-use.com/v2/typescript/getting-started/welcome)
77
+
78
+ ## Everything you need to ship MCP
79
+
80
+ <table>
81
+ <tr>
82
+ <td width="50%" valign="top">
83
+ <h3>Fully typed</h3>
84
+ <p>Zod schemas flow from tools to structured results, View props, and tool calls.</p>
85
+ </td>
86
+ <td width="50%" valign="top">
87
+ <h3>Native Views</h3>
88
+ <p>Bind React Views directly to tools and ship interactive apps without custom extension wiring.</p>
89
+ </td>
90
+ </tr>
91
+ <tr>
92
+ <td width="50%" valign="top">
93
+ <h3>Agent-first and headless</h3>
94
+ <p>Scaffold, invoke, inspect, screenshot, and deploy through your agent.</p>
95
+ </td>
96
+ <td width="50%" valign="top">
97
+ <h3>Built-in debugging tools</h3>
98
+ <p>Inspect tools and Views in the browser or headlessly through the CLI.</p>
99
+ </td>
100
+ </tr>
101
+ </table>
102
+
103
+ ## Quickstart
104
+
105
+ The scaffold gives you the server, TypeScript configuration, development scripts, Inspector, and a React view pipeline. Start it once and the MCP endpoint also serves a client-ready landing page with its connection URL and setup instructions.
106
+
107
+ Replace its `index.ts` with a view-bound tool like this:
108
+
109
+ <table><tr><td>
110
+ <details>
111
+ <summary><strong><code>index.ts</code></strong> — Server entry file for tool definition and metadata</summary>
112
+
113
+ ```typescript
114
+ import { MCPServer } from "mcp-use";
115
+ import { z } from "zod";
116
+
117
+ const server = new MCPServer({
118
+ name: "weather-app",
119
+ title: "Weather App",
120
+ version: "1.0.0",
121
+ });
122
+
123
+ const weatherInput = z.object({
124
+ city: z.string().describe("City to look up"),
125
+ });
126
+
127
+ const weatherOutput = z.object({
128
+ city: z.string(),
129
+ temperature: z.number(),
130
+ conditions: z.string(),
131
+ });
132
+
133
+ export const getWeather = server.tool(
134
+ {
135
+ name: "get-weather",
136
+ title: "Get weather",
137
+ description: "Get the current weather for a city",
138
+ inputSchema: weatherInput,
139
+ outputSchema: weatherOutput,
140
+ view: { name: "weather-card" },
141
+ annotations: {
142
+ readOnlyHint: true,
143
+ destructiveHint: false,
144
+ openWorldHint: true,
145
+ },
146
+ },
147
+ async ({ city }) => {
148
+ const weather = {
149
+ city,
150
+ temperature: 22,
151
+ conditions: "Sunny",
152
+ };
153
+
154
+ return {
155
+ content: [
156
+ {
157
+ type: "text",
158
+ text: `Weather in ${city}: ${weather.conditions}, ${weather.temperature}°C`,
159
+ },
160
+ ],
161
+ structuredContent: weather,
162
+ };
163
+ },
164
+ );
165
+
166
+ export default server;
167
+ ```
168
+
169
+ </details>
170
+ </td></tr></table>
171
+
172
+ [Explore MCP server tools →](https://mcp-use.com/docs/typescript/server/tools)
173
+
174
+ ## Add Views to your tools
175
+
176
+ Create `views/weather-card/view.tsx`. The directory name matches `view.name` on the tool:
177
+
178
+ <table><tr><td>
179
+ <details>
180
+ <summary><strong><code>view.tsx</code></strong> — Return a view from your tools: React weather card</summary>
181
+
182
+ ```tsx
183
+ import { useCallTool, useToolContext } from "mcp-use/react";
184
+
185
+ export default function WeatherCard() {
186
+ const { status, toolOutput, toolInput } =
187
+ useToolContext<"get-weather">();
188
+ const refresh = useCallTool("get-weather");
189
+
190
+ if (status === "pending") {
191
+ return <p>Checking the weather in {toolInput?.city ?? "your city"}…</p>;
192
+ }
193
+ if (status === "error") return <p>Could not load the weather.</p>;
194
+
195
+ const weather = refresh.data?.structuredContent ?? toolOutput;
196
+
197
+ return (
198
+ <main style={{ padding: 24 }}>
199
+ <h2>{weather.city}</h2>
200
+ <p>
201
+ {weather.temperature}°C · {weather.conditions}
202
+ </p>
203
+ <button
204
+ disabled={refresh.isPending}
205
+ onClick={() => void refresh.callTool({ city: weather.city })}
206
+ >
207
+ {refresh.isPending ? "Refreshing…" : "Refresh"}
208
+ </button>
209
+ {refresh.error && <p>{refresh.error.message}</p>}
210
+ </main>
211
+ );
212
+ }
213
+ ```
214
+
215
+ </details>
216
+ </td></tr></table>
217
+
218
+ <p align="center">
219
+ <img src="./static/readme/chatgpt-hello-world.jpg" alt="Hello World MCP App rendered in a ChatGPT conversation" width="100%" />
220
+ <br />
221
+ <sub>Build interactive UI experiences within ChatGPT with mcp-use.</sub>
222
+ </p>
223
+
224
+ [Build your first MCP App →](https://mcp-use.com/docs/typescript/mcp-apps/quickstart)
225
+
226
+ ## Build
227
+
228
+ Create the production build:
229
+
230
+ ```bash
231
+ npm run build
232
+ ```
233
+
234
+ ## Inspect
235
+
236
+ Start development mode to serve the MCP endpoint at [`http://localhost:3000/mcp`](http://localhost:3000/mcp). The Inspector is automatically available at [`http://localhost:3000/mcp/inspector`](http://localhost:3000/mcp/inspector):
237
+
238
+ ```bash
239
+ npm run dev
240
+ ```
241
+
242
+ <p align="center">
243
+ <img src="./static/readme/inspector-hello-world.jpg" alt="Hello World MCP App rendered in the mcp-use Inspector" width="100%" />
244
+ <br />
245
+ <sub>Invoke tools, validate inputs, and inspect interactive Views in the same development loop.</sub>
246
+ </p>
247
+
248
+ Start a tunnel from the Inspector UI or run `mcp-use dev --tunnel` to get a public URL for your local MCP server and test it with ChatGPT and Claude before deployment. [Learn more about tunneling →](https://docs.mcp-use.com/tunneling)
249
+
250
+ Inspect the same server headlessly from the terminal, invoke representative tools, and capture a View screenshot:
251
+
252
+ ```bash
253
+ npm install --save-dev @mcp-use/client
254
+ npx mcp-use client connect local http://localhost:3000/mcp
255
+ npx mcp-use client local tools list
256
+ npx mcp-use client local tools call get-weather city=Tokyo
257
+ npx mcp-use screenshot \
258
+ --server local \
259
+ --tool get-weather \
260
+ city=Tokyo \
261
+ --output weather-card.png
262
+ ```
263
+
264
+ ## Deploy
265
+
266
+ Ship to [Manufact](https://manufact.com) and get observability, analytics, evals, submission readiness, and Git-based preview environments for free.
267
+
268
+ ```bash
269
+ npm run deploy
270
+ ```
271
+
272
+ Prefer to run it yourself? Follow the [self-hosting guide →](https://mcpuse-codex-v1-v2-docs-split.mintlify.site/v2/typescript/server/deployment/runtime-patterns).
273
+
274
+ ## How mcp-use compares
275
+
276
+ mcp-use builds on the official TypeScript SDK v2 and adds first-class Views, typed tool-to-UI contracts, an optimized stateless runtime, the Inspector, screenshot verification, agent-first CLI workflows, and deployment.
277
+
278
+ ```mermaid
279
+ block-beta
280
+ columns 7
281
+
282
+ metric["Metric"] mcp["mcp-use v2"] fastmcp["FastMCP TS"] official["Official SDK v2*"] xmcp["xmcp"] skybridge["Skybridge"] handler["mcp-handler"]
283
+
284
+ speed["Speed"] speedMcp["10,982 ops/s"] speedFast["6,628 ops/s"] speedOfficial["8,050 ops/s"] speedXmcp["6,585 ops/s"] speedSkybridge["8,116 ops/s"] speedHandler["6,324 ops/s"]
285
+ install["MCP App<br/>dev stack"] installMcp["74.4 MiB"] installFast["122.5 MiB"] installOfficial["99.0 MiB"] installXmcp["121.9 MiB"] installSkybridge["137.5 MiB"] installHandler["388.0 MiB"]
286
+ packages["Installed<br/>packages"] packagesMcp["51"] packagesFast["180"] packagesOfficial["119"] packagesXmcp["171"] packagesSkybridge["300"] packagesHandler["130"]
287
+ views["Views"] viewsMcp["✅"] viewsFast["✅"] viewsOfficial["◐ Extension"] viewsXmcp["✅"] viewsSkybridge["✅"] viewsHandler["❌"]
288
+ nativeViews["Native Views<br/>on MCP 2026"] nativeViewsMcp["✅"] nativeViewsFast["✅"] nativeViewsOfficial["❌"] nativeViewsXmcp["❌"] nativeViewsSkybridge["❌"] nativeViewsHandler["❌"]
289
+ oauth["One-line<br/>OAuth adapters"] oauthMcp["✅"] oauthFast["◐ Provider/proxy"] oauthOfficial["◐ Primitives"] oauthXmcp["✅"] oauthSkybridge["✅"] oauthHandler["❌"]
290
+ protocol["MCP 2026<br/>protocol"] protocolMcp["✅"] protocolFast["✅"] protocolOfficial["✅"] protocolXmcp["❌"] protocolSkybridge["❌"] protocolHandler["❌"]
291
+ screenshot["Built-in View<br/>screenshot CLI"] screenshotMcp["✅"] screenshotFast["❌"] screenshotOfficial["❌"] screenshotXmcp["❌"] screenshotSkybridge["❌"] screenshotHandler["❌"]
292
+ tunnel["Built-in<br/>tunneling"] tunnelMcp["✅"] tunnelFast["❌"] tunnelOfficial["❌"] tunnelXmcp["❌"] tunnelSkybridge["✅"] tunnelHandler["❌"]
293
+ inspector["Built-in<br/>Inspector"] inspectorMcp["✅"] inspectorFast["✅"] inspectorOfficial["❌"] inspectorXmcp["❌"] inspectorSkybridge["◐ Limited"] inspectorHandler["❌"]
294
+
295
+ classDef metricLabel fill:#6e76811a,font-weight:bold
296
+ classDef brand fill:#2ea04333,stroke:#2da44e,stroke-width:3px,font-weight:bold
297
+ classDef header fill:#6e76811a,font-weight:bold
298
+ classDef value fill:#6e76810f,stroke-width:1px
299
+ classDef leader fill:#2ea0432e,stroke:#2da44e,stroke-width:2px,font-weight:bold
300
+ classDef partial fill:#bb80092e,stroke:#bf8700,stroke-width:2px,font-weight:bold
301
+ classDef unavailable fill:#6e76810f,opacity:0.72
302
+
303
+ class metric,speed,install,packages,views,nativeViews,oauth,protocol,screenshot,tunnel,inspector metricLabel
304
+ class mcp brand
305
+ class fastmcp,official,xmcp,skybridge,handler header
306
+ class speedFast,speedOfficial,speedXmcp,speedSkybridge,speedHandler,installFast,installOfficial,installXmcp,installSkybridge,installHandler,packagesFast,packagesOfficial,packagesXmcp,packagesSkybridge,packagesHandler value
307
+ class speedMcp,installMcp,packagesMcp,viewsMcp,viewsFast,viewsXmcp,viewsSkybridge,nativeViewsMcp,nativeViewsFast,oauthMcp,oauthXmcp,oauthSkybridge,protocolMcp,protocolFast,protocolOfficial,screenshotMcp,tunnelMcp,tunnelSkybridge,inspectorMcp,inspectorFast leader
308
+ class oauthFast,viewsOfficial,oauthOfficial,inspectorSkybridge partial
309
+ class viewsHandler,nativeViewsOfficial,nativeViewsXmcp,nativeViewsSkybridge,nativeViewsHandler,oauthHandler,protocolXmcp,protocolSkybridge,protocolHandler,screenshotFast,screenshotOfficial,screenshotXmcp,screenshotSkybridge,screenshotHandler,tunnelFast,tunnelOfficial,tunnelXmcp,tunnelHandler,inspectorOfficial,inspectorXmcp,inspectorHandler unavailable
310
+ ```
311
+
312
+ <sub>* Includes `@modelcontextprotocol/ext-apps`, Vite, and zod for an MCP Apps-capable stack.</sub>
313
+
314
+ <sub>Install rows compare custom React MCP App development stacks. FastMCP therefore includes the Apps extension, React, Vite React plugin, Vite, TypeScript, and zod rather than only its narrower server-side component workflow. Size is actual `node_modules` disk usage after a normal npm install, including required peer dependencies.</sub>
315
+
316
+ **[Read the detailed benchmark report →](./benchmark.md)**
317
+
318
+ ## Examples
319
+
320
+ Remix a complete MCP App, inspect the source, or deploy it as a starting point:
321
+
322
+ | Preview | App | What it demonstrates |
323
+ | --- | --- | --- |
324
+ | <img src="https://raw.githubusercontent.com/mcp-use/mcp-chart-builder/main/repo-assets/demo.gif" alt="Chart Builder demo" width="280"> | [Chart Builder](https://github.com/mcp-use/mcp-chart-builder) | Structured data rendered as interactive charts · [Open demo](https://yellow-shadow-21833.run.mcp-use.com/mcp) |
325
+ | <img src="https://raw.githubusercontent.com/mcp-use/mcp-diagram-builder/main/repo-assets/demo.gif" alt="Diagram Builder demo" width="280"> | [Diagram Builder](https://github.com/mcp-use/mcp-diagram-builder) | Create and edit diagrams through MCP tools · [Open demo](https://lucky-darkness-402ph.run.mcp-use.com/mcp) |
326
+ | <img src="https://raw.githubusercontent.com/mcp-use/mcp-maps-explorer/main/repo-assets/demo.gif" alt="Maps Explorer demo" width="280"> | [Maps Explorer](https://github.com/mcp-use/mcp-maps-explorer) | Search, detail tools, and an interactive map view · [Open demo](https://super-night-ttde2.run.mcp-use.com/mcp) |
327
+
328
+ [Browse all TypeScript examples →](./libraries/typescript/packages/server/examples)
329
+
330
+ ## Ecosystem
331
+
332
+ | Package | Use it for |
333
+ | --- | --- |
334
+ | [`mcp-use`](https://www.npmjs.com/package/mcp-use) | TypeScript v2 server framework, React views, and CLI |
335
+ | [`@mcp-use/client`](https://www.npmjs.com/package/@mcp-use/client) | Connect to MCP servers from Node.js, browsers, React, and sandboxes |
336
+ | [`@mcp-use/agent`](https://www.npmjs.com/package/@mcp-use/agent) | Build model-powered agents on top of MCP clients |
337
+ | [`@mcp-use/inspector`](https://www.npmjs.com/package/@mcp-use/inspector) | Inspect and debug MCP servers and apps |
338
+ | [`create-mcp-use-app`](https://www.npmjs.com/package/create-mcp-use-app) | Scaffold servers and interactive apps |
339
+ | [`mcp-use` for Python](https://pypi.org/project/mcp-use/) | Build Python MCP servers, clients, and agents |
340
+
341
+ - [TypeScript documentation](https://mcp-use.com/docs/typescript)
342
+ - [Python documentation](https://mcp-use.com/docs/python)
343
+ - [Inspector documentation](https://mcp-use.com/docs/inspector/index)
344
+ - [Agent documentation](https://mcp-use.com/docs/typescript/agent/index)
345
+ - [Client documentation](https://mcp-use.com/docs/typescript/client/index)
346
+
347
+ ## Protocol conformance
348
+
349
+ <div align="center">
350
+ <a href="https://github.com/mcp-use/mcp-use/actions/workflows/conformance.yml">
351
+ <img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/tonxxd/6edf670f0446dc9f7a1f32d6bfda2b70/raw/python-conformance.json" alt="Python MCP conformance">
352
+ </a>
353
+ <a href="https://github.com/mcp-use/mcp-use/actions/workflows/conformance.yml">
354
+ <img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/tonxxd/6edf670f0446dc9f7a1f32d6bfda2b70/raw/python-client-conformance.json" alt="Python MCP client conformance">
355
+ </a>
356
+ <a href="https://github.com/mcp-use/mcp-use/actions/workflows/conformance.yml">
357
+ <img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/tonxxd/6edf670f0446dc9f7a1f32d6bfda2b70/raw/typescript-conformance.json" alt="TypeScript MCP conformance">
358
+ </a>
359
+ <a href="https://github.com/mcp-use/mcp-use/actions/workflows/conformance.yml">
360
+ <img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/tonxxd/6edf670f0446dc9f7a1f32d6bfda2b70/raw/typescript-node-client-conformance.json" alt="TypeScript MCP client conformance">
361
+ </a>
362
+ </div>
363
+
364
+ ## Security and community
365
+
366
+ - [Security policy](./SECURITY.md)
367
+ - [Contribution guide](./CONTRIBUTING.md)
368
+ - [GitHub issues](https://github.com/mcp-use/mcp-use/issues)
369
+ - [Discord community](https://discord.gg/XkNkSkMz3V)
370
+ - [Manufact](https://manufact.com)
371
+ - [MIT license](./LICENSE)
372
+
373
+ ## Contributors
374
+
375
+ Built by [Pietro](https://github.com/pietrozullo), [Luigi](https://github.com/pederzh), [Enrico](https://github.com/tonxxd), and the mcp-use community.
376
+
377
+ <a href="https://github.com/mcp-use/mcp-use/graphs/contributors">
378
+ <img src="https://contrib.rocks/image?repo=mcp-use/mcp-use" alt="mcp-use contributors">
379
+ </a>
package/dist/bin.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var{main}=await import("@mcp-use/cli");main(process.argv.slice(2),{frameworkVersion:"2.0.0"}).then(code=>{process.exitCode=code},error=>{console.error(error instanceof Error?error.message:String(error)),process.exitCode=1});
2
+ var{main}=await import("@mcp-use/cli");main(process.argv.slice(2),{frameworkVersion:"2.0.2"}).then(code=>{process.exitCode=code},error=>{console.error(error instanceof Error?error.message:String(error)),process.exitCode=1});
@@ -1,2 +1,2 @@
1
1
  var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId;function getRuntimeId(){return runtimeId??=crypto.randomUUID(),runtimeId}var once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function canPersistTelemetryIdentity(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||!canPersistTelemetryIdentity())return{id:getRuntimeId(),stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
2
- `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.0.0",server_id:resolvedIdentity.id,runtime_id:getRuntimeId(),identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}async function flushUsage(){await Promise.all([...pending])}export{isUsageDisabled,recordUsage,flushUsage};
2
+ `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.0.2",server_id:resolvedIdentity.id,runtime_id:getRuntimeId(),identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}async function flushUsage(){await Promise.all([...pending])}export{isUsageDisabled,recordUsage,flushUsage};
@@ -733,7 +733,7 @@ ${cyan("=".repeat(80))}`),console.log(bold(cyan("[TRACE] Request Details"))),con
733
733
  `)),level==="trace"&&await printTraceDump(response,requestHeaders,requestBody,!isStreamingMethod),response}}function createMcpMount(factory,options={}){let{path="/mcp",handler:handlerOptions,authInfo:getAuthInfo}=options,legacyMode=handlerOptions?.legacy??"stateless",handler=createMcpHandler(factory,{legacy:"stateless",...handlerOptions});return{handler,fetch:async request=>{if(!matchesPath(request,path))return new Response("Not Found",{status:404});if(legacyMode==="stateless"){let method=request.method.toUpperCase();if(method==="GET"||method==="DELETE"||method==="HEAD")return new Response(null,{status:204})}let bag=getRequestBag(request),parsedBody=bag.parsedBody;if(parsedBody===void 0)try{parsedBody=await request.clone().json()}catch{}let capabilities=extractClientCapabilitiesFromBody(parsedBody);capabilities!==void 0&&stashClientCapabilities(request,capabilities);let authInfo=getAuthInfo?.(request)??bag.authInfo,response=await handler.fetch(request,{...parsedBody!==void 0&&{parsedBody},...authInfo!==void 0&&{authInfo}});return response.headers.get("content-type")?.toLowerCase().includes("application/json")?"Bun"in globalThis&&response.body!==null?new Response(await response.arrayBuffer(),{status:response.status,statusText:response.statusText,headers:response.headers}):trackBufferedResponse(request,response):response}}}function createPrefixCompletion(values){let strings=values.map(String);return value=>{let prefix=String(value??"").toLowerCase();return strings.filter(candidate=>candidate.toLowerCase().startsWith(prefix))}}function completable2(schema,complete){return typeof complete=="function"?completable(schema,(value,context)=>complete(String(value??""),context)):completable(schema,createPrefixCompletion(complete))}function normalizeCompletions(completions){let normalized=Object.create(null);for(let[variable,completer]of Object.entries(completions))completer!==void 0&&(normalized[variable]=Array.isArray(completer)?createPrefixCompletion(completer):completer);return normalized}var HTTP_METHODS=["get","put","post","delete","options","head","patch","trace"];function registerOpenAPITools(server,options){let operations=collectOperations(options.spec,options),names=createToolNames(operations),baseUrl=operations.length>0?resolveBaseUrl(options):void 0;for(let[index,operation]of operations.entries()){let name=names[index];if(name===void 0||baseUrl===void 0)continue;let inputBindings=createInputBindings(operation);server.tool({name,description:createToolDescription(operation),inputSchema:createToolInputSchema(options.spec,operation,inputBindings)},async params=>callOpenAPIOperation(operation,params,options,inputBindings,baseUrl))}}function collectOperations(spec,options){let collected=[];for(let[path,pathItemOrRef]of Object.entries(spec.paths??{})){let pathItem=resolveRef(spec,pathItemOrRef);if(pathItem===void 0||isReferenceObject(pathItem))continue;let pathParameters=resolveParameters(spec,pathItem.parameters);for(let method of HTTP_METHODS){let operationOrRef=pathItem[method];if(operationOrRef===void 0)continue;let operation=resolveRef(spec,operationOrRef);if(operation===void 0||isReferenceObject(operation))continue;let operationParameters=resolveParameters(spec,operation.parameters),requestBody=operation.requestBody===void 0?void 0:resolveRef(spec,operation.requestBody),item={method,path,operation,parameters:mergeParameters(pathParameters,operationParameters),...requestBody!==void 0&&!isReferenceObject(requestBody)&&{requestBody}};isIncluded(item,options)&&collected.push(item)}}return collected}function resolveParameters(spec,parameters){let resolved=[];for(let parameter of parameters??[]){let value=resolveRef(spec,parameter);value!==void 0&&!isReferenceObject(value)&&resolved.push(value)}return resolved}function mergeParameters(pathParameters,operationParameters){let merged=new Map;for(let parameter of[...pathParameters,...operationParameters])merged.set(`${parameter.in}:${parameter.name}`,parameter);return[...merged.values()]}function isIncluded(operation,options){if(options.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!options.tags.some(tag=>tags.has(tag)))return!1}return!(options.exclude??[]).some(rule=>matchesExcludeRule(operation,rule))}function matchesExcludeRule(operation,rule){if(rule.method&&rule.method.toLowerCase()!==operation.method||rule.operationId&&!matchesPattern2(rule.operationId,operation.operation.operationId??"")||rule.path&&!matchesPattern2(rule.path,operation.path))return!1;if(rule.tags?.length){let tags=new Set(operation.operation.tags??[]);if(!rule.tags.some(tag=>tags.has(tag)))return!1}return!0}function matchesPattern2(pattern,value){return typeof pattern=="string"?pattern===value:(pattern.lastIndex=0,pattern.test(value))}function createToolNames(operations){let seen=new Map;return operations.map(operation=>{let baseName=slugifyToolName(operation.operation.operationId??`${operation.method}_${operation.path.replace(/[{}]/g,"").replace(/\//g,"_")}`),count=seen.get(baseName)??0;if(seen.set(baseName,count+1),count===0)return baseName;let suffix=`_${count+1}`;return`${baseName.slice(0,64-suffix.length)}${suffix}`})}function createToolDescription(operation){return[operation.operation.summary,operation.operation.description,`HTTP: ${operation.method.toUpperCase()} ${operation.path}`].filter(part=>!!part).join(`
734
734
 
735
735
  `)}function slugifyToolName(value){return value.trim().replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/_+/g,"_").replace(/^_/,"").replace(/_$/,"").slice(0,64)||"openapi_tool"}function createToolInputSchema(spec,operation,inputBindings){let properties={},required2=[];for(let{parameter,inputName}of inputBindings.parameters){let parameterSchema=transformSchema(spec,parameter.schema??{});properties[inputName]={...parameterSchema,description:parameter.description??`${parameter.in} parameter`},(parameter.required||parameter.in==="path")&&required2.push(inputName)}let bodySchema=getJsonRequestBodySchema(operation.requestBody);bodySchema!==void 0&&inputBindings.bodyInputName!==void 0&&(properties[inputBindings.bodyInputName]=transformSchema(spec,bodySchema),operation.requestBody?.required&&required2.push(inputBindings.bodyInputName));let definitions=createSchemaDefinitions(spec),schema={type:"object",properties,additionalProperties:!1,...required2.length>0&&{required:required2},...definitions!==void 0&&{$defs:definitions}};return fromJsonSchema2(schema)}function createInputBindings(operation){let parameters=operation.parameters.filter(parameter=>parameter.in!=="cookie"),bodyInputName=getJsonRequestBodySchema(operation.requestBody)===void 0?void 0:"body",nameCounts=new Map;for(let parameter of parameters)nameCounts.set(parameter.name,(nameCounts.get(parameter.name)??0)+1);let usedNames=new Set(bodyInputName===void 0?[]:[bodyInputName]);return{parameters:parameters.map(parameter=>{let preferredName=(nameCounts.get(parameter.name)??0)>1||parameter.name===bodyInputName?`${parameter.name}_${parameter.in}`:parameter.name;return{parameter,inputName:claimInputName(preferredName,usedNames)}}),...bodyInputName!==void 0&&{bodyInputName}}}function claimInputName(preferredName,usedNames){let inputName=preferredName,suffix=2;for(;usedNames.has(inputName);)inputName=`${preferredName}_${suffix}`,suffix+=1;return usedNames.add(inputName),inputName}function createSchemaDefinitions(spec){let schemas=readRecord(spec.components?.schemas);if(schemas===void 0)return;let definitions={};for(let[name,schema]of Object.entries(schemas))definitions[name]=transformSchemaNode(spec,schema,new Set);return definitions}function transformSchema(spec,schema){let transformed=transformSchemaNode(spec,schema,new Set);return readRecord(transformed)??{}}function transformSchemaNode(spec,value,resolvingRefs){if(Array.isArray(value))return value.map(item=>transformSchemaNode(spec,item,resolvingRefs));let object3=readRecord(value);if(object3===void 0)return value;let ref=typeof object3.$ref=="string"?object3.$ref:void 0,siblings={};for(let[key,child]of Object.entries(object3))key!=="$ref"&&(key==="nullable"&&typeof child=="boolean"||(siblings[key]=transformSchemaNode(spec,child,resolvingRefs)));let transformed=siblings;if(ref!==void 0){let schemaRef=rewriteSchemaRef(spec,ref);if(schemaRef!==void 0)transformed={$ref:schemaRef,...siblings};else if(!resolvingRefs.has(ref)){let resolved=resolveRef(spec,{$ref:ref});if(resolved!==void 0){let nextRefs=new Set(resolvingRefs);nextRefs.add(ref),transformed={...readRecord(transformSchemaNode(spec,resolved,nextRefs))??{},...siblings}}}}return object3.nullable===!0?{anyOf:[transformed,{type:"null"}]}:transformed}function rewriteSchemaRef(spec,ref){let prefix="#/components/schemas/";if(ref.startsWith(prefix))return resolveRef(spec,{$ref:ref})===void 0?void 0:`#/$defs/${ref.slice(prefix.length)}`}function getJsonRequestBodySchema(requestBody){let content=requestBody?.content;if(content!==void 0)return content["application/json"]?.schema??content["application/*+json"]?.schema??Object.entries(content).find(([mediaType])=>mediaType.includes("+json"))?.[1].schema}async function callOpenAPIOperation(operation,params,options,inputBindings,baseUrl){let fetchImpl=options.fetch??globalThis.fetch,url2=buildUrl(operation,params,inputBindings.parameters,baseUrl),headers=buildHeaders(inputBindings.parameters,params,options),bodyInputName=inputBindings.bodyInputName,body=bodyInputName===void 0||params[bodyInputName]===void 0?void 0:JSON.stringify(params[bodyInputName]);body!==void 0&&!hasHeader(headers,"content-type")&&(headers["content-type"]="application/json");let response=await fetchImpl(url2,{method:operation.method.toUpperCase(),headers,...body!==void 0&&{body}}),contentType=response.headers.get("content-type")??"";if(!response.ok)return{content:[{type:"text",text:await response.text()}],isError:!0};if(contentType.includes("application/json")||contentType.includes("+json")){let text2=await response.text();try{let data=JSON.parse(text2);return{content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}catch{return{content:[{type:"text",text:text2}]}}}return{content:[{type:"text",text:await response.text()}]}}function buildUrl(operation,params,parameterBindings,baseUrl){let interpolatedPath=operation.path.replace(/{([^}]+)}/g,(_match,name)=>{let binding=parameterBindings.find(({parameter})=>parameter.in==="path"&&parameter.name===name);return encodeURIComponent(String(binding===void 0?"":params[binding.inputName]??""))}),url2=new URL(interpolatedPath.replace(/^\/+/,""),ensureTrailingSlash(baseUrl));for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="query")continue;let value=params[inputName];value==null||value===""||appendQueryParam(url2,parameter.name,value)}return url2.toString()}function buildHeaders(parameterBindings,params,options){let headers={...options.headers??{}};for(let{parameter,inputName}of parameterBindings){if(parameter.in!=="header")continue;let value=params[inputName];value==null||value===""||(headers[parameter.name]=String(value))}return options.auth?.type==="bearer"&&options.auth.token&&(headers.authorization=`Bearer ${options.auth.token}`),options.auth?.type==="header"&&options.auth.value&&(headers[options.auth.name]=options.auth.value),headers}function resolveBaseUrl(options){let baseUrl=options.baseUrl??options.spec.servers?.[0]?.url;if(baseUrl===void 0||baseUrl.trim()==="")throw new Error("MCPServer.fromOpenAPI requires options.baseUrl or spec.servers[0].url");return baseUrl}function appendQueryParam(url2,name,value){if(Array.isArray(value)){for(let item of value)item!=null&&item!==""&&url2.searchParams.append(name,String(item));return}url2.searchParams.set(name,String(value))}function ensureTrailingSlash(url2){return url2.endsWith("/")?url2:`${url2}/`}function hasHeader(headers,name){return Object.keys(headers).some(headerName=>headerName.toLowerCase()===name)}function isReferenceObject(value){let object3=readRecord(value);return object3!==void 0&&typeof object3.$ref=="string"}function resolveRef(spec,value){if(!isReferenceObject(value))return value;if(!value.$ref.startsWith("#/"))return;let segments=value.$ref.slice(2).split("/").map(segment=>segment.replace(/~1/g,"/").replace(/~0/g,"~")),current=spec;for(let segment of segments){let object3=readRecord(current);if(object3===void 0||!(segment in object3))return;current=object3[segment]}return current}function readRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isLocalhost(url2){let hostname=url2.hostname.toLowerCase();return hostname==="localhost"||hostname.endsWith(".localhost")||hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(hostname)}function parseAbsoluteUrl(value,name){let url2;try{url2=new URL(value)}catch{throw new Error(`${name} must be an absolute URL`)}if(url2.origin==="null"||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute URL without credentials`);return url2}function assertSecureHttpUrl(url2,name){if(url2.protocol!=="https:"&&!(url2.protocol==="http:"&&isLocalhost(url2)))throw new Error(`${name} must use HTTPS, or HTTP for localhost`)}function invalidToken(message,cause){let error3=new OAuthError(OAuthErrorCode.InvalidToken,message);return cause!==void 0&&(error3.cause=cause),error3}function resolveConfiguredOAuthResource(options){let provider=options.provider,basePath=normalizeBasePath(options.basePath);if(provider.resource!==void 0)return validateOAuthResource(provider.resource,basePath);if(options.mcpUrl!==void 0)return validateOAuthResource(appendBasePath(requireAbsoluteOrigin(options.mcpUrl,"MCP_URL"),basePath),basePath)}function resolveLocalOAuthResource(listenOrigin,basePath){let listenOriginUrl=requireAbsoluteOrigin(listenOrigin,"listen origin");if(!isLocalhost(listenOriginUrl))throw new Error("OAuth listen origin must be localhost or a loopback address");return validateOAuthResource(appendBasePath(listenOriginUrl,normalizeBasePath(basePath)),basePath)}function validateOAuthResource(resource2,basePath){let normalizedBasePath=normalizeBasePath(basePath),url2=parseAbsoluteUrl(resource2,"OAuth resource");if(url2.search!==""||url2.hash!=="")throw new Error("OAuth resource must not include a query string or fragment");if(assertSecureHttpUrl(url2,"OAuth resource"),normalizePathname(url2.pathname)!==normalizedBasePath)throw new Error(`OAuth resource path must exactly match basePath (${normalizedBasePath})`);return url2.pathname=normalizedBasePath,url2}function wrapOAuthTokenVerifier(provider,expectedResource){let canonicalResource=normalizeResourceUrl(expectedResource),tokenVerifier=provider.createTokenVerifier(new URL(canonicalResource.href));if(tokenVerifier===null||typeof tokenVerifier!="object"||typeof tokenVerifier.verifyAccessToken!="function")throw new TypeError("OAuth provider createTokenVerifier must return an OAuthTokenVerifier");return{async verifyAccessToken(token){let authInfo=await tokenVerifier.verifyAccessToken(token);assertVerifiedAuthInfo(authInfo),assertResourceBinding(authInfo,canonicalResource);let mapped;try{mapped=provider.mapAuthInfo(authInfo)}catch(error3){throw invalidToken("Token identity mapping failed",error3)}return assertMappedExtra(mapped),{...authInfo,scopes:[...authInfo.scopes],extra:{...authInfo.extra,...mapped}}}}}function assertResourceBinding(authInfo,expectedResource){if(authInfo.resource===void 0)throw invalidToken("Token verifier did not return a validated protected resource");if(parseTokenResource(authInfo.resource).href!==normalizeResourceUrl(expectedResource).href)throw invalidToken("Token resource does not match the protected resource")}function parseTokenResource(value){if(!(value instanceof URL))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");let resource2=value;if(!/^https?:$/.test(resource2.protocol)||resource2.username!==""||resource2.password!==""||resource2.search!==""||resource2.hash!==""||resource2.protocol==="http:"&&!isLocalhost(resource2))throw invalidToken("Token resource must be an absolute HTTPS URL, or HTTP URL for localhost");return normalizeResourceUrl(resource2)}function normalizeResourceUrl(resource2){let normalized=new URL(resource2);return normalized.pathname=normalized.pathname==="/"?"/":normalized.pathname.replace(/\/+$/,""),normalized}function getOAuthProviderOptions(provider){return{oauthMetadata:provider.oauthMetadata,...provider.requiredScopes!==void 0&&{requiredScopes:[...provider.requiredScopes]},...provider.scopesSupported!==void 0&&{scopesSupported:[...provider.scopesSupported]},...provider.resourceName!==void 0&&{resourceName:provider.resourceName},...provider.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:provider.serviceDocumentationUrl}}}function assertVerifiedAuthInfo(authInfo){if(authInfo===null||typeof authInfo!="object"||typeof authInfo.token!="string"||authInfo.token.length===0||typeof authInfo.clientId!="string"||!Array.isArray(authInfo.scopes)||!authInfo.scopes.every(scope=>typeof scope=="string")||typeof authInfo.expiresAt!="number"||!Number.isFinite(authInfo.expiresAt)||authInfo.expiresAt<=Date.now()/1e3)throw invalidToken("Token verifier returned invalid authentication information")}function assertMappedExtra(mapped){if(mapped===null||typeof mapped!="object"||!("user"in mapped)||mapped.user===void 0||!isRecord(mapped.payload)||!Array.isArray(mapped.permissions)||!mapped.permissions.every(permission=>typeof permission=="string"))throw invalidToken("Token identity mapping must return user, payload, and string permissions")}function requireAbsoluteOrigin(value,name){let url2=parseAbsoluteUrl(value,name);if(url2.pathname!=="/"||url2.search!==""||url2.hash!==""||url2.username!==""||url2.password!=="")throw new Error(`${name} must be an absolute origin without a path`);return url2}function appendBasePath(origin,basePath){let resource2=new URL(origin.origin);return resource2.pathname=basePath,resource2}function normalizeBasePath(basePath){if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#"))throw new Error("basePath must be an absolute URL pathname");return normalizePathname(basePath)}function normalizePathname(pathname){if(pathname==="/")return"/";let end=pathname.length;for(;end>0&&pathname.charCodeAt(end-1)===47;)end--;return pathname.slice(0,end)}function oauthMetadata(provider,resource2){let options=getOAuthProviderOptions(provider);return async(request,next)=>{let response=oauthMetadataResponse(request,{oauthMetadata:options.oauthMetadata,resourceServerUrl:resource2,...options.scopesSupported!==void 0&&{scopesSupported:[...options.scopesSupported]},...options.resourceName!==void 0&&{resourceName:options.resourceName},...options.serviceDocumentationUrl!==void 0&&{serviceDocumentationUrl:options.serviceDocumentationUrl}});return response!==void 0?response:next()}}function authInfoFromRequest(request){return getRequestBag(request).authInfo}function resolveToolInputSchema(definition){return definition.inputSchema??definition.schema}var EVENT="mcp_use_sdk_event",ENDPOINT="https://eu.i.posthog.com/i/v0/e/",TOKEN="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI",CONTENT=/(^|_)(arguments?|args|body|command|headers?|location|message|organization|path|query|response|secret|subject|token|uri|url|user_agent)(_|$)/i,RESERVED=new Set("feature action sdk_generation telemetry_schema_version sdk_package sdk_version server_id runtime_id identity_stability distinct_id validation_run_id is_validation".split(" ")),runtimeId;function getRuntimeId(){return runtimeId??=crypto.randomUUID(),runtimeId}var once=new Set,pending=new Set,identities=new Map;function hasControl(value){return[...value].some(character=>{let code=character.charCodeAt(0);return code<32||code===127})}function env(name){return typeof process>"u"?void 0:process.env?.[name]}function safeEnv(name){let value=env(name);return value!==void 0&&value.length>0&&value.length<=128&&!hasControl(value)?value:void 0}function canPersistTelemetryIdentity(){return typeof process>"u"||process.versions?.node===void 0?!1:!("Deno"in globalThis)}function disabled(){if(env("MCP_USE_ANONYMIZED_TELEMETRY")==="false")return!0;try{return globalThis.__MCP_USE_ANONYMIZED_TELEMETRY__===!1||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}catch{return!1}}function isUsageDisabled(){return disabled()}function clean(properties){return Object.fromEntries(Object.entries(properties).filter(([key,value])=>key.length>128||hasControl(key)||key.startsWith("$")||RESERVED.has(key)||CONTENT.test(key)||value===void 0?!1:typeof value=="string"?value.length<=128&&!hasControl(value):typeof value=="boolean"||typeof value=="number"&&Number.isFinite(value)))}async function identity(serverRoot){let projectId=safeEnv("MCP_USE_TELEMETRY_PROJECT_ID");if(projectId!==void 0)return{id:projectId,stability:"project"};if(serverRoot===void 0||!canPersistTelemetryIdentity())return{id:getRuntimeId(),stability:"process"};let existing=identities.get(serverRoot);if(existing!==void 0)return existing;let resolving=(async()=>{try{let fs=await import("fs/promises"),directory=`${serverRoot}/.mcp-use`,file=`${directory}/usage.json`,read=async()=>{try{let value=JSON.parse(await fs.readFile(file,"utf8"));if(typeof value=="object"&&value!==null&&"schemaVersion"in value&&value.schemaVersion===1&&"serverId"in value&&typeof value.serverId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.serverId))return value.serverId}catch{}},stored=await read();if(stored!==void 0)return{id:stored,stability:"server"};await fs.mkdir(directory,{recursive:!0,mode:448});let created=crypto.randomUUID();try{return await fs.writeFile(file,`${JSON.stringify({schemaVersion:1,serverId:created})}
736
- `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.0.0",server_id:resolvedIdentity.id,runtime_id:getRuntimeId(),identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}var registerViews=Symbol("mcp-use/registerViews");function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var VIEW_BOOTSTRAP_STYLE=`<style>
736
+ `,{flag:"wx",mode:384}),{id:created,stability:"server"}}catch{let raced=await read();if(raced!==void 0)return{id:raced,stability:"server"}}}catch{}return{id:getRuntimeId(),stability:"process"}})();return identities.set(serverRoot,resolving),resolving}function capture(feature,action,properties,options,resolveIdentity){let validationId=safeEnv("MCP_USE_TELEMETRY_VALIDATION_ID");if(disabled()||env("NODE_ENV")==="test"&&validationId===void 0||pending.size>=16)return;if(options.onceKey!==void 0){if(once.has(options.onceKey))return;once.add(options.onceKey)}let rate=Math.max(0,Math.min(1,options.sampleRate??1));if(validationId===void 0&&Math.random()>=rate)return;let request=(async()=>{try{let resolvedIdentity=await resolveIdentity(),body=JSON.stringify({api_key:TOKEN,event:EVENT,properties:{...clean(properties),feature,action,sdk_generation:"v2",telemetry_schema_version:2,sdk_package:"mcp-use",sdk_version:"2.0.2",server_id:resolvedIdentity.id,runtime_id:getRuntimeId(),identity_stability:resolvedIdentity.stability,distinct_id:resolvedIdentity.id,sample_rate:validationId===void 0?rate:1,$process_person_profile:!1,$geoip_disable:!0,...validationId!==void 0&&{is_validation:!0,validation_run_id:validationId}}});await fetch(ENDPOINT,{method:"POST",headers:{"content-type":"application/json"},keepalive:!0,body})}catch{return}})();pending.add(request),request.then(()=>pending.delete(request))}function recordUsage(feature,action,properties={},options={}){capture(feature,action,properties,options,()=>identity(options.serverRoot))}var registerViews=Symbol("mcp-use/registerViews");function resolveAssetUrl(assetPath,origin){if(!assetPath.startsWith("/"))throw new Error(`View manifest asset path must be origin-absolute (start with "/"); got ${JSON.stringify(assetPath)}`);return`${origin}${assetPath}`}function viewAssetsBasePath(basePath,viewName){return`${pathUnderBase(basePath,`_mcp-use/views/${viewName}`)}/`}function resolveExternalAssetUrl(assetPath,assetsBase,basePath,viewName){return assetPath.startsWith("http://")||assetPath.startsWith("https://")||assetPath.startsWith("data:")?assetPath:assetPath.startsWith("/")?resolveAssetUrl(assetPath,assetsBase):`${assetsBase}${viewAssetsBasePath(basePath,viewName)}${assetPath.replace(/^\/+/,"")}`}function resolvePublicBase(assetsBase,basePath){return`${assetsBase}${pathUnderBase(basePath,"_mcp-use/public")}/`}function escapeInlineScript(code){return code.replaceAll(/<\/script/gi,"<\\/script").replaceAll("<!--","\\x3C!--")}function escapeInlineStyle(css2){return css2.replaceAll(/<\/style/gi,"<\\/style")}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var VIEW_BOOTSTRAP_STYLE=`<style>
737
737
  html,body,#root{background:transparent}
738
738
  html,body{margin:0}
739
739
  #root[data-mcp-use-loading]{display:flex;min-height:100vh;align-items:center;justify-content:center;flex-direction:column;gap:10px;color:rgba(127,127,127,.9)}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{resolvePublicFilePath,servePublicFile}from"./chunk-ZMU5USAZ.js";import{hasExplicitAssetsBase,originFromAssetsBase,resolveAssetsBase,resolveServerOrigin}from"./chunk-PSKSL567.js";import{registerOpenAPITools}from"./chunk-Y26DNVWA.js";import{completable,normalizeCompletions}from"./chunk-OJF6B5EU.js";import{isUsageDisabled,recordUsage}from"./chunk-273ZVKJJ.js";import{inheritBufferedResponse,toNodeHandler,trackBufferedResponse}from"./chunk-XYHHP43G.js";import{authInfoFromRequest,composeFetch,getOAuthProtectedResourceMetadataUrl,getRequestBag,hostValidationMiddleware,isHtmlNavigationRequest,jsonBodyMiddleware,matchesPath,matchesPathPrefix,oauthMetadata,originValidationMiddleware,pathUnderBase,pathnameOf,requireBearerAuth}from"./chunk-MIZQEWZS.js";import{getOAuthProviderOptions,resolveConfiguredOAuthResource,resolveLocalOAuthResource,wrapOAuthTokenVerifier}from"./chunk-IS7FKXFR.js";import{localhostAllowedHostnames,localhostAllowedOrigins,McpServer as SdkMcpServer,ResourceTemplate,CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY3,CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY3,PROTOCOL_VERSION_META_KEY,isJSONRPCRequest as isJSONRPCRequest2,isInputRequiredResult as isInputRequiredResult2}from"@modelcontextprotocol/server";import{createServer as createNodeHttpServer}from"#mcp-use-node-http";import{Hono}from"hono";var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config){let websiteUrl;if(config.websiteUrl!==void 0){if(typeof config.websiteUrl!="string"||config.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config.websiteUrl}let icons;if(config.icons!==void 0){if(!Array.isArray(config.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config.favicon===void 0?void 0:assertBrandingSource(config.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){if(icons!==void 0)return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function assertServerConfig(config){if(config.basePath!==void 0){if(typeof config.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config.port!==void 0&&(typeof config.port!="number"||!Number.isInteger(config.port)||config.port<0||config.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY2,CLIENT_INFO_META_KEY}from"@modelcontextprotocol/server";import{HonoRequest}from"hono/request";import{CLIENT_CAPABILITIES_META_KEY}from"@modelcontextprotocol/server";var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta=params._meta;if(typeof meta!="object"||meta===null)return;let capabilities=meta[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta){if(meta===void 0)return;let locale=stringValue(meta["openai/locale"])??stringValue(meta["webplus/i18n"]),userAgent=stringValue(meta["openai/userAgent"]),subject=stringValue(meta["openai/subject"]),conversationId=stringValue(meta["openai/session"]),organizationId=stringValue(meta["openai/organization"]),rawLocation=meta["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function toClientContext(ctx){let envelope=ctx.mcpReq.envelope,capabilities={...envelope?.[CLIENT_CAPABILITIES_META_KEY2]??{}},info={...envelope?.[CLIENT_INFO_META_KEY]??{}},user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource}}})}function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),inheritBufferedResponse(response,new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged}))}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}import{CallToolResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"@modelcontextprotocol/core";import{isInputRequiredResult}from"@modelcontextprotocol/server";var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error2){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error2)}}function parseMcpPattern(raw){let pattern=raw.startsWith("mcp:")?raw.slice(4):raw;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw){return raw.startsWith("mcp:")?raw.slice(4):raw}import{CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY2,isJSONRPCRequest}from"@modelcontextprotocol/server";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw==="info"||raw==="debug"||raw==="trace"?raw:configured??"info"}function formatClientInfo(info){if(info!==void 0)return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta=message.params?._meta;if(meta===void 0)return;let info=meta[CLIENT_INFO_META_KEY2];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res){if(!res.body)return{errorMessage:null};let text2;try{text2=await res.clone().text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw=>{try{payloads.push(JSON.parse(raw))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
1
+ import{resolvePublicFilePath,servePublicFile}from"./chunk-ZMU5USAZ.js";import{hasExplicitAssetsBase,originFromAssetsBase,resolveAssetsBase,resolveServerOrigin}from"./chunk-PSKSL567.js";import{registerOpenAPITools}from"./chunk-Y26DNVWA.js";import{completable,normalizeCompletions}from"./chunk-OJF6B5EU.js";import{isUsageDisabled,recordUsage}from"./chunk-HC6D56SW.js";import{inheritBufferedResponse,toNodeHandler,trackBufferedResponse}from"./chunk-XYHHP43G.js";import{authInfoFromRequest,composeFetch,getOAuthProtectedResourceMetadataUrl,getRequestBag,hostValidationMiddleware,isHtmlNavigationRequest,jsonBodyMiddleware,matchesPath,matchesPathPrefix,oauthMetadata,originValidationMiddleware,pathUnderBase,pathnameOf,requireBearerAuth}from"./chunk-MIZQEWZS.js";import{getOAuthProviderOptions,resolveConfiguredOAuthResource,resolveLocalOAuthResource,wrapOAuthTokenVerifier}from"./chunk-IS7FKXFR.js";import{localhostAllowedHostnames,localhostAllowedOrigins,McpServer as SdkMcpServer,ResourceTemplate,CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY3,CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY3,PROTOCOL_VERSION_META_KEY,isJSONRPCRequest as isJSONRPCRequest2,isInputRequiredResult as isInputRequiredResult2}from"@modelcontextprotocol/server";import{createServer as createNodeHttpServer}from"#mcp-use-node-http";import{Hono}from"hono";var FAVICON_CACHE_CONTROL="public, max-age=31536000, immutable",FAVICON_REDIRECT_CACHE_CONTROL="public, max-age=300";function protocolOf(value){return/^([a-z][a-z\d+.-]*):/i.exec(value)?.[1]?.toLowerCase()}function publicAssetPath(basePath,source){return`${basePath==="/"?"":basePath}/_mcp-use/public/${source.split("/").map(segment=>encodeURIComponent(segment)).join("/")}`}function isLocalPublicSource(source){return protocolOf(source)===void 0}function selectFaviconFromIcons(icons){return icons[0]}function assertLocalPublicSource(source,field){if(source.startsWith("/")||source.includes("\\")||source.includes("?")||source.includes("#")||source.split("/").some(segment=>segment===""||segment===".."))throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`)}function parseDataImage(source,field){let comma=source.indexOf(",");if(comma<0)throw new TypeError(`${field} must be a valid image data URL`);let metadata=source.slice(5,comma),payload=source.slice(comma+1),parts=metadata.split(";"),mimeType=parts[0]?.toLowerCase()??"";if(!mimeType.startsWith("image/"))throw new TypeError(`${field} data URL must use an image MIME type`);try{if(parts.includes("base64")){let binary2=atob(payload);return{mimeType,bytes:Uint8Array.from(binary2,character=>character.charCodeAt(0))}}return{mimeType,bytes:new TextEncoder().encode(decodeURIComponent(payload))}}catch{throw new TypeError(`${field} must be a valid image data URL`)}}function assertBrandingSource(source,field){if(typeof source!="string"||source.length===0)throw new TypeError(`${field} must be a non-empty string`);let protocol=protocolOf(source);if(protocol===void 0)return assertLocalPublicSource(source,field),source;if(protocol==="data")return parseDataImage(source,field),source;if(protocol!=="http"&&protocol!=="https")throw new TypeError(`${field} must be an http(s) URL, image data URL, or safe path relative to public/`);try{new URL(source)}catch{throw new TypeError(`${field} must be a valid absolute http(s) URL`)}return source}function normalizeServerBranding(config){let websiteUrl;if(config.websiteUrl!==void 0){if(typeof config.websiteUrl!="string"||config.websiteUrl.length===0)throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");let parsed;try{parsed=new URL(config.websiteUrl)}catch{throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL")}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new TypeError("websiteUrl must be a non-empty absolute http(s) URL");websiteUrl=config.websiteUrl}let icons;if(config.icons!==void 0){if(!Array.isArray(config.icons))throw new TypeError("icons must be an array of MCP Icon objects");icons=Object.freeze(config.icons.map((value,index)=>{if(typeof value!="object"||value===null)throw new TypeError(`icons[${index}] must be an MCP Icon object`);let icon=value,src=assertBrandingSource(icon.src,`icons[${index}].src`),mimeType=icon.mimeType;if(mimeType!==void 0&&(typeof mimeType!="string"||!mimeType.toLowerCase().startsWith("image/")))throw new TypeError(`icons[${index}].mimeType must be an image MIME type when provided`);let sizes=icon.sizes;if(sizes!==void 0&&(!Array.isArray(sizes)||sizes.some(size=>typeof size!="string"||size.length===0)))throw new TypeError(`icons[${index}].sizes must be an array of non-empty strings when provided`);let normalizedSizes=sizes===void 0?void 0:sizes.map(size=>size),theme=icon.theme;if(theme!==void 0&&theme!=="light"&&theme!=="dark")throw new TypeError(`icons[${index}].theme must be "light" or "dark" when provided`);return Object.freeze({src,...mimeType!==void 0&&{mimeType},...normalizedSizes!==void 0&&{sizes:Object.freeze(normalizedSizes)},...theme!==void 0&&{theme}})}))}let explicitFavicon=config.favicon===void 0?void 0:assertBrandingSource(config.favicon,"favicon"),inferred=explicitFavicon===void 0?selectFaviconFromIcons(icons??[]):void 0,favicon=explicitFavicon??inferred?.src,faviconMimeType=inferred?.mimeType??icons?.find(icon=>icon.src===explicitFavicon)?.mimeType;return Object.freeze({...favicon!==void 0&&{favicon},...faviconMimeType!==void 0&&{faviconMimeType},...icons!==void 0&&{icons},...websiteUrl!==void 0&&{websiteUrl}})}function resolveImplementationIcons(icons,request,basePath){if(icons!==void 0)return icons.map(icon=>({...icon,src:request!==void 0&&isLocalPublicSource(icon.src)?`${resolveAssetsBase(request)}${publicAssetPath(basePath,icon.src)}`:icon.src,...icon.sizes!==void 0&&{sizes:[...icon.sizes]}}))}function hasLocalBrandingAsset(branding){return branding.favicon!==void 0&&isLocalPublicSource(branding.favicon)||branding.icons?.some(icon=>isLocalPublicSource(icon.src))===!0}function createFaviconHandler(branding,options){let source=branding.favicon;if(source!==void 0)return async request=>{if(request.method!=="GET"&&request.method!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});if(new URL(request.url).pathname!=="/favicon.ico")return new Response("Not Found",{status:404});let protocol=protocolOf(source);if(protocol==="http"||protocol==="https")return new Response(null,{status:307,headers:{Location:source,"Cache-Control":FAVICON_REDIRECT_CACHE_CONTROL}});if(protocol==="data"){let data=parseDataImage(source,"favicon");return new Response(request.method==="HEAD"?null:data.bytes.buffer,{status:200,headers:{"Content-Type":branding.faviconMimeType??data.mimeType,"Cache-Control":FAVICON_CACHE_CONTROL,"X-Content-Type-Options":"nosniff"}})}let{join}=await import("path"),publicRoot=options.dev?join(options.projectRoot,"public"):join(options.projectRoot,".mcp-use/build/views/public"),diskPath=await resolvePublicFilePath(publicRoot,source);if(diskPath===null)return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});let response=await servePublicFile(diskPath,{...options.deferCors===!0&&{deferCors:!0},...request.method==="HEAD"&&{head:!0}});return response.headers.set("Cache-Control",FAVICON_CACHE_CONTROL),response.headers.set("X-Content-Type-Options","nosniff"),branding.faviconMimeType!==void 0&&response.headers.set("Content-Type",branding.faviconMimeType),response}}function assertServerConfig(config){if(config.basePath!==void 0){if(typeof config.basePath!="string")throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace");let{basePath}=config;if(!basePath.startsWith("/")||basePath.includes("?")||basePath.includes("#")||/\s/.test(basePath)||basePath.includes("//")||basePath.length>1&&basePath.endsWith("/"))throw new TypeError("basePath must be an absolute URL pathname without empty segments, trailing slash, query, fragment, or whitespace")}if(config.port!==void 0&&(typeof config.port!="number"||!Number.isInteger(config.port)||config.port<0||config.port>65535))throw new TypeError("port must be an integer between 0 and 65535")}var DEFAULT_LISTEN_HOST="127.0.0.1";function resolveListenHost(explicitHost,configuredHost,env=process.env){if(explicitHost!==void 0)return explicitHost;let envHost=env.HOST?.trim();return envHost!==void 0&&envHost!==""?envHost:configuredHost??DEFAULT_LISTEN_HOST}function resolveListenPort(explicitPort,configuredPort,env=process.env){if(explicitPort!==void 0)return explicitPort;let envPort=parsePort(env.PORT);return envPort!==void 0?envPort:configuredPort??3e3}function parsePort(value){if(value===void 0||value.trim()==="")return;let port=Number(value);return Number.isInteger(port)&&port>=0&&port<=65535?port:void 0}import{CLIENT_CAPABILITIES_META_KEY as CLIENT_CAPABILITIES_META_KEY2,CLIENT_INFO_META_KEY}from"@modelcontextprotocol/server";import{HonoRequest}from"hono/request";import{CLIENT_CAPABILITIES_META_KEY}from"@modelcontextprotocol/server";var UI_EXTENSION_ID="io.modelcontextprotocol/ui",UI_MIME_TYPE="text/html;profile=mcp-app",UI_RESOURCE_URI_PREFIX="ui://views/";var UI_RESOURCE_URI_META_KEY="ui/resourceUri";function viewResourceUri(viewName){return`${UI_RESOURCE_URI_PREFIX}${viewName}.html`}var clientCapabilitiesByRequest=new WeakMap;function stashClientCapabilities(request,capabilities){clientCapabilitiesByRequest.set(request,capabilities)}function extractClientCapabilitiesFromBody(body){if(typeof body!="object"||body===null)return;let params=body.params;if(typeof params!="object"||params===null)return;let meta=params._meta;if(typeof meta!="object"||meta===null)return;let capabilities=meta[CLIENT_CAPABILITIES_META_KEY];if(!(typeof capabilities!="object"||capabilities===null))return capabilities}function supportsViews(capabilities){let extensions=capabilities?.extensions;if(extensions===void 0)return!1;let uiExtension=extensions[UI_EXTENSION_ID];if(typeof uiExtension!="object"||uiExtension===null)return!1;let mimeTypes=uiExtension.mimeTypes;return Array.isArray(mimeTypes)?mimeTypes.includes(UI_MIME_TYPE):!1}function requireOAuthAuthInfo(authInfo){if(authInfo===void 0||authInfo.extra===void 0||authInfo.expiresAt===void 0)throw new Error("OAuth callback did not receive mapped AuthInfo.extra")}function stringValue(value){return typeof value=="string"?value:void 0}function coordinateValue(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)?value:void 0}function normalizeUserContext(meta){if(meta===void 0)return;let locale=stringValue(meta["openai/locale"])??stringValue(meta["webplus/i18n"]),userAgent=stringValue(meta["openai/userAgent"]),subject=stringValue(meta["openai/subject"]),conversationId=stringValue(meta["openai/session"]),organizationId=stringValue(meta["openai/organization"]),rawLocation=meta["openai/userLocation"],location;if(typeof rawLocation=="object"&&rawLocation!==null&&!Array.isArray(rawLocation)){let values=rawLocation,normalized={city:stringValue(values.city),region:stringValue(values.region),country:stringValue(values.country),timezone:stringValue(values.timezone),latitude:coordinateValue(values.latitude),longitude:coordinateValue(values.longitude)},entries=Object.entries(normalized).filter(entry=>entry[1]!==void 0);entries.length>0&&(location=Object.fromEntries(entries))}if(!(locale===void 0&&userAgent===void 0&&location===void 0&&subject===void 0&&conversationId===void 0&&organizationId===void 0))return{...locale!==void 0&&{locale},...userAgent!==void 0&&{userAgent},...location!==void 0&&{location},...subject!==void 0&&{subject},...conversationId!==void 0&&{conversationId},...organizationId!==void 0&&{organizationId}}}function toClientContext(ctx){let envelope=ctx.mcpReq.envelope,capabilities={...envelope?.[CLIENT_CAPABILITIES_META_KEY2]??{}},info={...envelope?.[CLIENT_INFO_META_KEY]??{}},user=normalizeUserContext(ctx.mcpReq._meta);return{can(capability){return Object.hasOwn(capabilities,capability)},capabilities(){return{...capabilities}},extension(id){let settings=capabilities.extensions?.[id];return settings===void 0?void 0:{...settings}},info(){return{...info}},user(){return user===void 0?void 0:{...user,...user.location!==void 0&&{location:{...user.location}}}},supportsViews(){return supportsViews(capabilities)}}}function toRequestContext(ctx){let rawRequest=ctx.http?.req,http=rawRequest===void 0?void 0:getRequestBag(rawRequest).honoContext,request=http?.req??(rawRequest===void 0?void 0:new HonoRequest(rawRequest)),additions={signal:ctx.mcpReq.signal,...request!==void 0&&{request},...ctx.mcpReq.inputResponses!==void 0&&{inputResponses:ctx.mcpReq.inputResponses},client:toClientContext(ctx),requestState:()=>ctx.mcpReq.requestState(),async sendNotification(method,params){await ctx.mcpReq.notify({method,...params!==void 0&&{params}})},async reportProgress(progress,total,message){let progressToken=ctx.mcpReq._meta?.progressToken;return progressToken===void 0?!1:(await ctx.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,...total!==void 0&&{total},...message!==void 0&&{message}}}),!0)},async sendLog(level,data,logger){await ctx.mcpReq.notify({method:"notifications/message",params:{level,data,...logger!==void 0&&{logger}}})}};return http!==void 0?Object.assign(http,additions):{...additions,...request!==void 0&&{req:request}}}function toAuthenticatedRequestContext(ctx){let authInfo=ctx.http?.authInfo;return requireOAuthAuthInfo(authInfo),Object.assign(toRequestContext(ctx),{auth:{user:authInfo.extra.user,payload:authInfo.extra.payload,accessToken:authInfo.token,scopes:[...authInfo.scopes],permissions:[...authInfo.extra.permissions],...authInfo.clientId.length>0&&{clientId:authInfo.clientId},expiresAt:authInfo.expiresAt,...authInfo.resource!==void 0&&{resource:authInfo.resource}}})}function isReadResourceResult(result){return"contents"in result&&Array.isArray(result.contents)}function isGetPromptResult(result){return"messages"in result&&Array.isArray(result.messages)}function toResourceResult(result,uri){if(isReadResourceResult(result))return result;let mime=result._meta&&typeof result._meta=="object"&&typeof result._meta.mimeType=="string"?result._meta.mimeType:void 0,contents=[];for(let block of result.content??[]){let mapped=contentBlockToResourceContents(block,uri,mime);mapped!==void 0&&contents.push(mapped)}return contents.length===0&&result.structuredContent!==void 0&&contents.push({uri,mimeType:"application/json",text:JSON.stringify(result.structuredContent)}),contents.length===0&&contents.push({uri,mimeType:"text/plain",text:""}),{contents}}function contentBlockToResourceContents(block,uri,mimeHint){if(block.type==="text")return{uri,mimeType:mimeHint??"text/plain",text:block.text};if(block.type==="image"||block.type==="audio")return{uri,mimeType:block.mimeType,blob:block.data};if(block.type==="resource")return{...block.resource}}function toPromptResult(result){if(isGetPromptResult(result))return result;let messages=(result.content??[]).map(content=>({role:"user",content}));return messages.length===0&&result.structuredContent!==void 0&&messages.push({role:"user",content:{type:"text",text:JSON.stringify(result.structuredContent)}}),messages.length===0&&messages.push({role:"user",content:{type:"text",text:""}}),{messages}}var DEFAULT_METHODS=["GET","HEAD","POST","OPTIONS"],DEFAULT_ALLOWED_HEADERS=["Content-Type","Authorization","mcp-protocol-version","mcp-method","mcp-name"];function resolveAllowedOrigin(origin,requestOrigin){return origin===void 0?requestOrigin:typeof origin=="function"?origin(requestOrigin):origin==="*"?"*":Array.isArray(origin)?requestOrigin!==null&&origin.includes(requestOrigin)?requestOrigin:null:origin}function corsHeaders(options,request){if(request.headers.has("Access-Control-Allow-Origin"))return;let requestOrigin=request.headers.get("Origin"),allowedOrigin=resolveAllowedOrigin(options.origin,requestOrigin);if(allowedOrigin===null)return;let headers={"Access-Control-Allow-Origin":allowedOrigin,"Access-Control-Allow-Methods":options.methods.join(", "),"Access-Control-Allow-Headers":options.allowedHeaders.join(", ")};return options.credentials&&(headers["Access-Control-Allow-Credentials"]="true"),allowedOrigin!=="*"&&(headers.Vary="Origin"),headers}function mergeCorsHeaders(response,headers){if(response.headers.has("Access-Control-Allow-Origin"))return response;let merged=new Headers(response.headers);return new Headers(headers).forEach((value,key)=>{merged.set(key,value)}),inheritBufferedResponse(response,new Response(response.body,{status:response.status,statusText:response.statusText,headers:merged}))}function corsFetchMiddleware(options){if(!(options.enabled!==!1))return async(_request,next)=>next();let resolved={...options.origin!==void 0&&{origin:options.origin},methods:options.methods??DEFAULT_METHODS,allowedHeaders:options.allowedHeaders??DEFAULT_ALLOWED_HEADERS,credentials:options.credentials??!1};return async(request,next)=>{let headers=corsHeaders(resolved,request);if(headers===void 0)return next();if(request.method==="OPTIONS")return new Response(null,{status:204,headers});let response=await next();return mergeCorsHeaders(response,headers)}}function isGlobalCorsEnabled(cors){return cors!==void 0&&cors.enabled!==!1}import{CallToolResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListToolsResultSchema,ReadResourceResultSchema}from"@modelcontextprotocol/core";import{isInputRequiredResult}from"@modelcontextprotocol/server";var MCP_MIDDLEWARE_METHODS=["tools/call","tools/list","resources/read","resources/list","prompts/get","prompts/list"];function withMcpMiddlewareParams(request,params){if(typeof request!="object"||request===null||Array.isArray(request))throw new TypeError("[mcp-use] MCP middleware received an invalid downstream request");return{...request,params}}function createMcpMiddlewareEntry(pattern,handler){let normalizedPattern=normalizeMcpMiddlewarePattern(pattern),invoke=handler;if(normalizedPattern!=="*"&&!isMcpMiddlewareMethod(normalizedPattern))throw new TypeError(`Unsupported MCP middleware pattern "${pattern}". Use an exact MCP method or "mcp:*".`);return normalizedPattern==="*"?{pattern:normalizedPattern,handler:async(ctx,next)=>{let downstreamCalled=!1,downstreamResult;if(await invoke(ctx,async()=>{downstreamResult=await next(),downstreamCalled=!0}),!downstreamCalled)throw new Error(`Wildcard MCP middleware "${normalizedPattern}" must call next()`);return downstreamResult}}:{pattern:normalizedPattern,handler:(ctx,next)=>invoke(ctx,next)}}function createMcpEventListenerEntry(pattern,handler){let{pattern:normalizedPattern,phase}=parseMcpPattern(pattern),invoke=handler;return{pattern:normalizedPattern,phase,handler:(ctx,result)=>invoke(ctx,result)}}function matchesPattern(pattern,method){if(pattern==="*")return!0;if(pattern.endsWith("/*")){let prefix=pattern.slice(0,-1);return method.startsWith(prefix)}return pattern===method}function isMcpMiddlewareMethod(value){return MCP_MIDDLEWARE_METHODS.some(method=>method===value)}function composeMiddleware(entries,method,innerFn){let matching=entries.filter(entry=>matchesPattern(entry.pattern,method));return matching.length===0?_ctx=>innerFn():ctx=>{let index=-1,dispatch=i=>i<=index?Promise.reject(new Error("next() called multiple times")):(index=i,i===matching.length?innerFn():matching[i].handler(ctx,()=>dispatch(i+1)));return dispatch(0)}}function freezeMiddlewareContext(ctx){return Object.freeze({method:ctx.method,params:Object.freeze({...ctx.params}),...ctx.request!==void 0&&{request:ctx.request},...ctx.req!==void 0&&{req:ctx.req},...ctx.session!==void 0&&{session:Object.freeze({...ctx.session})},...ctx.auth!==void 0&&{auth:ctx.auth},state:new Map(ctx.state)})}async function runMcpOperation(middlewares,events,method,ctx,innerFn){dispatchMcpEvents(events,method,"before",ctx);let result=await composeMiddleware(middlewares,method,innerFn)(ctx);return assertValidMiddlewareResult(method,result),dispatchMcpEvents(events,method,"complete",ctx,result),result}function assertValidMiddlewareResult(method,result){if((method==="tools/call"||method==="resources/read"||method==="prompts/get")&&isInputRequiredResult(result))return;let validation=(()=>{switch(method){case"tools/call":return assertArrayProperty(method,result,"content"),CallToolResultSchema.safeParse(result);case"tools/list":return assertArrayResult(method,result),ListToolsResultSchema.safeParse({tools:result});case"resources/read":return assertArrayProperty(method,result,"contents"),ReadResourceResultSchema.safeParse(result);case"resources/list":return assertArrayResult(method,result),ListResourcesResultSchema.safeParse({resources:result});case"prompts/get":return assertArrayProperty(method,result,"messages"),GetPromptResultSchema.safeParse(result);case"prompts/list":return assertArrayResult(method,result),ListPromptsResultSchema.safeParse({prompts:result});default:throw new TypeError(`Unsupported MCP middleware method "${method}"`)}})();if(!validation.success)throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: ${validation.error.message}`)}function assertArrayResult(method,result){if(!Array.isArray(result))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected an array`)}function assertArrayProperty(method,result,property){if(typeof result!="object"||result===null||!Array.isArray(result[property]))throw new TypeError(`[mcp-use] ${method} middleware returned an invalid result: expected a ${property} array`)}function dispatchMcpEvents(events,method,phase,ctx,result){let frozen=freezeMiddlewareContext(ctx);for(let entry of events)if(!(entry.phase!==phase||!matchesPattern(entry.pattern,method)))try{entry.handler(frozen,result)}catch(error2){console.error(`[mcp-use] MCP event listener for "${entry.pattern}" (${phase}) threw:`,error2)}}function parseMcpPattern(raw){let pattern=raw.startsWith("mcp:")?raw.slice(4):raw;return pattern.endsWith(":complete")?{pattern:pattern.slice(0,-9),phase:"complete"}:{pattern,phase:"before"}}function normalizeMcpMiddlewarePattern(raw){return raw.startsWith("mcp:")?raw.slice(4):raw}import{CLIENT_INFO_META_KEY as CLIENT_INFO_META_KEY2,isJSONRPCRequest}from"@modelcontextprotocol/server";function colorsEnabled(){return typeof process>"u"||process.env?.NO_COLOR!==void 0?!1:process.stdout?.isTTY===!0}function ansi(open,close){return text2=>colorsEnabled()?`\x1B[${open}m${text2}\x1B[${close}m`:text2}var bold=ansi(1,22),dim=ansi(2,22),red=ansi(31,39),green=ansi(32,39),yellow=ansi(33,39),blue=ansi(34,39),magenta=ansi(35,39),cyan=ansi(36,39),gray=ansi(90,39);function resolveLogLevel(configured){let raw=typeof process>"u"?void 0:process.env?.MCP_USE_LOG_LEVEL?.toLowerCase();return raw==="info"||raw==="debug"||raw==="trace"?raw:configured??"info"}function formatClientInfo(info){if(info!==void 0)return typeof info.version=="string"&&info.version!==""?`${info.name}/${info.version}`:info.name}var detailFormatters={initialize:p=>({subject:formatClientInfo(p.clientInfo)}),ping:()=>({}),"server/discover":()=>({}),"completion/complete":p=>({subject:p.ref.type==="ref/prompt"?p.ref.name:p.ref.uri,input:p.argument}),"logging/setLevel":p=>({subject:p.level}),"prompts/get":p=>({subject:p.name,input:p.arguments}),"prompts/list":()=>({}),"resources/list":()=>({}),"resources/templates/list":()=>({}),"resources/read":p=>({subject:p.uri}),"resources/subscribe":p=>({subject:p.uri}),"resources/unsubscribe":p=>({subject:p.uri}),"subscriptions/listen":()=>({}),"tools/call":p=>({subject:p.name,input:p.arguments}),"tools/list":()=>({}),"sampling/createMessage":()=>({}),"elicitation/create":()=>({}),"roots/list":()=>({})};function isKnownMethod(method){return Object.prototype.hasOwnProperty.call(detailFormatters,method)}function formatDetail(message){if(!isKnownMethod(message.method))return{};try{let formatter=detailFormatters[message.method],detail=formatter(message.params);return typeof detail.subject=="string"||detail.subject===void 0?detail:{}}catch{return{}}}var INLINE_JSON_MAX_LENGTH=80;function inlineJson(value){let text2;try{text2=JSON.stringify(value)??String(value)}catch{text2=String(value)}return text2.length>INLINE_JSON_MAX_LENGTH?`${text2.slice(0,INLINE_JSON_MAX_LENGTH)}...`:text2}function formatClientIdentity(message){let meta=message.params?._meta;if(meta===void 0)return;let info=meta[CLIENT_INFO_META_KEY2];if(!(typeof info!="object"||info===null||typeof info.name!="string"))return formatClientInfo(info)}function sanitize(text2){return text2.replace(/[\u0000-\u001F\u007F-\u009F]+/g," ")}function methodStyle(method){return method.startsWith("tools/")?cyan:method.startsWith("resources/")?green:method.startsWith("prompts/")?magenta:method==="initialize"||method==="ping"?gray:blue}var REDACTED_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key"]);function redactHeaders(headers){return Object.fromEntries(Object.entries(headers).map(([name,value])=>[name,REDACTED_HEADERS.has(name.toLowerCase())?"[REDACTED]":value]))}async function extractResponseOutcome(res){if(!res.body)return{errorMessage:null};let text2;try{text2=await res.clone().text()}catch{return{errorMessage:null}}if(!text2)return{errorMessage:null};let isSse=(res.headers.get("content-type")??"").includes("text/event-stream"),payloads=[],tryParse=raw=>{try{payloads.push(JSON.parse(raw))}catch{}};if(isSse){for(let line of text2.split(/\r?\n/))if(line.startsWith("data:")){let data=line.slice(5).trim();data&&tryParse(data)}}else tryParse(text2);let result;for(let payload of payloads){if(payload===null||typeof payload!="object")continue;let message=payload;if(typeof message.error?.message=="string")return{errorMessage:message.error.message};if(message.result?.isError===!0){let textBlock=(Array.isArray(message.result.content)?message.result.content:[]).find(b=>b?.type==="text"&&typeof b.text=="string");return{errorMessage:textBlock?String(textBlock.text):"tool error"}}"result"in message&&(result=message.result)}return{errorMessage:null,result}}function compactToolResult(result){if(result===null||typeof result!="object")return result;let{structuredContent,content}=result;if(structuredContent!==void 0)return structuredContent;if(Array.isArray(content)){let[block]=content;if(content.length===1&&block?.type==="text")return block.text}return content}function formatForDump(value){function truncate(val){return typeof val=="string"&&val.length>100?`${val.slice(0,100)}...`:Array.isArray(val)?val.map(truncate):val!==null&&typeof val=="object"?Object.fromEntries(Object.entries(val).map(([k,v])=>[k,truncate(v)])):val}try{return JSON.stringify(truncate(value),null,2)}catch{return String(value)}}var DUMP_BODY_MAX_LENGTH=1e4;async function printTraceDump(response,requestHeaders,requestBody,readResponseBody){console.log(`
2
2
  ${cyan("=".repeat(80))}`),console.log(bold(cyan("[TRACE] Request Details"))),console.log(cyan("-".repeat(80))),Object.keys(requestHeaders).length>0&&(console.log(yellow("Request Headers:")),console.log(formatForDump(redactHeaders(requestHeaders)))),requestBody!==void 0&&(console.log(yellow("Request Body:")),console.log(typeof requestBody=="string"?requestBody:formatForDump(requestBody)));let responseHeaders={};if(response.headers.forEach((value,key)=>{responseHeaders[key]=value}),Object.keys(responseHeaders).length>0&&(console.log(yellow("Response Headers:")),console.log(formatForDump(redactHeaders(responseHeaders)))),!readResponseBody)console.log(`${yellow("Response Body:")} (streaming \u2014 not dumped)`);else if(response.body===null)console.log(`${yellow("Response Body:")} (no body)`);else try{let text2=await response.clone().text();if(text2.length===0)console.log(`${yellow("Response Body:")} (empty)`);else{console.log(yellow("Response Body:"));try{console.log(formatForDump(JSON.parse(text2)))}catch{console.log(text2.length>DUMP_BODY_MAX_LENGTH?`${text2.slice(0,DUMP_BODY_MAX_LENGTH)}
3
3
  ... (truncated, ${text2.length-DUMP_BODY_MAX_LENGTH} more characters)`:text2)}}}catch{console.log(`${yellow("Response Body:")} (unable to read)`)}console.log(`${cyan("=".repeat(80))}
4
4
  `)}function styleStatus(status){let text2=String(status);return status>=500?magenta(text2):status>=400?red(text2):status>=300?yellow(text2):green(text2)}function isNoisyRequest(httpMethod,pathname){return httpMethod!=="GET"&&httpMethod!=="HEAD"?!1:pathname.endsWith("/favicon.ico")}function requestLogger(options={}){return options.enabled===!1?(_request,next)=>next():async(request,next)=>{let level=resolveLogLevel(options.level),startedAt=Date.now(),httpMethod=request.method,pathname=new URL(request.url).pathname;if(isNoisyRequest(httpMethod,pathname))return next();let requestHeaders={};level==="trace"&&request.headers.forEach((value,key)=>{requestHeaders[key]=value});let requestBody;if(httpMethod!=="GET"&&httpMethod!=="HEAD"){let parsedBody=getRequestBag(request).parsedBody;if(parsedBody!==void 0)requestBody=parsedBody;else try{requestBody=await request.clone().json()}catch{}}let response=await next(),durationMs=Date.now()-startedAt,timestamp=new Date().toISOString().substring(11,19),mcpRequest=isJSONRPCRequest(requestBody)?requestBody:void 0,isStreamingMethod=mcpRequest?.method==="subscriptions/listen",lines=[[dim(timestamp),bold(httpMethod),pathname,styleStatus(response.status),dim(`in ${durationMs}ms`)].join(" ")];if(mcpRequest!==void 0){let method=sanitize(mcpRequest.method),parts=[` ${methodStyle(method)(method)}`],detail=formatDetail(mcpRequest);detail.subject!==void 0&&parts.push(bold(sanitize(detail.subject)));let echoPayloads=level!=="info";echoPayloads&&detail.input!==void 0&&parts.push(inlineJson(detail.input));let outcome=isStreamingMethod?{errorMessage:null}:await extractResponseOutcome(response);if(echoPayloads&&mcpRequest.method==="tools/call"&&outcome.errorMessage===null&&outcome.result!==void 0&&parts.push(dim("->"),inlineJson(compactToolResult(outcome.result))),mcpRequest.method!=="initialize"){let client=formatClientIdentity(mcpRequest);client!==void 0&&parts.push(dim(sanitize(client)))}outcome.errorMessage!==null?parts.push(red(`ERROR ${sanitize(outcome.errorMessage)}`)):response.status>=400&&parts.push(red(`ERROR (HTTP ${response.status})`)),lines.push(parts.join(" "))}return console.log(lines.join(`
@@ -1 +1 @@
1
- import{flushUsage,isUsageDisabled,recordUsage}from"../chunk-273ZVKJJ.js";export{flushUsage,isUsageDisabled,recordUsage};
1
+ import{flushUsage,isUsageDisabled,recordUsage}from"../chunk-HC6D56SW.js";export{flushUsage,isUsageDisabled,recordUsage};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-use",
3
3
  "type": "module",
4
- "version": "2.0.0",
4
+ "version": "2.0.2",
5
5
  "description": "MCP framework and CLI built on the official v2 SDK",
6
6
  "author": "mcp-use, Inc.",
7
7
  "license": "MIT",
@@ -104,7 +104,7 @@
104
104
  "hono": "^4.12.27",
105
105
  "jose": "^6.1.3",
106
106
  "@mcp-use/cli": "4.0.0",
107
- "@mcp-use/inspector": "20.0.0"
107
+ "@mcp-use/inspector": "20.0.2"
108
108
  },
109
109
  "peerDependencies": {
110
110
  "@mcp-use/client": "^2.0.0",
@@ -139,7 +139,7 @@
139
139
  "vitest": "^4.1.9",
140
140
  "zod": "^4.4.3",
141
141
  "@mcp-use/client": "2.0.0",
142
- "mcp-use": "2.0.0"
142
+ "mcp-use": "2.0.2"
143
143
  },
144
144
  "publishConfig": {
145
145
  "access": "public"