@vitemcp/server 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +25 -0
- package/README.md +2001 -0
- package/dist/OAuthProvider-Cg7nUJJT.d.cts +961 -0
- package/dist/OAuthProvider-Cg7nUJJT.d.ts +961 -0
- package/dist/ViteMCP.cjs +1115 -0
- package/dist/ViteMCP.cjs.map +1 -0
- package/dist/ViteMCP.d.cts +400 -0
- package/dist/ViteMCP.d.ts +400 -0
- package/dist/ViteMCP.js +1115 -0
- package/dist/ViteMCP.js.map +1 -0
- package/dist/auth/index.cjs +55 -0
- package/dist/auth/index.cjs.map +1 -0
- package/dist/auth/index.d.cts +411 -0
- package/dist/auth/index.d.ts +411 -0
- package/dist/auth/index.js +55 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/bin/vitemcp.cjs +237 -0
- package/dist/bin/vitemcp.cjs.map +1 -0
- package/dist/bin/vitemcp.d.cts +1 -0
- package/dist/bin/vitemcp.d.ts +1 -0
- package/dist/bin/vitemcp.js +237 -0
- package/dist/bin/vitemcp.js.map +1 -0
- package/dist/chunk-57MXTIW7.cjs +3119 -0
- package/dist/chunk-57MXTIW7.cjs.map +1 -0
- package/dist/chunk-NZIPGNND.js +3119 -0
- package/dist/chunk-NZIPGNND.js.map +1 -0
- package/dist/edge/index.cjs +115 -0
- package/dist/edge/index.cjs.map +1 -0
- package/dist/edge/index.d.cts +84 -0
- package/dist/edge/index.d.ts +84 -0
- package/dist/edge/index.js +115 -0
- package/dist/edge/index.js.map +1 -0
- package/package.json +152 -0
package/README.md
ADDED
|
@@ -0,0 +1,2001 @@
|
|
|
1
|
+
# ViteMCP
|
|
2
|
+
|
|
3
|
+
A TypeScript framework for building [MCP](https://glama.ai/mcp) servers.
|
|
4
|
+
|
|
5
|
+
> [!IMPORTANT]
|
|
6
|
+
>
|
|
7
|
+
> ViteMCP targets MCP revision **2026-07-28**, which made the protocol
|
|
8
|
+
> stateless. There is no `initialize` handshake and no `Mcp-Session-Id`: every
|
|
9
|
+
> request is self-contained and carries its own protocol version and client
|
|
10
|
+
> capabilities.
|
|
11
|
+
>
|
|
12
|
+
> If you are coming from a session-based version, see
|
|
13
|
+
> [Migrating from the session-based API](#migrating-from-the-session-based-api).
|
|
14
|
+
|
|
15
|
+
## Contents
|
|
16
|
+
|
|
17
|
+
- [Features](#features)
|
|
18
|
+
- [When to use ViteMCP over the official SDK?](#when-to-use-vitemcp-over-the-official-sdk)
|
|
19
|
+
- [Installation](#installation)
|
|
20
|
+
- [Quickstart](#quickstart)
|
|
21
|
+
- [Core Concepts](#core-concepts)
|
|
22
|
+
- [Tools](#tools)
|
|
23
|
+
- [Resources](#resources)
|
|
24
|
+
- [Resource templates](#resource-templates)
|
|
25
|
+
- [Embedded Resources](#embedded-resources)
|
|
26
|
+
- [Prompts](#prompts)
|
|
27
|
+
- [Authentication](#authentication)
|
|
28
|
+
- [Providing Instructions](#providing-instructions)
|
|
29
|
+
- [Multi round-trip requests](#multi-round-trip-requests)
|
|
30
|
+
- [Cacheable results](#cacheable-results)
|
|
31
|
+
- [Client ID Metadata Documents](#client-id-metadata-documents)
|
|
32
|
+
- [Migrating from the session-based API](#migrating-from-the-session-based-api)
|
|
33
|
+
- [Server Features](#server-features)
|
|
34
|
+
- [Logging](#logging)
|
|
35
|
+
- [Custom Logger](#custom-logger)
|
|
36
|
+
- [Errors](#errors)
|
|
37
|
+
- [Progress](#progress)
|
|
38
|
+
- [Health-check Endpoint](#health-check-endpoint)
|
|
39
|
+
- [Deployment](#deployment)
|
|
40
|
+
- [HTTP Streaming](#http-streaming)
|
|
41
|
+
- [Custom HTTP Routes](#custom-http-routes)
|
|
42
|
+
- [Edge Runtime Support](#edge-runtime-support)
|
|
43
|
+
- [Testing and Debugging](#testing-and-debugging)
|
|
44
|
+
- [Unit testing with an in-memory transport](#unit-testing-with-an-in-memory-transport)
|
|
45
|
+
- [Test with `mcp-cli`](#test-with-mcp-cli)
|
|
46
|
+
- [Inspect with `MCP Inspector`](#inspect-with-mcp-inspector)
|
|
47
|
+
- [FAQ](#faq)
|
|
48
|
+
- [How to use with Claude Desktop?](#how-to-use-with-claude-desktop)
|
|
49
|
+
- [How to run ViteMCP behind a proxy?](#how-to-run-vitemcp-behind-a-proxy)
|
|
50
|
+
- [Showcase](#showcase)
|
|
51
|
+
- [Acknowledgements](#acknowledgements)
|
|
52
|
+
|
|
53
|
+
Authentication has a dedicated reference — see the [OAuth guide](docs/oauth.md).
|
|
54
|
+
|
|
55
|
+
## Features
|
|
56
|
+
|
|
57
|
+
- Simple Tool, Resource, Prompt definition
|
|
58
|
+
- [Authentication](#authentication)
|
|
59
|
+
- [Per-request auth context](#authentication)
|
|
60
|
+
- [Image content](#return-types)
|
|
61
|
+
- [Audio content](#return-types)
|
|
62
|
+
- [Embedded](#embedded-resources)
|
|
63
|
+
- [Error handling](#errors)
|
|
64
|
+
- [HTTP Streaming](#http-streaming)
|
|
65
|
+
- [HTTPS Support](#https-support) for secure connections
|
|
66
|
+
- [Custom HTTP routes](#custom-http-routes) for REST APIs, webhooks, and admin interfaces
|
|
67
|
+
- [Edge Runtime Support](#edge-runtime-support) for Cloudflare Workers, Deno Deploy, and more
|
|
68
|
+
- Stateless by construction — every request stands alone, so serverless just works
|
|
69
|
+
- CORS (enabled by default)
|
|
70
|
+
- [Progress notifications](#progress)
|
|
71
|
+
- [Multi round-trip requests](#multi-round-trip-requests) for asking the client for more input
|
|
72
|
+
- [Prompt argument auto-completion](#prompt-argument-auto-completion)
|
|
73
|
+
- [Cacheable list results](#cacheable-results) (`ttlMs` / `cacheScope`)
|
|
74
|
+
- [Health-check endpoint](#health-check-endpoint)
|
|
75
|
+
- [In-memory transport](#unit-testing-with-an-in-memory-transport) for unit testing without binding a port
|
|
76
|
+
- CLI for [testing](#test-with-mcp-cli) and [debugging](#inspect-with-mcp-inspector)
|
|
77
|
+
|
|
78
|
+
## When to use ViteMCP over the official SDK?
|
|
79
|
+
|
|
80
|
+
ViteMCP is built on top of the official SDK.
|
|
81
|
+
|
|
82
|
+
The official SDK provides foundational blocks for building MCPs, but leaves many implementation details to you — all of which [`src/ViteMCP.ts`](src/ViteMCP.ts) handles on your behalf:
|
|
83
|
+
|
|
84
|
+
- Initiating and configuring all the server components
|
|
85
|
+
- Handling of connections
|
|
86
|
+
- Handling of tools
|
|
87
|
+
- Handling of responses
|
|
88
|
+
- Handling of resources
|
|
89
|
+
- Adding prompts, resources and resource templates
|
|
90
|
+
- Embedding resource, image and audio content blocks
|
|
91
|
+
|
|
92
|
+
ViteMCP eliminates this complexity by providing an opinionated framework that:
|
|
93
|
+
|
|
94
|
+
- Handles all the boilerplate automatically
|
|
95
|
+
- Provides simple, intuitive APIs for common tasks
|
|
96
|
+
- Includes built-in best practices and error handling
|
|
97
|
+
- Lets you focus on your MCP's core functionality
|
|
98
|
+
|
|
99
|
+
**When to choose ViteMCP:** You want to build MCP servers quickly without dealing with low-level implementation details.
|
|
100
|
+
|
|
101
|
+
**When to use the official SDK:** You need maximum control or have specific architectural requirements. In this case, we encourage referencing ViteMCP's implementation to avoid common pitfalls.
|
|
102
|
+
|
|
103
|
+
## Installation
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
npm install @vitemcp/server
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Quickstart
|
|
110
|
+
|
|
111
|
+
> [!NOTE]
|
|
112
|
+
>
|
|
113
|
+
> There are many real-world examples of using ViteMCP in the wild. See the [Showcase](#showcase) for examples.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
import { ViteMCP } from "@vitemcp/server";
|
|
117
|
+
import { z } from "zod"; // Or any validation library that supports Standard Schema
|
|
118
|
+
|
|
119
|
+
const server = new ViteMCP({
|
|
120
|
+
name: "My Server",
|
|
121
|
+
version: "1.0.0",
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
server.addTool({
|
|
125
|
+
name: "add",
|
|
126
|
+
description: "Add two numbers",
|
|
127
|
+
parameters: z.object({
|
|
128
|
+
a: z.number(),
|
|
129
|
+
b: z.number(),
|
|
130
|
+
}),
|
|
131
|
+
execute: async (args) => {
|
|
132
|
+
return String(args.a + args.b);
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
server.start({
|
|
137
|
+
transportType: "stdio",
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
_That's it!_ You have a working MCP server.
|
|
142
|
+
|
|
143
|
+
You can test the server in terminal with:
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
git clone https://github.com/vitemcp/vitemcp.git
|
|
147
|
+
cd vitemcp
|
|
148
|
+
|
|
149
|
+
pnpm install
|
|
150
|
+
pnpm build
|
|
151
|
+
|
|
152
|
+
# Test the addition server example using CLI:
|
|
153
|
+
npx @vitemcp/server dev src/examples/addition.ts
|
|
154
|
+
# Test the addition server example using MCP Inspector:
|
|
155
|
+
npx @vitemcp/server inspect src/examples/addition.ts
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
If you are looking for something to start from, [`src/examples/`](src/examples/) has runnable servers covering tools, authentication, custom routes and edge deployment.
|
|
159
|
+
|
|
160
|
+
## Core Concepts
|
|
161
|
+
|
|
162
|
+
### Tools
|
|
163
|
+
|
|
164
|
+
[Tools](https://modelcontextprotocol.io/docs/concepts/tools) in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions.
|
|
165
|
+
|
|
166
|
+
ViteMCP uses the [Standard Schema](https://standardschema.dev) specification for defining tool parameters. This allows you to use your preferred schema validation library (like Zod, ArkType, or Valibot) as long as it implements the spec.
|
|
167
|
+
|
|
168
|
+
**Zod Example:**
|
|
169
|
+
|
|
170
|
+
```typescript
|
|
171
|
+
import { z } from "zod";
|
|
172
|
+
|
|
173
|
+
server.addTool({
|
|
174
|
+
name: "fetch-zod",
|
|
175
|
+
description: "Fetch the content of a url (using Zod)",
|
|
176
|
+
parameters: z.object({
|
|
177
|
+
url: z.string(),
|
|
178
|
+
}),
|
|
179
|
+
execute: async (args) => {
|
|
180
|
+
return await fetchWebpageContent(args.url);
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
**ArkType Example:**
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
import { type } from "arktype";
|
|
189
|
+
|
|
190
|
+
server.addTool({
|
|
191
|
+
name: "fetch-arktype",
|
|
192
|
+
description: "Fetch the content of a url (using ArkType)",
|
|
193
|
+
parameters: type({
|
|
194
|
+
url: "string",
|
|
195
|
+
}),
|
|
196
|
+
execute: async (args) => {
|
|
197
|
+
return await fetchWebpageContent(args.url);
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
**Valibot Example:**
|
|
203
|
+
|
|
204
|
+
Valibot requires the peer dependency @valibot/to-json-schema.
|
|
205
|
+
|
|
206
|
+
```typescript
|
|
207
|
+
import * as v from "valibot";
|
|
208
|
+
|
|
209
|
+
server.addTool({
|
|
210
|
+
name: "fetch-valibot",
|
|
211
|
+
description: "Fetch the content of a url (using Valibot)",
|
|
212
|
+
parameters: v.object({
|
|
213
|
+
url: v.string(),
|
|
214
|
+
}),
|
|
215
|
+
execute: async (args) => {
|
|
216
|
+
return await fetchWebpageContent(args.url);
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
**Plain JSON Schema Example:**
|
|
222
|
+
|
|
223
|
+
If you already have a JSON Schema — from an OpenAPI document, a config file, or
|
|
224
|
+
another server — `jsonSchemaAdapter` wraps it so it can be used directly, with
|
|
225
|
+
no schema library in between.
|
|
226
|
+
|
|
227
|
+
It requires the peer dependency `ajv`, which does the validation, plus
|
|
228
|
+
`ajv-formats` if your schema uses `format` keywords such as `email` or `uri`.
|
|
229
|
+
Both are imported the first time a tool is called, so servers that don't use
|
|
230
|
+
this pay nothing for it.
|
|
231
|
+
|
|
232
|
+
```bash
|
|
233
|
+
npm install ajv ajv-formats
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
import { jsonSchemaAdapter } from "@vitemcp/server";
|
|
238
|
+
|
|
239
|
+
server.addTool({
|
|
240
|
+
name: "fetch-json-schema",
|
|
241
|
+
description: "Fetch the content of a url (using plain JSON Schema)",
|
|
242
|
+
parameters: jsonSchemaAdapter({
|
|
243
|
+
type: "object",
|
|
244
|
+
properties: {
|
|
245
|
+
url: { type: "string", format: "uri" },
|
|
246
|
+
},
|
|
247
|
+
required: ["url"],
|
|
248
|
+
}),
|
|
249
|
+
execute: async (args) => {
|
|
250
|
+
const { url } = args as { url: string };
|
|
251
|
+
return await fetchWebpageContent(url);
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Works for `outputSchema` too. Note that ViteMCP advertises every tool schema
|
|
257
|
+
with `additionalProperties: false` when it has to convert them through
|
|
258
|
+
xsschema (Valibot, and anything else without native JSON Schema output). Zod
|
|
259
|
+
and ArkType emit their own JSON Schema and pass through unchanged — the same
|
|
260
|
+
treatment Zod and Valibot schemas get.
|
|
261
|
+
|
|
262
|
+
Unlike the schema libraries above, a plain JSON Schema carries no TypeScript
|
|
263
|
+
types, so `execute` receives `unknown` arguments. Cast or narrow them yourself.
|
|
264
|
+
|
|
265
|
+
#### Tools Without Parameters
|
|
266
|
+
|
|
267
|
+
When creating tools that don't require parameters, you have two options:
|
|
268
|
+
|
|
269
|
+
1. Omit the parameters property entirely:
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
server.addTool({
|
|
273
|
+
name: "sayHello",
|
|
274
|
+
description: "Say hello",
|
|
275
|
+
// No parameters property
|
|
276
|
+
execute: async () => {
|
|
277
|
+
return "Hello, world!";
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
2. Explicitly define empty parameters:
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
import { z } from "zod";
|
|
286
|
+
|
|
287
|
+
server.addTool({
|
|
288
|
+
name: "sayHello",
|
|
289
|
+
description: "Say hello",
|
|
290
|
+
parameters: z.object({}), // Empty object
|
|
291
|
+
execute: async () => {
|
|
292
|
+
return "Hello, world!";
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
> [!NOTE]
|
|
298
|
+
>
|
|
299
|
+
> Both approaches are fully compatible with all MCP clients, including Cursor. ViteMCP automatically generates the proper schema in both cases.
|
|
300
|
+
|
|
301
|
+
#### Structured Tool Output
|
|
302
|
+
|
|
303
|
+
Tools can declare an `outputSchema` and return structured data. ViteMCP exposes that value as MCP `structuredContent`, while also returning a JSON text fallback for clients that only render text content.
|
|
304
|
+
|
|
305
|
+
```typescript
|
|
306
|
+
server.addTool({
|
|
307
|
+
name: "get-weather",
|
|
308
|
+
description: "Get weather for a city",
|
|
309
|
+
parameters: z.object({
|
|
310
|
+
city: z.string(),
|
|
311
|
+
}),
|
|
312
|
+
outputSchema: z.object({
|
|
313
|
+
temperature: z.number(),
|
|
314
|
+
humidity: z.number(),
|
|
315
|
+
}),
|
|
316
|
+
execute: async ({ city }) => {
|
|
317
|
+
const weather = await getWeather(city);
|
|
318
|
+
|
|
319
|
+
return {
|
|
320
|
+
temperature: weather.temperature,
|
|
321
|
+
humidity: weather.humidity,
|
|
322
|
+
};
|
|
323
|
+
},
|
|
324
|
+
});
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
You can also return explicit text content and structured content together:
|
|
328
|
+
|
|
329
|
+
```typescript
|
|
330
|
+
server.addTool({
|
|
331
|
+
name: "get-weather",
|
|
332
|
+
description: "Get weather for a city",
|
|
333
|
+
parameters: z.object({
|
|
334
|
+
city: z.string(),
|
|
335
|
+
}),
|
|
336
|
+
outputSchema: z.object({
|
|
337
|
+
temperature: z.number(),
|
|
338
|
+
humidity: z.number(),
|
|
339
|
+
}),
|
|
340
|
+
execute: async ({ city }) => {
|
|
341
|
+
const weather = await getWeather(city);
|
|
342
|
+
|
|
343
|
+
return {
|
|
344
|
+
content: [
|
|
345
|
+
{
|
|
346
|
+
type: "text",
|
|
347
|
+
text: `${city}: ${weather.temperature}F`,
|
|
348
|
+
},
|
|
349
|
+
],
|
|
350
|
+
structuredContent: {
|
|
351
|
+
temperature: weather.temperature,
|
|
352
|
+
humidity: weather.humidity,
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
},
|
|
356
|
+
});
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
When `outputSchema` is provided, ViteMCP validates `structuredContent` before sending the tool result. Invalid structured output is returned to the client as a tool error instead of silently violating the advertised schema.
|
|
360
|
+
|
|
361
|
+
#### Restricting who can call a tool
|
|
362
|
+
|
|
363
|
+
A tool's optional `canAccess` receives the request's auth context and returns whether the caller may use it. Tools it rejects are filtered out of `tools/list` entirely.
|
|
364
|
+
|
|
365
|
+
```typescript
|
|
366
|
+
server.addTool({
|
|
367
|
+
name: "admin-tool",
|
|
368
|
+
description: "An admin-only tool",
|
|
369
|
+
canAccess: (auth) => auth?.role === "admin",
|
|
370
|
+
execute: async () => "Welcome, admin!",
|
|
371
|
+
});
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
Built-in helpers — `requireAuth`, `requireScopes`, `requireRole`, `requireAll`, `requireAny` — cover the usual cases; see [Tool Authorization](#tool-authorization).
|
|
375
|
+
|
|
376
|
+
#### Return types
|
|
377
|
+
|
|
378
|
+
`execute` may return a plain string, a content object, or an array of content
|
|
379
|
+
blocks. A bare string is shorthand for a single `text` block — these two are
|
|
380
|
+
equivalent:
|
|
381
|
+
|
|
382
|
+
```js
|
|
383
|
+
execute: async () => "Hello, world!";
|
|
384
|
+
execute: async () => ({ content: [{ type: "text", text: "Hello, world!" }] });
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
| Return value | Produces |
|
|
388
|
+
| ----------------------- | ------------------------------------------------------- |
|
|
389
|
+
| `"some string"` | one `text` block |
|
|
390
|
+
| `{ content: [...] }` | any mix of `text`, `image`, `audio` and resource blocks |
|
|
391
|
+
| `imageContent({ ... })` | one `image` block |
|
|
392
|
+
| `audioContent({ ... })` | one `audio` block |
|
|
393
|
+
|
|
394
|
+
`imageContent` and `audioContent` build a block from a `url`, a `path`, or a
|
|
395
|
+
`buffer` — exactly one of the three. Both accept `timeoutMs` to bound a URL
|
|
396
|
+
download (30 seconds by default).
|
|
397
|
+
|
|
398
|
+
```js
|
|
399
|
+
import { audioContent, imageContent } from "@vitemcp/server";
|
|
400
|
+
|
|
401
|
+
server.addTool({
|
|
402
|
+
name: "fetch-image",
|
|
403
|
+
description: "Fetch an image",
|
|
404
|
+
parameters: z.object({ url: z.string() }),
|
|
405
|
+
execute: async (args) => imageContent({ url: args.url }),
|
|
406
|
+
// ...or imageContent({ path: "/path/to/image.png" })
|
|
407
|
+
// ...or imageContent({ buffer: Buffer.from(base64Png, "base64") })
|
|
408
|
+
});
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
Each helper returns a single block, so combine them under `content` to send
|
|
412
|
+
more than one:
|
|
413
|
+
|
|
414
|
+
```js
|
|
415
|
+
execute: async () => ({
|
|
416
|
+
content: [
|
|
417
|
+
{ type: "text", text: "Here is what I found:" },
|
|
418
|
+
await imageContent({ url: "https://example.com/image.png" }),
|
|
419
|
+
await audioContent({ url: "https://example.com/audio.mp3" }),
|
|
420
|
+
],
|
|
421
|
+
});
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
Raw blocks work too when you already hold base64 data:
|
|
425
|
+
|
|
426
|
+
```js
|
|
427
|
+
execute: async () => ({
|
|
428
|
+
content: [
|
|
429
|
+
{ type: "image", data: base64Png, mimeType: "image/png" },
|
|
430
|
+
{ type: "audio", data: base64Mp3, mimeType: "audio/mpeg" },
|
|
431
|
+
],
|
|
432
|
+
});
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
#### Tool Annotations
|
|
436
|
+
|
|
437
|
+
Tools can include annotations that provide richer context and control by adding metadata about a tool's behavior:
|
|
438
|
+
|
|
439
|
+
```typescript
|
|
440
|
+
server.addTool({
|
|
441
|
+
name: "fetch-content",
|
|
442
|
+
description: "Fetch content from a URL",
|
|
443
|
+
parameters: z.object({
|
|
444
|
+
url: z.string(),
|
|
445
|
+
}),
|
|
446
|
+
annotations: {
|
|
447
|
+
title: "Web Content Fetcher", // Human-readable title for UI display
|
|
448
|
+
readOnlyHint: true, // Tool doesn't modify its environment
|
|
449
|
+
openWorldHint: true, // Tool interacts with external entities
|
|
450
|
+
},
|
|
451
|
+
execute: async (args) => {
|
|
452
|
+
return await fetchWebpageContent(args.url);
|
|
453
|
+
},
|
|
454
|
+
});
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
The available annotations are:
|
|
458
|
+
|
|
459
|
+
| Annotation | Type | Default | Description |
|
|
460
|
+
| :---------------- | :------ | :------ | :----------------------------------------------------------------------------------------------------------------------------------- |
|
|
461
|
+
| `title` | string | - | A human-readable title for the tool, useful for UI display |
|
|
462
|
+
| `readOnlyHint` | boolean | `false` | If true, indicates the tool does not modify its environment |
|
|
463
|
+
| `destructiveHint` | boolean | `true` | If true, the tool may perform destructive updates (only meaningful when `readOnlyHint` is false) |
|
|
464
|
+
| `idempotentHint` | boolean | `false` | If true, calling the tool repeatedly with the same arguments has no additional effect (only meaningful when `readOnlyHint` is false) |
|
|
465
|
+
| `openWorldHint` | boolean | `true` | If true, the tool may interact with an "open world" of external entities |
|
|
466
|
+
|
|
467
|
+
These annotations help clients and LLMs better understand how to use the tools and what to expect when calling them.
|
|
468
|
+
|
|
469
|
+
### Resources
|
|
470
|
+
|
|
471
|
+
[Resources](https://modelcontextprotocol.io/docs/concepts/resources) represent any kind of data that an MCP server wants to make available to clients. This can include:
|
|
472
|
+
|
|
473
|
+
- File contents
|
|
474
|
+
- Screenshots and images
|
|
475
|
+
- Log files
|
|
476
|
+
- And more
|
|
477
|
+
|
|
478
|
+
Each resource is identified by a unique URI and can contain either text or binary data.
|
|
479
|
+
|
|
480
|
+
```ts
|
|
481
|
+
server.addResource({
|
|
482
|
+
uri: "file:///logs/app.log",
|
|
483
|
+
name: "Application Logs",
|
|
484
|
+
mimeType: "text/plain",
|
|
485
|
+
async load() {
|
|
486
|
+
return {
|
|
487
|
+
text: await readLogFile(),
|
|
488
|
+
};
|
|
489
|
+
},
|
|
490
|
+
});
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
> [!NOTE]
|
|
494
|
+
>
|
|
495
|
+
> `load` can return multiple resources. This could be used, for example, to return a list of files inside a directory when the directory is read.
|
|
496
|
+
>
|
|
497
|
+
> ```ts
|
|
498
|
+
> async load() {
|
|
499
|
+
> return [
|
|
500
|
+
> {
|
|
501
|
+
> text: "First file content",
|
|
502
|
+
> },
|
|
503
|
+
> {
|
|
504
|
+
> text: "Second file content",
|
|
505
|
+
> },
|
|
506
|
+
> ];
|
|
507
|
+
> }
|
|
508
|
+
> ```
|
|
509
|
+
|
|
510
|
+
You can also return binary contents in `load`:
|
|
511
|
+
|
|
512
|
+
```ts
|
|
513
|
+
async load() {
|
|
514
|
+
return {
|
|
515
|
+
blob: 'base64-encoded-data'
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
`load` receives a `context` object mirroring what `tool.execute` gets — `auth`, `log`, `requestId` and the multi-round-trip helpers. `reportProgress` is not included, since it is tied to a tool call's progress token:
|
|
521
|
+
|
|
522
|
+
```ts
|
|
523
|
+
server.addResource({
|
|
524
|
+
uri: "file:///logs/app.log",
|
|
525
|
+
name: "Application Logs",
|
|
526
|
+
mimeType: "text/plain",
|
|
527
|
+
async load(context) {
|
|
528
|
+
context.log.info("loading application logs", { requestedBy: auth?.userId });
|
|
529
|
+
|
|
530
|
+
return {
|
|
531
|
+
text: await readLogFile(),
|
|
532
|
+
};
|
|
533
|
+
},
|
|
534
|
+
});
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
### Resource templates
|
|
538
|
+
|
|
539
|
+
You can also define resource templates:
|
|
540
|
+
|
|
541
|
+
```ts
|
|
542
|
+
server.addResourceTemplate({
|
|
543
|
+
uriTemplate: "file:///logs/{name}.log",
|
|
544
|
+
name: "Application Logs",
|
|
545
|
+
mimeType: "text/plain",
|
|
546
|
+
arguments: [
|
|
547
|
+
{
|
|
548
|
+
name: "name",
|
|
549
|
+
description: "Name of the log",
|
|
550
|
+
required: true,
|
|
551
|
+
},
|
|
552
|
+
],
|
|
553
|
+
async load({ name }) {
|
|
554
|
+
return {
|
|
555
|
+
text: `Example log content for ${name}`,
|
|
556
|
+
};
|
|
557
|
+
},
|
|
558
|
+
});
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
Like plain resources, `load` also receives `auth` and `context` as its second and third arguments (see [Resources](#resources)).
|
|
562
|
+
|
|
563
|
+
#### Resource template argument auto-completion
|
|
564
|
+
|
|
565
|
+
Provide `complete` functions for resource template arguments to enable automatic completion:
|
|
566
|
+
|
|
567
|
+
```ts
|
|
568
|
+
server.addResourceTemplate({
|
|
569
|
+
uriTemplate: "file:///logs/{name}.log",
|
|
570
|
+
name: "Application Logs",
|
|
571
|
+
mimeType: "text/plain",
|
|
572
|
+
arguments: [
|
|
573
|
+
{
|
|
574
|
+
name: "name",
|
|
575
|
+
description: "Name of the log",
|
|
576
|
+
required: true,
|
|
577
|
+
complete: async (value) => {
|
|
578
|
+
if (value === "Example") {
|
|
579
|
+
return {
|
|
580
|
+
values: ["Example Log"],
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
return {
|
|
585
|
+
values: [],
|
|
586
|
+
};
|
|
587
|
+
},
|
|
588
|
+
},
|
|
589
|
+
],
|
|
590
|
+
async load({ name }) {
|
|
591
|
+
return {
|
|
592
|
+
text: `Example log content for ${name}`,
|
|
593
|
+
};
|
|
594
|
+
},
|
|
595
|
+
});
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
### Embedded Resources
|
|
599
|
+
|
|
600
|
+
ViteMCP provides a convenient `embedded()` method that simplifies including resources in tool responses. This feature reduces code duplication and makes it easier to reference resources from within tools.
|
|
601
|
+
|
|
602
|
+
#### Basic Usage
|
|
603
|
+
|
|
604
|
+
```js
|
|
605
|
+
server.addTool({
|
|
606
|
+
name: "get_user_data",
|
|
607
|
+
description: "Retrieve user information",
|
|
608
|
+
parameters: z.object({
|
|
609
|
+
userId: z.string(),
|
|
610
|
+
}),
|
|
611
|
+
execute: async (args) => {
|
|
612
|
+
return {
|
|
613
|
+
content: [
|
|
614
|
+
{
|
|
615
|
+
type: "resource",
|
|
616
|
+
resource: await server.embedded(`user://profile/${args.userId}`),
|
|
617
|
+
},
|
|
618
|
+
],
|
|
619
|
+
};
|
|
620
|
+
},
|
|
621
|
+
});
|
|
622
|
+
```
|
|
623
|
+
|
|
624
|
+
#### Working with Resource Templates
|
|
625
|
+
|
|
626
|
+
The `embedded()` method works seamlessly with resource templates:
|
|
627
|
+
|
|
628
|
+
```js
|
|
629
|
+
// Define a resource template
|
|
630
|
+
server.addResourceTemplate({
|
|
631
|
+
uriTemplate: "docs://project/{section}",
|
|
632
|
+
name: "Project Documentation",
|
|
633
|
+
mimeType: "text/markdown",
|
|
634
|
+
arguments: [
|
|
635
|
+
{
|
|
636
|
+
name: "section",
|
|
637
|
+
required: true,
|
|
638
|
+
},
|
|
639
|
+
],
|
|
640
|
+
async load(args) {
|
|
641
|
+
const docs = {
|
|
642
|
+
"getting-started": "# Getting Started\n\nWelcome to our project!",
|
|
643
|
+
"api-reference": "# API Reference\n\nAuthentication is required.",
|
|
644
|
+
};
|
|
645
|
+
return {
|
|
646
|
+
text: docs[args.section] || "Documentation not found",
|
|
647
|
+
};
|
|
648
|
+
},
|
|
649
|
+
});
|
|
650
|
+
|
|
651
|
+
// Use embedded resources in a tool
|
|
652
|
+
server.addTool({
|
|
653
|
+
name: "get_documentation",
|
|
654
|
+
description: "Retrieve project documentation",
|
|
655
|
+
parameters: z.object({
|
|
656
|
+
section: z.enum(["getting-started", "api-reference"]),
|
|
657
|
+
}),
|
|
658
|
+
execute: async (args) => {
|
|
659
|
+
return {
|
|
660
|
+
content: [
|
|
661
|
+
{
|
|
662
|
+
type: "resource",
|
|
663
|
+
resource: await server.embedded(`docs://project/${args.section}`),
|
|
664
|
+
},
|
|
665
|
+
],
|
|
666
|
+
};
|
|
667
|
+
},
|
|
668
|
+
});
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
#### Working with Direct Resources
|
|
672
|
+
|
|
673
|
+
It also works with directly defined resources:
|
|
674
|
+
|
|
675
|
+
```js
|
|
676
|
+
// Define a direct resource
|
|
677
|
+
server.addResource({
|
|
678
|
+
uri: "system://status",
|
|
679
|
+
name: "System Status",
|
|
680
|
+
mimeType: "text/plain",
|
|
681
|
+
async load() {
|
|
682
|
+
return {
|
|
683
|
+
text: "System operational",
|
|
684
|
+
};
|
|
685
|
+
},
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
// Use in a tool
|
|
689
|
+
server.addTool({
|
|
690
|
+
name: "get_system_status",
|
|
691
|
+
description: "Get current system status",
|
|
692
|
+
parameters: z.object({}),
|
|
693
|
+
execute: async () => {
|
|
694
|
+
return {
|
|
695
|
+
content: [
|
|
696
|
+
{
|
|
697
|
+
type: "resource",
|
|
698
|
+
resource: await server.embedded("system://status"),
|
|
699
|
+
},
|
|
700
|
+
],
|
|
701
|
+
};
|
|
702
|
+
},
|
|
703
|
+
});
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
### Prompts
|
|
707
|
+
|
|
708
|
+
[Prompts](https://modelcontextprotocol.io/docs/concepts/prompts) enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions.
|
|
709
|
+
|
|
710
|
+
```ts
|
|
711
|
+
server.addPrompt({
|
|
712
|
+
name: "git-commit",
|
|
713
|
+
description: "Generate a Git commit message",
|
|
714
|
+
arguments: [
|
|
715
|
+
{
|
|
716
|
+
name: "changes",
|
|
717
|
+
description: "Git diff or description of changes",
|
|
718
|
+
required: true,
|
|
719
|
+
},
|
|
720
|
+
],
|
|
721
|
+
load: async (args) => {
|
|
722
|
+
return `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}`;
|
|
723
|
+
},
|
|
724
|
+
});
|
|
725
|
+
```
|
|
726
|
+
|
|
727
|
+
Like resources, `load` also receives `auth` and `context` as its second and third arguments (see [Resources](#resources)):
|
|
728
|
+
|
|
729
|
+
```ts
|
|
730
|
+
server.addPrompt({
|
|
731
|
+
name: "git-commit",
|
|
732
|
+
description: "Generate a Git commit message",
|
|
733
|
+
arguments: [
|
|
734
|
+
{
|
|
735
|
+
name: "changes",
|
|
736
|
+
description: "Git diff or description of changes",
|
|
737
|
+
required: true,
|
|
738
|
+
},
|
|
739
|
+
],
|
|
740
|
+
load: async (args, context) => {
|
|
741
|
+
context.log.debug("generating git commit prompt", { user: auth?.userId });
|
|
742
|
+
|
|
743
|
+
return `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}`;
|
|
744
|
+
},
|
|
745
|
+
});
|
|
746
|
+
```
|
|
747
|
+
|
|
748
|
+
#### Prompt argument auto-completion
|
|
749
|
+
|
|
750
|
+
Prompts can provide auto-completion for their arguments:
|
|
751
|
+
|
|
752
|
+
```js
|
|
753
|
+
server.addPrompt({
|
|
754
|
+
name: "countryPoem",
|
|
755
|
+
description: "Writes a poem about a country",
|
|
756
|
+
load: async ({ name }) => {
|
|
757
|
+
return `Hello, ${name}!`;
|
|
758
|
+
},
|
|
759
|
+
arguments: [
|
|
760
|
+
{
|
|
761
|
+
name: "name",
|
|
762
|
+
description: "Name of the country",
|
|
763
|
+
required: true,
|
|
764
|
+
complete: async (value) => {
|
|
765
|
+
if (value === "Germ") {
|
|
766
|
+
return {
|
|
767
|
+
values: ["Germany"],
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
return {
|
|
772
|
+
values: [],
|
|
773
|
+
};
|
|
774
|
+
},
|
|
775
|
+
},
|
|
776
|
+
],
|
|
777
|
+
});
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
#### Prompt argument auto-completion using `enum`
|
|
781
|
+
|
|
782
|
+
If you provide an `enum` array for an argument, the server will automatically provide completions for the argument.
|
|
783
|
+
|
|
784
|
+
```js
|
|
785
|
+
server.addPrompt({
|
|
786
|
+
name: "countryPoem",
|
|
787
|
+
description: "Writes a poem about a country",
|
|
788
|
+
load: async ({ name }) => {
|
|
789
|
+
return `Hello, ${name}!`;
|
|
790
|
+
},
|
|
791
|
+
arguments: [
|
|
792
|
+
{
|
|
793
|
+
name: "name",
|
|
794
|
+
description: "Name of the country",
|
|
795
|
+
required: true,
|
|
796
|
+
enum: ["Germany", "France", "Italy"],
|
|
797
|
+
},
|
|
798
|
+
],
|
|
799
|
+
});
|
|
800
|
+
```
|
|
801
|
+
|
|
802
|
+
### Authentication
|
|
803
|
+
|
|
804
|
+
ViteMCP supports OAuth 2.1 authentication with pre-configured providers, allowing you to secure your server with minimal setup. This section covers the common cases; the [OAuth guide](docs/oauth.md) is the full reference.
|
|
805
|
+
|
|
806
|
+
#### OAuth with Pre-configured Providers
|
|
807
|
+
|
|
808
|
+
Use the `auth` option with a provider to enable OAuth authentication:
|
|
809
|
+
|
|
810
|
+
```ts
|
|
811
|
+
import {
|
|
812
|
+
ViteMCP,
|
|
813
|
+
getAuthSession,
|
|
814
|
+
GoogleProvider,
|
|
815
|
+
requireAuth,
|
|
816
|
+
} from "@vitemcp/server";
|
|
817
|
+
|
|
818
|
+
const server = new ViteMCP({
|
|
819
|
+
auth: new GoogleProvider({
|
|
820
|
+
baseUrl: "https://your-server.com",
|
|
821
|
+
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
822
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
823
|
+
}),
|
|
824
|
+
name: "My Server",
|
|
825
|
+
version: "1.0.0",
|
|
826
|
+
});
|
|
827
|
+
|
|
828
|
+
server.addTool({
|
|
829
|
+
canAccess: requireAuth,
|
|
830
|
+
description: "Get user profile",
|
|
831
|
+
execute: async (_args, { auth }) => {
|
|
832
|
+
const { accessToken } = getAuthSession(auth);
|
|
833
|
+
const response = await fetch(
|
|
834
|
+
"https://www.googleapis.com/oauth2/v2/userinfo",
|
|
835
|
+
{
|
|
836
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
837
|
+
},
|
|
838
|
+
);
|
|
839
|
+
return JSON.stringify(await response.json());
|
|
840
|
+
},
|
|
841
|
+
name: "get-profile",
|
|
842
|
+
});
|
|
843
|
+
```
|
|
844
|
+
|
|
845
|
+
**Available providers**, all exported from `@vitemcp/server`:
|
|
846
|
+
|
|
847
|
+
| Provider | Use case |
|
|
848
|
+
| :--------------- | :------------------------------------------- |
|
|
849
|
+
| `GoogleProvider` | Google OAuth |
|
|
850
|
+
| `GitHubProvider` | GitHub OAuth |
|
|
851
|
+
| `AzureProvider` | Azure / Entra ID |
|
|
852
|
+
| `OAuthProvider` | Any OAuth 2.0 provider (Auth0, Okta, SAP, …) |
|
|
853
|
+
|
|
854
|
+
`OAuthProvider` takes `authorizationEndpoint` and `tokenEndpoint` in place of a
|
|
855
|
+
provider name. See [Provider setup](docs/oauth.md#provider-setup) for
|
|
856
|
+
registration steps, redirect URIs and scopes for each.
|
|
857
|
+
|
|
858
|
+
#### Tool Authorization
|
|
859
|
+
|
|
860
|
+
`canAccess` decides whether a caller may use a tool; tools it rejects are
|
|
861
|
+
filtered out of `tools/list` entirely. Built-in helpers cover the common cases:
|
|
862
|
+
|
|
863
|
+
```ts
|
|
864
|
+
import {
|
|
865
|
+
getAuthSession,
|
|
866
|
+
requireAll,
|
|
867
|
+
requireAny,
|
|
868
|
+
requireAuth,
|
|
869
|
+
requireRole,
|
|
870
|
+
requireScopes,
|
|
871
|
+
} from "@vitemcp/server";
|
|
872
|
+
|
|
873
|
+
server.addTool({ canAccess: requireAuth, name: "user-tool" /* ... */ });
|
|
874
|
+
server.addTool({
|
|
875
|
+
canAccess: requireScopes("read:user"),
|
|
876
|
+
name: "scoped" /* ... */,
|
|
877
|
+
});
|
|
878
|
+
server.addTool({
|
|
879
|
+
canAccess: requireRole("admin"),
|
|
880
|
+
name: "admin-tool" /* ... */,
|
|
881
|
+
});
|
|
882
|
+
server.addTool({
|
|
883
|
+
canAccess: requireAll(requireAuth, requireRole("admin")),
|
|
884
|
+
name: "admin-only",
|
|
885
|
+
// ...
|
|
886
|
+
});
|
|
887
|
+
server.addTool({
|
|
888
|
+
canAccess: requireAny(requireRole("admin"), requireRole("moderator")),
|
|
889
|
+
name: "staff-tool",
|
|
890
|
+
// ...
|
|
891
|
+
});
|
|
892
|
+
```
|
|
893
|
+
|
|
894
|
+
For anything these do not cover, pass a function — it receives whatever your
|
|
895
|
+
`authenticate` hook returned. Inside `execute`, `getAuthSession` gives
|
|
896
|
+
type-safe access to the session and throws a clear error if the request was
|
|
897
|
+
never authenticated:
|
|
898
|
+
|
|
899
|
+
```ts
|
|
900
|
+
server.addTool({
|
|
901
|
+
canAccess: requireAuth,
|
|
902
|
+
name: "get-profile",
|
|
903
|
+
execute: async (_args, { auth }) => {
|
|
904
|
+
const { accessToken } = getAuthSession(auth);
|
|
905
|
+
// Or, with provider-specific typing:
|
|
906
|
+
// const { accessToken } = getAuthSession<GoogleSession>(auth);
|
|
907
|
+
const response = await fetch("https://api.example.com/user", {
|
|
908
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
909
|
+
});
|
|
910
|
+
return JSON.stringify(await response.json());
|
|
911
|
+
},
|
|
912
|
+
});
|
|
913
|
+
```
|
|
914
|
+
|
|
915
|
+
Reading `auth.accessToken` directly works too, but then handling `undefined` is
|
|
916
|
+
yours. Full detail in [Protecting tools](docs/oauth.md#protecting-tools).
|
|
917
|
+
|
|
918
|
+
#### Custom Authentication
|
|
919
|
+
|
|
920
|
+
For non-OAuth scenarios (API keys, custom tokens), use the `authenticate` option:
|
|
921
|
+
|
|
922
|
+
```ts
|
|
923
|
+
const server = new ViteMCP({
|
|
924
|
+
name: "My Server",
|
|
925
|
+
version: "1.0.0",
|
|
926
|
+
authenticate: (request) => {
|
|
927
|
+
const apiKey = request.headers.get("x-api-key");
|
|
928
|
+
|
|
929
|
+
if (apiKey !== "123") {
|
|
930
|
+
throw new Response(null, {
|
|
931
|
+
status: 401,
|
|
932
|
+
statusText: "Unauthorized",
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
return { id: 1, role: "user" };
|
|
937
|
+
},
|
|
938
|
+
});
|
|
939
|
+
|
|
940
|
+
server.addTool({
|
|
941
|
+
name: "sayHello",
|
|
942
|
+
execute: async (args, { auth }) => {
|
|
943
|
+
return `Hello, ${auth.id}!`;
|
|
944
|
+
},
|
|
945
|
+
});
|
|
946
|
+
```
|
|
947
|
+
|
|
948
|
+
#### OAuth Proxy
|
|
949
|
+
|
|
950
|
+
The `auth` option is backed by ViteMCP's OAuth Proxy, which sits between MCP
|
|
951
|
+
clients and upstream providers. It presents a DCR-compliant face to the client
|
|
952
|
+
while using your pre-registered credentials upstream, and handles the whole
|
|
953
|
+
OAuth 2.1 flow: two-tier PKCE, the consent screen, token exchange and refresh,
|
|
954
|
+
and encrypted storage with token swap.
|
|
955
|
+
|
|
956
|
+
- **Secure by default** — AES-256-GCM storage encryption and the token swap pattern, both on unless you turn them off
|
|
957
|
+
- **Zero configuration** — keys are generated and every `/oauth/*` endpoint is registered for you
|
|
958
|
+
- **Pre-configured providers** — Google, GitHub and Azure, or bring your own
|
|
959
|
+
- **RFC compliant** — DCR (7591), PKCE (7636), Authorization Server Metadata (8414), Issuer Identification (9207), OAuth 2.1
|
|
960
|
+
- **Optional JWKS** — RS256/ES256 verification via the optional `jose` dependency
|
|
961
|
+
|
|
962
|
+
The [OAuth guide](docs/oauth.md) is the complete reference: provider setup,
|
|
963
|
+
configuration, token swap, storage backends, running multiple instances, JWKS
|
|
964
|
+
verification, the production checklist and troubleshooting.
|
|
965
|
+
|
|
966
|
+
#### OAuth Discovery Endpoints
|
|
967
|
+
|
|
968
|
+
ViteMCP also supports OAuth discovery endpoints for direct integration with OAuth providers. These comply with RFC 8414 (OAuth 2.0 Authorization Server Metadata) and RFC 9728 (OAuth 2.0 Protected Resource Metadata):
|
|
969
|
+
|
|
970
|
+
```ts
|
|
971
|
+
import { ViteMCP } from "@vitemcp/server";
|
|
972
|
+
import buildGetJwks from "get-jwks";
|
|
973
|
+
import fastJwt, { type DecodedJwt } from "fast-jwt";
|
|
974
|
+
|
|
975
|
+
const server = new ViteMCP({
|
|
976
|
+
name: "My Server",
|
|
977
|
+
version: "1.0.0",
|
|
978
|
+
oauth: {
|
|
979
|
+
enabled: true,
|
|
980
|
+
authorizationServer: {
|
|
981
|
+
issuer: "https://auth.example.com",
|
|
982
|
+
authorizationEndpoint: "https://auth.example.com/oauth/authorize",
|
|
983
|
+
tokenEndpoint: "https://auth.example.com/oauth/token",
|
|
984
|
+
jwksUri: "https://auth.example.com/.well-known/jwks.json",
|
|
985
|
+
responseTypesSupported: ["code"],
|
|
986
|
+
},
|
|
987
|
+
protectedResource: {
|
|
988
|
+
resource: "mcp://my-server",
|
|
989
|
+
authorizationServers: ["https://auth.example.com"],
|
|
990
|
+
},
|
|
991
|
+
},
|
|
992
|
+
authenticate: async (request) => {
|
|
993
|
+
const authHeader = request.headers.get("authorization");
|
|
994
|
+
|
|
995
|
+
if (!authHeader?.startsWith("Bearer ")) {
|
|
996
|
+
throw new Response(null, {
|
|
997
|
+
status: 401,
|
|
998
|
+
statusText: "Missing or invalid authorization header",
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
const token = authHeader.slice(7); // Remove 'Bearer ' prefix
|
|
1003
|
+
|
|
1004
|
+
// Validate OAuth JWT access token using OpenID Connect discovery
|
|
1005
|
+
try {
|
|
1006
|
+
// Create JWKS client for token verification
|
|
1007
|
+
const getJwks = buildGetJwks();
|
|
1008
|
+
|
|
1009
|
+
// Create JWT verifier
|
|
1010
|
+
const verify = fastJwt.createVerifier({
|
|
1011
|
+
async key({ header }: DecodedJwt) {
|
|
1012
|
+
const publicKey = await getJwks.getPublicKey({
|
|
1013
|
+
kid: header.kid,
|
|
1014
|
+
alg: header.alg,
|
|
1015
|
+
domain: "https://auth.example.com",
|
|
1016
|
+
});
|
|
1017
|
+
return publicKey;
|
|
1018
|
+
},
|
|
1019
|
+
algorithms: ["RS256"],
|
|
1020
|
+
});
|
|
1021
|
+
|
|
1022
|
+
// Verify the JWT token
|
|
1023
|
+
const payload = await verify(token);
|
|
1024
|
+
|
|
1025
|
+
return {
|
|
1026
|
+
userId: payload.sub,
|
|
1027
|
+
scope: payload.scope,
|
|
1028
|
+
email: payload.email,
|
|
1029
|
+
// Include other claims as needed
|
|
1030
|
+
};
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
throw new Response(null, {
|
|
1033
|
+
status: 401,
|
|
1034
|
+
statusText: "Invalid OAuth token",
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
},
|
|
1038
|
+
});
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
If your MCP server is published below an issuer path, configure the HTTP
|
|
1042
|
+
stream base path as well:
|
|
1043
|
+
|
|
1044
|
+
```ts
|
|
1045
|
+
server.start({
|
|
1046
|
+
transportType: "httpStream",
|
|
1047
|
+
httpStream: {
|
|
1048
|
+
basePath: "/issuer1",
|
|
1049
|
+
endpoint: "/mcp",
|
|
1050
|
+
port: 8080,
|
|
1051
|
+
},
|
|
1052
|
+
});
|
|
1053
|
+
```
|
|
1054
|
+
|
|
1055
|
+
With this configuration, ViteMCP serves the issuer-path authorization server
|
|
1056
|
+
metadata at `/.well-known/oauth-authorization-server/issuer1`, while protected
|
|
1057
|
+
resource metadata remains available for the MCP endpoint at
|
|
1058
|
+
`/.well-known/oauth-protected-resource/issuer1/mcp`.
|
|
1059
|
+
|
|
1060
|
+
This configuration automatically exposes OAuth discovery endpoints:
|
|
1061
|
+
|
|
1062
|
+
- `/.well-known/oauth-authorization-server` - Authorization server metadata (RFC 8414)
|
|
1063
|
+
- `/.well-known/oauth-authorization-server<basePath>` - Authorization server metadata when `httpStream.basePath` is set (RFC 8414 Section 3)
|
|
1064
|
+
- `/.well-known/oauth-protected-resource` - Protected resource metadata (RFC 9728)
|
|
1065
|
+
- `/.well-known/oauth-protected-resource<endpoint>` - Protected resource metadata at sub-path
|
|
1066
|
+
|
|
1067
|
+
**Discovery Mechanism:**
|
|
1068
|
+
|
|
1069
|
+
Clients discover protected resource metadata using the following search order:
|
|
1070
|
+
|
|
1071
|
+
1. **WWW-Authenticate header** - Primary method (handled automatically by mcp-proxy)
|
|
1072
|
+
2. **Sub-path well-known** - `/.well-known/oauth-protected-resource<endpoint>` (e.g., `/.well-known/oauth-protected-resource/mcp`)
|
|
1073
|
+
3. **Root well-known** - `/.well-known/oauth-protected-resource` (fallback)
|
|
1074
|
+
|
|
1075
|
+
Both the sub-path and root endpoints return identical metadata, ensuring compatibility with all MCP client implementations.
|
|
1076
|
+
|
|
1077
|
+
For JWT token validation, you can use libraries like [`get-jwks`](https://github.com/nearform/get-jwks) and [`fast-jwt`](https://github.com/nearform/fast-jwt) for OAuth JWT tokens.
|
|
1078
|
+
|
|
1079
|
+
#### Passing Headers Through Context
|
|
1080
|
+
|
|
1081
|
+
If you are exposing your MCP server via HTTP, you may wish to allow clients to supply sensitive keys via headers, which can then be passed along to APIs that your tools interact with, allowing each client to supply their own API keys. This can be done by capturing the HTTP headers in the `authenticate` section and storing them in the session to be referenced by the tools later.
|
|
1082
|
+
|
|
1083
|
+
```ts
|
|
1084
|
+
import { ViteMCP } from "@vitemcp/server";
|
|
1085
|
+
import { IncomingHttpHeaders } from "http";
|
|
1086
|
+
|
|
1087
|
+
// Define the session data type
|
|
1088
|
+
interface SessionData {
|
|
1089
|
+
headers: IncomingHttpHeaders;
|
|
1090
|
+
[key: string]: unknown; // Add index signature to satisfy Record<string, unknown>
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
// Create a server instance
|
|
1094
|
+
const server = new ViteMCP({
|
|
1095
|
+
name: "My Server",
|
|
1096
|
+
version: "1.0.0",
|
|
1097
|
+
authenticate: async (request: any): Promise<SessionData> => {
|
|
1098
|
+
// Authentication logic
|
|
1099
|
+
return {
|
|
1100
|
+
headers: request.headers,
|
|
1101
|
+
};
|
|
1102
|
+
},
|
|
1103
|
+
});
|
|
1104
|
+
|
|
1105
|
+
// Tool to display HTTP headers
|
|
1106
|
+
server.addTool({
|
|
1107
|
+
name: "headerTool",
|
|
1108
|
+
description: "Reads HTTP headers from the request",
|
|
1109
|
+
execute: async (args: any, context: any) => {
|
|
1110
|
+
const session = context.session as SessionData;
|
|
1111
|
+
const headers = session?.headers ?? {};
|
|
1112
|
+
|
|
1113
|
+
const getHeaderString = (header: string | string[] | undefined) =>
|
|
1114
|
+
Array.isArray(header) ? header.join(", ") : (header ?? "N/A");
|
|
1115
|
+
|
|
1116
|
+
const userAgent = getHeaderString(headers["user-agent"]);
|
|
1117
|
+
const authorization = getHeaderString(headers["authorization"]);
|
|
1118
|
+
return `User-Agent: ${userAgent}\nAuthorization: ${authorization}\nAll Headers: ${JSON.stringify(headers, null, 2)}`;
|
|
1119
|
+
},
|
|
1120
|
+
});
|
|
1121
|
+
|
|
1122
|
+
// Start the server
|
|
1123
|
+
server.start({
|
|
1124
|
+
transportType: "httpStream",
|
|
1125
|
+
httpStream: {
|
|
1126
|
+
port: 8080,
|
|
1127
|
+
},
|
|
1128
|
+
});
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
A client that would connect to this may look something like this:
|
|
1132
|
+
|
|
1133
|
+
```ts
|
|
1134
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
1135
|
+
import { Client } from "@modelcontextprotocol/client";
|
|
1136
|
+
|
|
1137
|
+
const transport = new StreamableHTTPClientTransport(
|
|
1138
|
+
new URL(`http://localhost:8080/mcp`),
|
|
1139
|
+
{
|
|
1140
|
+
requestInit: {
|
|
1141
|
+
headers: {
|
|
1142
|
+
Authorization: "Test 123",
|
|
1143
|
+
},
|
|
1144
|
+
},
|
|
1145
|
+
},
|
|
1146
|
+
);
|
|
1147
|
+
|
|
1148
|
+
const client = new Client({
|
|
1149
|
+
name: "example-client",
|
|
1150
|
+
version: "1.0.0",
|
|
1151
|
+
});
|
|
1152
|
+
|
|
1153
|
+
(async () => {
|
|
1154
|
+
await client.connect(transport);
|
|
1155
|
+
|
|
1156
|
+
// Call a tool
|
|
1157
|
+
const result = await client.callTool({
|
|
1158
|
+
name: "headerTool",
|
|
1159
|
+
arguments: {
|
|
1160
|
+
arg1: "value",
|
|
1161
|
+
},
|
|
1162
|
+
});
|
|
1163
|
+
|
|
1164
|
+
console.log("Tool result:", result);
|
|
1165
|
+
})().catch(console.error);
|
|
1166
|
+
```
|
|
1167
|
+
|
|
1168
|
+
What would show up in the console after the client runs is something like this:
|
|
1169
|
+
|
|
1170
|
+
```
|
|
1171
|
+
Tool result: {
|
|
1172
|
+
content: [
|
|
1173
|
+
{
|
|
1174
|
+
type: 'text',
|
|
1175
|
+
text: 'User-Agent: node\n' +
|
|
1176
|
+
'Authorization: Test 123\n' +
|
|
1177
|
+
'All Headers: {\n' +
|
|
1178
|
+
' "host": "localhost:8080",\n' +
|
|
1179
|
+
' "connection": "keep-alive",\n' +
|
|
1180
|
+
' "authorization": "Test 123",\n' +
|
|
1181
|
+
' "content-type": "application/json",\n' +
|
|
1182
|
+
' "accept": "application/json, text/event-stream",\n' +
|
|
1183
|
+
' "accept-language": "*",\n' +
|
|
1184
|
+
' "sec-fetch-mode": "cors",\n' +
|
|
1185
|
+
' "user-agent": "node",\n' +
|
|
1186
|
+
' "accept-encoding": "gzip, deflate",\n' +
|
|
1187
|
+
' "content-length": "163"\n' +
|
|
1188
|
+
'}'
|
|
1189
|
+
}
|
|
1190
|
+
]
|
|
1191
|
+
}
|
|
1192
|
+
```
|
|
1193
|
+
|
|
1194
|
+
### Providing Instructions
|
|
1195
|
+
|
|
1196
|
+
You can provide instructions to the server using the `instructions` option:
|
|
1197
|
+
|
|
1198
|
+
```ts
|
|
1199
|
+
const server = new ViteMCP({
|
|
1200
|
+
name: "My Server",
|
|
1201
|
+
version: "1.0.0",
|
|
1202
|
+
instructions:
|
|
1203
|
+
'Instructions describing how to use the server and its features.\n\nThis can be used by clients to improve the LLM\'s understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.',
|
|
1204
|
+
});
|
|
1205
|
+
```
|
|
1206
|
+
|
|
1207
|
+
### Multi round-trip requests
|
|
1208
|
+
|
|
1209
|
+
On the stateless protocol a server cannot pause mid-execution and ask the
|
|
1210
|
+
client a question — there is no session to hold the suspended call. Instead the
|
|
1211
|
+
handler _returns_ a request for more input, and the client re-issues the whole
|
|
1212
|
+
call with the answers attached.
|
|
1213
|
+
|
|
1214
|
+
```ts
|
|
1215
|
+
import { z } from "zod";
|
|
1216
|
+
|
|
1217
|
+
const confirmSchema = z.object({ confirmed: z.boolean() });
|
|
1218
|
+
|
|
1219
|
+
server.addTool({
|
|
1220
|
+
name: "delete-everything",
|
|
1221
|
+
parameters: z.object({ target: z.string() }),
|
|
1222
|
+
execute: async ({ target }, ctx) => {
|
|
1223
|
+
if (!ctx.inputResponses) {
|
|
1224
|
+
return ctx.inputRequired(
|
|
1225
|
+
{
|
|
1226
|
+
confirm: ctx.elicit({
|
|
1227
|
+
message: `Really delete ${target}?`,
|
|
1228
|
+
requestedSchema: confirmSchema,
|
|
1229
|
+
}),
|
|
1230
|
+
},
|
|
1231
|
+
// Optional opaque state, echoed back verbatim on the retry.
|
|
1232
|
+
JSON.stringify({ target }),
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
const answer = ctx.input("confirm", confirmSchema);
|
|
1237
|
+
return answer?.confirmed ? `Deleted ${target}` : "Cancelled";
|
|
1238
|
+
},
|
|
1239
|
+
});
|
|
1240
|
+
```
|
|
1241
|
+
|
|
1242
|
+
A complete worked version, including HMAC-signing `requestState` and
|
|
1243
|
+
distinguishing "declined" from "answered no", is in
|
|
1244
|
+
[`src/examples/multi-round-trip.ts`](src/examples/multi-round-trip.ts). Per-request
|
|
1245
|
+
auth is demonstrated in [`src/examples/auth-context.ts`](src/examples/auth-context.ts).
|
|
1246
|
+
|
|
1247
|
+
Three consequences worth internalising:
|
|
1248
|
+
|
|
1249
|
+
- **Handlers are re-entrant.** `execute` runs again from the top on the retry.
|
|
1250
|
+
Do not do irreversible work before you have the input you need.
|
|
1251
|
+
- **`requestState` is attacker-controlled on the way back.** It round-trips
|
|
1252
|
+
through the client. If it influences authorization or resource access, sign
|
|
1253
|
+
or encrypt it and reject anything that fails verification — ViteMCP does not
|
|
1254
|
+
do that for you.
|
|
1255
|
+
- **`ctx.input()` returns `undefined` when the client declined**, which is not
|
|
1256
|
+
the same as the user answering "no". Handle the two separately, or a decline
|
|
1257
|
+
silently reads as a negative answer.
|
|
1258
|
+
|
|
1259
|
+
### Cacheable results
|
|
1260
|
+
|
|
1261
|
+
`tools/list`, `prompts/list`, `resources/list`, `resources/templates/list` and
|
|
1262
|
+
`resources/read` carry cache hints on this revision. Set them per resource:
|
|
1263
|
+
|
|
1264
|
+
```ts
|
|
1265
|
+
server.addResource({
|
|
1266
|
+
name: "Changelog",
|
|
1267
|
+
uri: "docs://changelog",
|
|
1268
|
+
cache: { cacheScope: "public", ttlMs: 60_000 },
|
|
1269
|
+
load: async () => ({ text: await readChangelog() }),
|
|
1270
|
+
});
|
|
1271
|
+
```
|
|
1272
|
+
|
|
1273
|
+
`cacheScope: "private"` restricts caching to the requesting client; `"public"`
|
|
1274
|
+
permits shared intermediaries.
|
|
1275
|
+
|
|
1276
|
+
### Client ID Metadata Documents
|
|
1277
|
+
|
|
1278
|
+
Dynamic Client Registration is deprecated on this revision. The replacement is
|
|
1279
|
+
Client ID Metadata Documents: a client identifies itself with an HTTPS URL that
|
|
1280
|
+
serves a JSON document describing it, so no registration step is needed and the
|
|
1281
|
+
identity is portable across authorization servers.
|
|
1282
|
+
|
|
1283
|
+
ViteMCP's OAuth proxy resolves URL-formatted `client_id`s automatically and
|
|
1284
|
+
advertises `client_id_metadata_document_supported` in its metadata. A client
|
|
1285
|
+
document looks like this:
|
|
1286
|
+
|
|
1287
|
+
```json
|
|
1288
|
+
{
|
|
1289
|
+
"client_id": "https://app.example.com/oauth/client.json",
|
|
1290
|
+
"client_name": "Example MCP Client",
|
|
1291
|
+
"redirect_uris": ["http://127.0.0.1:3000/callback"],
|
|
1292
|
+
"grant_types": ["authorization_code"],
|
|
1293
|
+
"response_types": ["code"]
|
|
1294
|
+
}
|
|
1295
|
+
```
|
|
1296
|
+
|
|
1297
|
+
> [!WARNING]
|
|
1298
|
+
>
|
|
1299
|
+
> Resolving a URL-formatted `client_id` means **your server fetches a URL an
|
|
1300
|
+
> unauthenticated caller chose** — a server-side request forgery surface. The
|
|
1301
|
+
> resolver defends it by refusing non-HTTPS URLs and bare origins, refusing
|
|
1302
|
+
> addresses that resolve into private, loopback, link-local or CGNAT ranges
|
|
1303
|
+
> (including `169.254.169.254`, the cloud instance-metadata endpoint), not
|
|
1304
|
+
> following redirects, and capping both response size and time.
|
|
1305
|
+
>
|
|
1306
|
+
> The address check runs inside the connection's own DNS lookup, so a name that
|
|
1307
|
+
> resolves publicly during validation and internally at connect time — DNS
|
|
1308
|
+
> rebinding — is still refused.
|
|
1309
|
+
|
|
1310
|
+
Narrow it further with a trust policy, or turn it off:
|
|
1311
|
+
|
|
1312
|
+
```ts
|
|
1313
|
+
const authProxy = new OAuthProxy({
|
|
1314
|
+
// ...
|
|
1315
|
+
clientIdMetadata: {
|
|
1316
|
+
allowedDomains: ["app.example.com", ".trusted-partner.com"],
|
|
1317
|
+
fetchTimeoutMs: 3000,
|
|
1318
|
+
maxDocumentBytes: 32 * 1024,
|
|
1319
|
+
},
|
|
1320
|
+
});
|
|
1321
|
+
```
|
|
1322
|
+
|
|
1323
|
+
### Migrating from the session-based API
|
|
1324
|
+
|
|
1325
|
+
Revision 2026-07-28 removed protocol sessions, the `initialize` handshake,
|
|
1326
|
+
`ping`, `logging/setLevel`, roots, `resources/subscribe` and SSE resumability.
|
|
1327
|
+
The corresponding ViteMCP surface went with them:
|
|
1328
|
+
|
|
1329
|
+
| Removed | Replacement |
|
|
1330
|
+
| --------------------------------------------------------------------------- | ----------------------------------------------------- |
|
|
1331
|
+
| `ViteMCPSession`, `server.sessions`, `server.on("connect" \| "disconnect")` | Nothing — requests are self-contained |
|
|
1332
|
+
| `context.session` | `context.auth` (per-request `authenticate` result) |
|
|
1333
|
+
| `context.sessionId` | Nothing. Correlate with your own identifier if needed |
|
|
1334
|
+
| `await context.elicit(...)` | Return `ctx.inputRequired({ ... })` — see above |
|
|
1335
|
+
| `session.requestSampling(...)` | Call your LLM provider directly |
|
|
1336
|
+
| `session.roots`, `session.clientCapabilities`, `session.loggingLevel` | Nothing |
|
|
1337
|
+
| `context.streamContent(...)` | `context.reportProgress(...)` |
|
|
1338
|
+
| `httpStream.stateless` | Nothing — every deployment is stateless |
|
|
1339
|
+
| `httpStream.eventStore` | Nothing — stream resumability was removed |
|
|
1340
|
+
| `ping` / `roots` server options | Nothing |
|
|
1341
|
+
|
|
1342
|
+
`authenticate` now receives a web-standard `Request` rather than a Node
|
|
1343
|
+
`IncomingMessage`, so read headers with `request.headers.get("...")`.
|
|
1344
|
+
|
|
1345
|
+
**The SDK you build clients with also changed.** `@modelcontextprotocol/sdk`
|
|
1346
|
+
v1 is replaced by `@modelcontextprotocol/{core,server,client,node}` v2, so every
|
|
1347
|
+
SDK import in your own code moves.
|
|
1348
|
+
|
|
1349
|
+
**Clients must opt into the new protocol era.** The v2 client negotiates the
|
|
1350
|
+
2025 era by default; this server serves only 2026-07-28. Construct clients with
|
|
1351
|
+
`versionNegotiation: { mode: "auto" }` or they will be rejected with
|
|
1352
|
+
`Unsupported protocol version`. If you need to serve older clients during a
|
|
1353
|
+
transition, pass `httpStream: { legacy: "stateless" }` — but note the server
|
|
1354
|
+
then answers requests it does not advertise support for.
|
|
1355
|
+
|
|
1356
|
+
## Server Features
|
|
1357
|
+
|
|
1358
|
+
Behaviour the server provides around your tools, resources and prompts.
|
|
1359
|
+
|
|
1360
|
+
### Logging
|
|
1361
|
+
|
|
1362
|
+
Tools can log messages to the client using the `log` object in the context object.
|
|
1363
|
+
|
|
1364
|
+
> [!IMPORTANT]
|
|
1365
|
+
>
|
|
1366
|
+
> Log notifications are **only emitted when the client asks for them**, by
|
|
1367
|
+
> setting `io.modelcontextprotocol/logLevel` in the request's `_meta`. The
|
|
1368
|
+
> revision forbids servers from sending `notifications/message` for a request
|
|
1369
|
+
> that did not opt in, so `log.*` is a no-op otherwise — that is expected
|
|
1370
|
+
> behaviour, not a bug.
|
|
1371
|
+
>
|
|
1372
|
+
> Logging is also deprecated as of 2026-07-28. For diagnostics that always
|
|
1373
|
+
> reach you, write to `stderr` (stdio servers) or use OpenTelemetry; for
|
|
1374
|
+
> user-visible progress, prefer [`reportProgress`](#progress).
|
|
1375
|
+
|
|
1376
|
+
```js
|
|
1377
|
+
server.addTool({
|
|
1378
|
+
name: "download",
|
|
1379
|
+
description: "Download a file",
|
|
1380
|
+
parameters: z.object({
|
|
1381
|
+
url: z.string(),
|
|
1382
|
+
}),
|
|
1383
|
+
execute: async (args, { log }) => {
|
|
1384
|
+
log.info("Downloading file...", {
|
|
1385
|
+
url,
|
|
1386
|
+
});
|
|
1387
|
+
|
|
1388
|
+
// ...
|
|
1389
|
+
|
|
1390
|
+
log.info("Downloaded file");
|
|
1391
|
+
|
|
1392
|
+
return "done";
|
|
1393
|
+
},
|
|
1394
|
+
});
|
|
1395
|
+
```
|
|
1396
|
+
|
|
1397
|
+
The `log` object has the following methods:
|
|
1398
|
+
|
|
1399
|
+
- `debug(message: string, data?: SerializableValue)`
|
|
1400
|
+
- `error(message: string, data?: SerializableValue)`
|
|
1401
|
+
- `info(message: string, data?: SerializableValue)`
|
|
1402
|
+
- `warn(message: string, data?: SerializableValue)`
|
|
1403
|
+
|
|
1404
|
+
### Custom Logger
|
|
1405
|
+
|
|
1406
|
+
Provide a `logger` to route server logs into your own infrastructure.
|
|
1407
|
+
|
|
1408
|
+
```ts
|
|
1409
|
+
import { ViteMCP, Logger } from "@vitemcp/server";
|
|
1410
|
+
|
|
1411
|
+
class CustomLogger implements Logger {
|
|
1412
|
+
debug(...args: unknown[]): void {
|
|
1413
|
+
console.log("[DEBUG]", new Date().toISOString(), ...args);
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
error(...args: unknown[]): void {
|
|
1417
|
+
console.error("[ERROR]", new Date().toISOString(), ...args);
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
info(...args: unknown[]): void {
|
|
1421
|
+
console.info("[INFO]", new Date().toISOString(), ...args);
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
log(...args: unknown[]): void {
|
|
1425
|
+
console.log("[LOG]", new Date().toISOString(), ...args);
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
warn(...args: unknown[]): void {
|
|
1429
|
+
console.warn("[WARN]", new Date().toISOString(), ...args);
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
const server = new ViteMCP({
|
|
1434
|
+
name: "My Server",
|
|
1435
|
+
version: "1.0.0",
|
|
1436
|
+
logger: new CustomLogger(),
|
|
1437
|
+
});
|
|
1438
|
+
```
|
|
1439
|
+
|
|
1440
|
+
See `src/examples/custom-logger.ts` for examples with Winston, Pino, and file-based logging.
|
|
1441
|
+
|
|
1442
|
+
### Errors
|
|
1443
|
+
|
|
1444
|
+
The errors that are meant to be shown to the user should be thrown as `UserError` instances:
|
|
1445
|
+
|
|
1446
|
+
```js
|
|
1447
|
+
import { UserError } from "@vitemcp/server";
|
|
1448
|
+
|
|
1449
|
+
server.addTool({
|
|
1450
|
+
name: "download",
|
|
1451
|
+
description: "Download a file",
|
|
1452
|
+
parameters: z.object({
|
|
1453
|
+
url: z.string(),
|
|
1454
|
+
}),
|
|
1455
|
+
execute: async (args) => {
|
|
1456
|
+
if (args.url.startsWith("https://example.com")) {
|
|
1457
|
+
throw new UserError("This URL is not allowed");
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
return "done";
|
|
1461
|
+
},
|
|
1462
|
+
});
|
|
1463
|
+
```
|
|
1464
|
+
|
|
1465
|
+
### Progress
|
|
1466
|
+
|
|
1467
|
+
Tools can report progress by calling `reportProgress` in the context object:
|
|
1468
|
+
|
|
1469
|
+
```js
|
|
1470
|
+
server.addTool({
|
|
1471
|
+
name: "download",
|
|
1472
|
+
description: "Download a file",
|
|
1473
|
+
parameters: z.object({
|
|
1474
|
+
url: z.string(),
|
|
1475
|
+
}),
|
|
1476
|
+
execute: async (args, { reportProgress }) => {
|
|
1477
|
+
await reportProgress({
|
|
1478
|
+
progress: 0,
|
|
1479
|
+
total: 100,
|
|
1480
|
+
});
|
|
1481
|
+
|
|
1482
|
+
// ...
|
|
1483
|
+
|
|
1484
|
+
await reportProgress({
|
|
1485
|
+
progress: 100,
|
|
1486
|
+
total: 100,
|
|
1487
|
+
});
|
|
1488
|
+
|
|
1489
|
+
return "done";
|
|
1490
|
+
},
|
|
1491
|
+
});
|
|
1492
|
+
```
|
|
1493
|
+
|
|
1494
|
+
`reportProgress` accepts an optional human-readable `message` alongside the numeric fields, which clients can display next to the progress indicator:
|
|
1495
|
+
|
|
1496
|
+
```js
|
|
1497
|
+
await reportProgress({
|
|
1498
|
+
progress: 40,
|
|
1499
|
+
total: 100,
|
|
1500
|
+
message: "Downloading chunk 4 of 10…",
|
|
1501
|
+
});
|
|
1502
|
+
```
|
|
1503
|
+
|
|
1504
|
+
Progress notifications are only emitted when the client opts in by supplying a `progressToken` on the tool call; otherwise `reportProgress` is a no-op. `notifications/progress` is part of the specification, so this is the portable way to send incremental updates during a long-running tool call.
|
|
1505
|
+
|
|
1506
|
+
### Health-check Endpoint
|
|
1507
|
+
|
|
1508
|
+
When you run ViteMCP with the `httpStream` transport you can optionally expose a
|
|
1509
|
+
simple HTTP endpoint that returns a plain-text response useful for load-balancer
|
|
1510
|
+
or container orchestration liveness checks.
|
|
1511
|
+
|
|
1512
|
+
Enable (or customise) the endpoint via the `health` key in the server options:
|
|
1513
|
+
|
|
1514
|
+
```ts
|
|
1515
|
+
const server = new ViteMCP({
|
|
1516
|
+
name: "My Server",
|
|
1517
|
+
version: "1.0.0",
|
|
1518
|
+
health: {
|
|
1519
|
+
// Enable / disable (default: true)
|
|
1520
|
+
enabled: true,
|
|
1521
|
+
// Body returned by the endpoint (default: 'ok')
|
|
1522
|
+
message: "healthy",
|
|
1523
|
+
// Path that should respond (default: '/health')
|
|
1524
|
+
path: "/healthz",
|
|
1525
|
+
// HTTP status code to return (default: 200)
|
|
1526
|
+
status: 200,
|
|
1527
|
+
},
|
|
1528
|
+
});
|
|
1529
|
+
|
|
1530
|
+
await server.start({
|
|
1531
|
+
transportType: "httpStream",
|
|
1532
|
+
httpStream: { port: 8080 },
|
|
1533
|
+
});
|
|
1534
|
+
```
|
|
1535
|
+
|
|
1536
|
+
Now a request to `http://localhost:8080/healthz` will return:
|
|
1537
|
+
|
|
1538
|
+
```
|
|
1539
|
+
HTTP/1.1 200 OK
|
|
1540
|
+
content-type: text/plain
|
|
1541
|
+
|
|
1542
|
+
healthy
|
|
1543
|
+
```
|
|
1544
|
+
|
|
1545
|
+
The endpoint is ignored when the server is started with the `stdio` transport.
|
|
1546
|
+
|
|
1547
|
+
## Deployment
|
|
1548
|
+
|
|
1549
|
+
ViteMCP can serve over HTTP, so a server on a remote machine is reachable over
|
|
1550
|
+
the network.
|
|
1551
|
+
|
|
1552
|
+
### HTTP Streaming
|
|
1553
|
+
|
|
1554
|
+
[HTTP streaming](https://www.cloudflare.com/learning/video/what-is-http-live-streaming/) provides a more efficient alternative to SSE in environments that support it, with potentially better performance for larger payloads.
|
|
1555
|
+
|
|
1556
|
+
You can run the server with HTTP streaming support:
|
|
1557
|
+
|
|
1558
|
+
```ts
|
|
1559
|
+
server.start({
|
|
1560
|
+
transportType: "httpStream",
|
|
1561
|
+
httpStream: {
|
|
1562
|
+
port: 8080,
|
|
1563
|
+
},
|
|
1564
|
+
});
|
|
1565
|
+
```
|
|
1566
|
+
|
|
1567
|
+
The server then listens on `http://localhost:8080/mcp`.
|
|
1568
|
+
|
|
1569
|
+
> **Note:** You can also customize the endpoint path using the `httpStream.endpoint` option (default is `/mcp`).
|
|
1570
|
+
|
|
1571
|
+
> **Note:** To serve HTTP streaming and built-in OAuth routes under an issuer path, set `httpStream.basePath` (for example, `/issuer1`). This exposes authorization server metadata at `/.well-known/oauth-authorization-server/issuer1` per RFC 8414.
|
|
1572
|
+
|
|
1573
|
+
Connect with a client transport:
|
|
1574
|
+
|
|
1575
|
+
For HTTP streaming connections:
|
|
1576
|
+
|
|
1577
|
+
```ts
|
|
1578
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
1579
|
+
|
|
1580
|
+
const client = new Client(
|
|
1581
|
+
{
|
|
1582
|
+
name: "example-client",
|
|
1583
|
+
version: "1.0.0",
|
|
1584
|
+
},
|
|
1585
|
+
{
|
|
1586
|
+
// Required: the SDK client negotiates the 2025 protocol era unless told
|
|
1587
|
+
// otherwise, and this server serves only 2026-07-28.
|
|
1588
|
+
versionNegotiation: { mode: "auto" },
|
|
1589
|
+
},
|
|
1590
|
+
);
|
|
1591
|
+
|
|
1592
|
+
const transport = new StreamableHTTPClientTransport(
|
|
1593
|
+
new URL(`http://localhost:8080/mcp`),
|
|
1594
|
+
);
|
|
1595
|
+
|
|
1596
|
+
await client.connect(transport);
|
|
1597
|
+
```
|
|
1598
|
+
|
|
1599
|
+
#### HTTPS Support
|
|
1600
|
+
|
|
1601
|
+
Pass SSL certificates to terminate TLS directly:
|
|
1602
|
+
|
|
1603
|
+
```ts
|
|
1604
|
+
server.start({
|
|
1605
|
+
transportType: "httpStream",
|
|
1606
|
+
httpStream: {
|
|
1607
|
+
port: 8443,
|
|
1608
|
+
sslCert: "./path/to/cert.pem",
|
|
1609
|
+
sslKey: "./path/to/key.pem",
|
|
1610
|
+
sslCa: "./path/to/ca.pem", // Optional: for client certificate authentication
|
|
1611
|
+
},
|
|
1612
|
+
});
|
|
1613
|
+
```
|
|
1614
|
+
|
|
1615
|
+
The server then listens on `https://localhost:8443/mcp`.
|
|
1616
|
+
|
|
1617
|
+
**SSL Options:**
|
|
1618
|
+
|
|
1619
|
+
- `sslCert` - Path to SSL certificate file
|
|
1620
|
+
- `sslKey` - Path to SSL private key file
|
|
1621
|
+
- `sslCa` - (Optional) Path to CA certificate for mutual TLS authentication
|
|
1622
|
+
|
|
1623
|
+
**For testing**, you can generate self-signed certificates:
|
|
1624
|
+
|
|
1625
|
+
```bash
|
|
1626
|
+
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes -subj "/CN=localhost"
|
|
1627
|
+
```
|
|
1628
|
+
|
|
1629
|
+
**For production**, obtain certificates from a trusted CA like Let's Encrypt.
|
|
1630
|
+
|
|
1631
|
+
See the [https-server example](src/examples/https-server.ts) for a complete demonstration.
|
|
1632
|
+
|
|
1633
|
+
#### CORS Configuration
|
|
1634
|
+
|
|
1635
|
+
By default, ViteMCP enables CORS with a standard set of allowed headers. You can customize the CORS behavior by passing a `cors` option:
|
|
1636
|
+
|
|
1637
|
+
```ts
|
|
1638
|
+
server.start({
|
|
1639
|
+
transportType: "httpStream",
|
|
1640
|
+
httpStream: {
|
|
1641
|
+
port: 8080,
|
|
1642
|
+
cors: {
|
|
1643
|
+
origin: "http://localhost:3000",
|
|
1644
|
+
allowedHeaders: [
|
|
1645
|
+
"Content-Type",
|
|
1646
|
+
"Authorization",
|
|
1647
|
+
"Accept",
|
|
1648
|
+
"Mcp-Protocol-Version",
|
|
1649
|
+
"X-Custom-Header",
|
|
1650
|
+
],
|
|
1651
|
+
credentials: true,
|
|
1652
|
+
},
|
|
1653
|
+
},
|
|
1654
|
+
});
|
|
1655
|
+
```
|
|
1656
|
+
|
|
1657
|
+
The `cors` option accepts:
|
|
1658
|
+
|
|
1659
|
+
- `true` (default) - enable CORS with default settings
|
|
1660
|
+
- `false` - disable CORS entirely
|
|
1661
|
+
- An object with these fields:
|
|
1662
|
+
- `origin` - a string, array of strings, or a function `(origin: string) => boolean`
|
|
1663
|
+
- `allowedHeaders` - a string or array of strings
|
|
1664
|
+
- `methods` - array of allowed HTTP methods
|
|
1665
|
+
- `exposedHeaders` - array of headers to expose
|
|
1666
|
+
- `credentials` - boolean to allow credentials
|
|
1667
|
+
- `maxAge` - preflight cache duration in seconds
|
|
1668
|
+
|
|
1669
|
+
The `CorsOptions` type is exported from `vitemcp` for convenience.
|
|
1670
|
+
|
|
1671
|
+
### Custom HTTP Routes
|
|
1672
|
+
|
|
1673
|
+
Custom HTTP routes live alongside the MCP endpoint in the same process — REST APIs, webhooks, admin interfaces.
|
|
1674
|
+
|
|
1675
|
+
```ts
|
|
1676
|
+
const app = server.getApp();
|
|
1677
|
+
|
|
1678
|
+
// Add REST API endpoints with Hono's native API
|
|
1679
|
+
app.get("/api/users", async (c) => {
|
|
1680
|
+
return c.json({ users: [] });
|
|
1681
|
+
});
|
|
1682
|
+
|
|
1683
|
+
// Handle path parameters
|
|
1684
|
+
app.get("/api/users/:id", async (c) => {
|
|
1685
|
+
return c.json({
|
|
1686
|
+
userId: c.req.param("id"),
|
|
1687
|
+
query: c.req.query(), // Access query parameters
|
|
1688
|
+
});
|
|
1689
|
+
});
|
|
1690
|
+
|
|
1691
|
+
// Handle POST requests with body parsing
|
|
1692
|
+
app.post("/api/users", async (c) => {
|
|
1693
|
+
const body = await c.req.json();
|
|
1694
|
+
return c.json({ created: body }, 201);
|
|
1695
|
+
});
|
|
1696
|
+
|
|
1697
|
+
// Serve HTML content
|
|
1698
|
+
app.get("/admin", async (c) => {
|
|
1699
|
+
return c.html("<html><body><h1>Admin Panel</h1></body></html>");
|
|
1700
|
+
});
|
|
1701
|
+
|
|
1702
|
+
// Handle webhooks
|
|
1703
|
+
app.post("/webhook/github", async (c) => {
|
|
1704
|
+
const payload = await c.req.json();
|
|
1705
|
+
const event = c.req.header("x-github-event");
|
|
1706
|
+
|
|
1707
|
+
// Process webhook...
|
|
1708
|
+
return c.json({ received: true });
|
|
1709
|
+
});
|
|
1710
|
+
```
|
|
1711
|
+
|
|
1712
|
+
Custom routes use the underlying [Hono](https://hono.dev/) app returned by `server.getApp()` and support:
|
|
1713
|
+
|
|
1714
|
+
- Hono's HTTP methods: `get`, `post`, `put`, `delete`, `patch`, `options`, and more
|
|
1715
|
+
- Path parameters (`:param`) and wildcards (`*`)
|
|
1716
|
+
- Query string parsing
|
|
1717
|
+
- JSON, text, form, and other body helpers from `c.req`
|
|
1718
|
+
- Custom status codes and headers
|
|
1719
|
+
- Middleware and route groups through Hono
|
|
1720
|
+
|
|
1721
|
+
Routes are matched in the order they are registered, allowing you to define specific routes before catch-all patterns.
|
|
1722
|
+
|
|
1723
|
+
#### Public and Protected Routes
|
|
1724
|
+
|
|
1725
|
+
Custom Hono routes are public unless you add your own route middleware or authentication checks. For protected custom routes, put your auth logic in a reusable helper and call it from both ViteMCP's `authenticate` option and your Hono route handlers:
|
|
1726
|
+
|
|
1727
|
+
```ts
|
|
1728
|
+
import type { Context } from "hono";
|
|
1729
|
+
import { ViteMCP } from "@vitemcp/server";
|
|
1730
|
+
|
|
1731
|
+
async function authenticateRequest(request: Request) {
|
|
1732
|
+
const apiKey = request.headers.get("x-api-key");
|
|
1733
|
+
return apiKey === "123" ? { userId: "123" } : undefined;
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
const server = new ViteMCP({
|
|
1737
|
+
name: "My Server",
|
|
1738
|
+
version: "1.0.0",
|
|
1739
|
+
authenticate: authenticateRequest,
|
|
1740
|
+
});
|
|
1741
|
+
|
|
1742
|
+
const app = server.getApp();
|
|
1743
|
+
|
|
1744
|
+
async function requireAuth(c: Context) {
|
|
1745
|
+
const auth = await authenticateRequest(c.env.incoming);
|
|
1746
|
+
|
|
1747
|
+
if (!auth) {
|
|
1748
|
+
return c.json({ error: "Authentication required" }, 401);
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
return auth;
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
// Public route - no authentication required
|
|
1755
|
+
app.get("/.well-known/openid-configuration", async (c) => {
|
|
1756
|
+
return c.json({
|
|
1757
|
+
issuer: "https://example.com",
|
|
1758
|
+
authorization_endpoint: "https://example.com/auth",
|
|
1759
|
+
token_endpoint: "https://example.com/token",
|
|
1760
|
+
});
|
|
1761
|
+
});
|
|
1762
|
+
|
|
1763
|
+
// Private route - requires authentication
|
|
1764
|
+
app.get("/api/users", async (c) => {
|
|
1765
|
+
const auth = await requireAuth(c);
|
|
1766
|
+
if (auth instanceof Response) {
|
|
1767
|
+
return auth;
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
return c.json({ users: [] });
|
|
1771
|
+
});
|
|
1772
|
+
|
|
1773
|
+
// Public static files
|
|
1774
|
+
app.get("/public/*", async (c) => {
|
|
1775
|
+
return c.text(`File: ${c.req.path}`);
|
|
1776
|
+
});
|
|
1777
|
+
```
|
|
1778
|
+
|
|
1779
|
+
Public routes are perfect for:
|
|
1780
|
+
|
|
1781
|
+
- OAuth discovery endpoints (`.well-known/*`)
|
|
1782
|
+
- Health checks and status pages
|
|
1783
|
+
- Static assets and documentation
|
|
1784
|
+
- Webhook endpoints from external services
|
|
1785
|
+
- Public APIs that don't require user authentication
|
|
1786
|
+
|
|
1787
|
+
See the [custom-routes example](src/examples/custom-routes.ts) for a complete demonstration.
|
|
1788
|
+
|
|
1789
|
+
### Edge Runtime Support
|
|
1790
|
+
|
|
1791
|
+
ViteMCP runs on edge runtimes such as Cloudflare Workers.
|
|
1792
|
+
|
|
1793
|
+
#### Choosing Between ViteMCP and EdgeViteMCP
|
|
1794
|
+
|
|
1795
|
+
| Use Case | Class | Import |
|
|
1796
|
+
| ------------------------------- | ------------- | ---------------------------------------------------- |
|
|
1797
|
+
| Node.js, Express, Bun | `ViteMCP` | `import { ViteMCP } from "@vitemcp/server"` |
|
|
1798
|
+
| Cloudflare Workers, Deno Deploy | `EdgeViteMCP` | `import { EdgeViteMCP } from "@vitemcp/server/edge"` |
|
|
1799
|
+
|
|
1800
|
+
| Feature | ViteMCP | EdgeViteMCP |
|
|
1801
|
+
| -------------------- | ------------------------------ | -------------------------------------- |
|
|
1802
|
+
| Runtime | Node.js | Edge (V8 isolates) |
|
|
1803
|
+
| Start method | `server.start({ port })` | `export default server` |
|
|
1804
|
+
| Transport | stdio, httpStream | HTTP Streamable only |
|
|
1805
|
+
| File system | Yes | No |
|
|
1806
|
+
| OAuth/Authentication | Built-in `authenticate` option | Use Hono middleware (built-in planned) |
|
|
1807
|
+
| Custom routes | `server.getApp()` | `server.getApp()` |
|
|
1808
|
+
|
|
1809
|
+
> **Note:** Built-in authentication for EdgeViteMCP is planned for a future release. Both ViteMCP and EdgeViteMCP use Hono internally, so there's no technical barrier. `ViteMCP`'s `authenticate` already takes a web-standard `Request`, so the same hook shape works on both.
|
|
1810
|
+
>
|
|
1811
|
+
> In the meantime, use Hono middleware:
|
|
1812
|
+
>
|
|
1813
|
+
> ```ts
|
|
1814
|
+
> const app = server.getApp();
|
|
1815
|
+
> app.use("/api/*", async (c, next) => {
|
|
1816
|
+
> if (c.req.header("authorization") !== "Bearer secret") {
|
|
1817
|
+
> return c.json({ error: "Unauthorized" }, 401);
|
|
1818
|
+
> }
|
|
1819
|
+
> await next();
|
|
1820
|
+
> });
|
|
1821
|
+
> ```
|
|
1822
|
+
|
|
1823
|
+
#### Cloudflare Workers
|
|
1824
|
+
|
|
1825
|
+
To deploy ViteMCP to Cloudflare Workers, use the `EdgeViteMCP` class from the `/edge` subpath:
|
|
1826
|
+
|
|
1827
|
+
```ts
|
|
1828
|
+
import { EdgeViteMCP } from "@vitemcp/server/edge";
|
|
1829
|
+
import { z } from "zod";
|
|
1830
|
+
|
|
1831
|
+
const server = new EdgeViteMCP({
|
|
1832
|
+
name: "My Edge Server",
|
|
1833
|
+
version: "1.0.0",
|
|
1834
|
+
description: "MCP server running on Cloudflare Workers",
|
|
1835
|
+
});
|
|
1836
|
+
|
|
1837
|
+
// Add tools, resources, prompts as usual
|
|
1838
|
+
server.addTool({
|
|
1839
|
+
name: "greet",
|
|
1840
|
+
description: "Greet someone",
|
|
1841
|
+
parameters: z.object({
|
|
1842
|
+
name: z.string(),
|
|
1843
|
+
}),
|
|
1844
|
+
execute: async ({ name }) => {
|
|
1845
|
+
return `Hello, ${name}! Served from the edge.`;
|
|
1846
|
+
},
|
|
1847
|
+
});
|
|
1848
|
+
|
|
1849
|
+
// Export the server as the default (required for Cloudflare Workers)
|
|
1850
|
+
export default server;
|
|
1851
|
+
```
|
|
1852
|
+
|
|
1853
|
+
#### Edge Runtime Differences
|
|
1854
|
+
|
|
1855
|
+
When running on edge runtimes:
|
|
1856
|
+
|
|
1857
|
+
- **No shared state**: Each request is handled independently — which is simply how the protocol works now
|
|
1858
|
+
- **No filesystem access**: Use fetch APIs for external data
|
|
1859
|
+
- **V8 Isolates**: Fast cold starts and efficient resource usage
|
|
1860
|
+
- **Global deployment**: Automatic distribution to edge locations
|
|
1861
|
+
|
|
1862
|
+
#### Custom Routes on Edge
|
|
1863
|
+
|
|
1864
|
+
You can access the underlying Hono app to add custom HTTP routes:
|
|
1865
|
+
|
|
1866
|
+
```ts
|
|
1867
|
+
const app = server.getApp();
|
|
1868
|
+
|
|
1869
|
+
// Add a landing page
|
|
1870
|
+
app.get("/", (c) => c.html("<h1>Welcome to my MCP server</h1>"));
|
|
1871
|
+
|
|
1872
|
+
// Add REST API endpoints
|
|
1873
|
+
app.get("/api/status", (c) => c.json({ status: "ok" }));
|
|
1874
|
+
```
|
|
1875
|
+
|
|
1876
|
+
#### Deploying to the edge
|
|
1877
|
+
|
|
1878
|
+
Configure your `wrangler.toml`:
|
|
1879
|
+
|
|
1880
|
+
```toml
|
|
1881
|
+
name = "my-mcp-server"
|
|
1882
|
+
main = "src/index.ts"
|
|
1883
|
+
compatibility_date = "2024-01-01"
|
|
1884
|
+
```
|
|
1885
|
+
|
|
1886
|
+
Deploy with:
|
|
1887
|
+
|
|
1888
|
+
```bash
|
|
1889
|
+
wrangler deploy
|
|
1890
|
+
```
|
|
1891
|
+
|
|
1892
|
+
See the [edge-cloudflare-worker example](src/examples/edge-cloudflare-worker.ts) for a complete demonstration.
|
|
1893
|
+
|
|
1894
|
+
## Testing and Debugging
|
|
1895
|
+
|
|
1896
|
+
### Unit testing with an in-memory transport
|
|
1897
|
+
|
|
1898
|
+
`server.connect(transport)` attaches the server to a transport you construct yourself, instead of letting `start()` create one. Paired with the SDK's `InMemoryTransport`, this lets you drive a server in-process — no port to bind, no subprocess to spawn — which is usually what you want for testing a `stdio` server:
|
|
1899
|
+
|
|
1900
|
+
```ts
|
|
1901
|
+
import { Client } from "@modelcontextprotocol/client";
|
|
1902
|
+
import { InMemoryTransport } from "@modelcontextprotocol/server";
|
|
1903
|
+
|
|
1904
|
+
async function createTestClient(server: ViteMCP) {
|
|
1905
|
+
const [clientTransport, serverTransport] =
|
|
1906
|
+
InMemoryTransport.createLinkedPair();
|
|
1907
|
+
|
|
1908
|
+
const client = new Client(
|
|
1909
|
+
{ name: "test-client", version: "0.0.0" },
|
|
1910
|
+
{ versionNegotiation: { mode: "auto" } },
|
|
1911
|
+
);
|
|
1912
|
+
|
|
1913
|
+
await Promise.all([
|
|
1914
|
+
server.connect(serverTransport),
|
|
1915
|
+
client.connect(clientTransport),
|
|
1916
|
+
]);
|
|
1917
|
+
|
|
1918
|
+
return { client };
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
test("adds two numbers", async () => {
|
|
1922
|
+
const { client } = await createTestClient(server);
|
|
1923
|
+
|
|
1924
|
+
expect(
|
|
1925
|
+
await client.callTool({ arguments: { a: 2, b: 3 }, name: "add" }),
|
|
1926
|
+
).toEqual({
|
|
1927
|
+
content: [{ text: "5", type: "text" }],
|
|
1928
|
+
});
|
|
1929
|
+
|
|
1930
|
+
await client.close();
|
|
1931
|
+
});
|
|
1932
|
+
```
|
|
1933
|
+
|
|
1934
|
+
The server instance is built from the tools, resources and prompts registered on it, exactly as `start()` builds it, so tests exercise the same wiring the real server uses.
|
|
1935
|
+
|
|
1936
|
+
`connect()` does not run your `authenticate` hook — there is no HTTP request to authenticate — so `context.auth` is `undefined` on this path and `canAccess` sees `undefined`. Test authorization through the HTTP transport instead.
|
|
1937
|
+
|
|
1938
|
+
The transport's lifecycle belongs to you: close the client when the test finishes. `stop()` closes servers created via `connect()` but not the transports you passed in.
|
|
1939
|
+
|
|
1940
|
+
### Test with `mcp-cli`
|
|
1941
|
+
|
|
1942
|
+
The fastest way to test and debug your server is with `vitemcp dev`:
|
|
1943
|
+
|
|
1944
|
+
```bash
|
|
1945
|
+
npx @vitemcp/server dev server.js
|
|
1946
|
+
npx @vitemcp/server dev server.ts
|
|
1947
|
+
```
|
|
1948
|
+
|
|
1949
|
+
This will run your server with [`mcp-cli`](https://github.com/wong2/mcp-cli) for testing and debugging your MCP server in the terminal.
|
|
1950
|
+
|
|
1951
|
+
To call a tool non-interactively (for example, in scripts or automated tests), pass `--tool` and optional JSON `--args`:
|
|
1952
|
+
|
|
1953
|
+
```bash
|
|
1954
|
+
npx @vitemcp/server dev server.ts --tool add --args '{"a":1,"b":2}'
|
|
1955
|
+
```
|
|
1956
|
+
|
|
1957
|
+
This prints the tool result as JSON and exits, instead of opening the interactive inspector. `--watch` has no effect in this mode, since the server is started for a single call.
|
|
1958
|
+
|
|
1959
|
+
### Inspect with `MCP Inspector`
|
|
1960
|
+
|
|
1961
|
+
Another way is to use the official [`MCP Inspector`](https://modelcontextprotocol.io/docs/tools/inspector) to inspect your server with a Web UI:
|
|
1962
|
+
|
|
1963
|
+
```bash
|
|
1964
|
+
npx @vitemcp/server inspect server.ts
|
|
1965
|
+
```
|
|
1966
|
+
|
|
1967
|
+
## FAQ
|
|
1968
|
+
|
|
1969
|
+
### How to use with Claude Desktop?
|
|
1970
|
+
|
|
1971
|
+
Follow the guide https://modelcontextprotocol.io/quickstart/user and add the following configuration:
|
|
1972
|
+
|
|
1973
|
+
```json
|
|
1974
|
+
{
|
|
1975
|
+
"mcpServers": {
|
|
1976
|
+
"my-mcp-server": {
|
|
1977
|
+
"command": "npx",
|
|
1978
|
+
"args": ["tsx", "/PATH/TO/YOUR_PROJECT/src/index.ts"],
|
|
1979
|
+
"env": {
|
|
1980
|
+
"YOUR_ENV_VAR": "value"
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
```
|
|
1986
|
+
|
|
1987
|
+
### How to run ViteMCP behind a proxy?
|
|
1988
|
+
|
|
1989
|
+
Refer to this [issue](https://github.com/vitemcp/vitemcp/issues/25#issuecomment-3004568732) for an example of using ViteMCP with `express` and `http-proxy-middleware`.
|
|
1990
|
+
|
|
1991
|
+
## Showcase
|
|
1992
|
+
|
|
1993
|
+
Built something with ViteMCP? [Open a PR](https://github.com/vitemcp/vitemcp) to
|
|
1994
|
+
list it here.
|
|
1995
|
+
|
|
1996
|
+
## Acknowledgements
|
|
1997
|
+
|
|
1998
|
+
- Parts of codebase were adopted from [LiteMCP](https://github.com/wong2/litemcp).
|
|
1999
|
+
- Parts of codebase were adopted from [Model Context protocolでSSEをやってみる](https://dev.classmethod.jp/articles/mcp-sse/).
|
|
2000
|
+
|
|
2001
|
+
This project is tested with BrowserStack.
|