fastmcp 1.22.4 → 1.23.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/README.md +51 -8
- package/dist/FastMCP.d.ts +36 -1
- package/dist/FastMCP.js +21 -14
- package/dist/FastMCP.js.map +1 -1
- package/jsr.json +1 -1
- package/package.json +1 -1
- package/src/FastMCP.test.ts +33 -24
- package/src/FastMCP.ts +83 -26
- package/src/examples/addition.ts +17 -0
package/README.md
CHANGED
|
@@ -432,7 +432,6 @@ server.addTool({
|
|
|
432
432
|
});
|
|
433
433
|
```
|
|
434
434
|
|
|
435
|
-
|
|
436
435
|
#### Logging
|
|
437
436
|
|
|
438
437
|
Tools can log messages to the client using the `log` object in the context object:
|
|
@@ -517,6 +516,40 @@ server.addTool({
|
|
|
517
516
|
});
|
|
518
517
|
```
|
|
519
518
|
|
|
519
|
+
#### Tool Annotations
|
|
520
|
+
|
|
521
|
+
As of the MCP Specification (2025-03-26), tools can include annotations that provide richer context and control by adding metadata about a tool's behavior:
|
|
522
|
+
|
|
523
|
+
```typescript
|
|
524
|
+
server.addTool({
|
|
525
|
+
name: "fetch-content",
|
|
526
|
+
description: "Fetch content from a URL",
|
|
527
|
+
parameters: z.object({
|
|
528
|
+
url: z.string(),
|
|
529
|
+
}),
|
|
530
|
+
annotations: {
|
|
531
|
+
title: "Web Content Fetcher", // Human-readable title for UI display
|
|
532
|
+
readOnlyHint: true, // Tool doesn't modify its environment
|
|
533
|
+
openWorldHint: true, // Tool interacts with external entities
|
|
534
|
+
},
|
|
535
|
+
execute: async (args) => {
|
|
536
|
+
return await fetchWebpageContent(args.url);
|
|
537
|
+
},
|
|
538
|
+
});
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
The available annotations are:
|
|
542
|
+
|
|
543
|
+
| Annotation | Type | Default | Description |
|
|
544
|
+
| :---------------- | :------ | :------ | :----------------------------------------------------------------------------------------------------------------------------------- |
|
|
545
|
+
| `title` | string | - | A human-readable title for the tool, useful for UI display |
|
|
546
|
+
| `readOnlyHint` | boolean | `false` | If true, indicates the tool does not modify its environment |
|
|
547
|
+
| `destructiveHint` | boolean | `true` | If true, the tool may perform destructive updates (only meaningful when `readOnlyHint` is false) |
|
|
548
|
+
| `idempotentHint` | boolean | `false` | If true, calling the tool repeatedly with the same arguments has no additional effect (only meaningful when `readOnlyHint` is false) |
|
|
549
|
+
| `openWorldHint` | boolean | `true` | If true, the tool may interact with an "open world" of external entities |
|
|
550
|
+
|
|
551
|
+
These annotations help clients and LLMs better understand how to use the tools and what to expect when calling them.
|
|
552
|
+
|
|
520
553
|
### Resources
|
|
521
554
|
|
|
522
555
|
[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:
|
|
@@ -712,10 +745,10 @@ import { AuthError } from "fastmcp";
|
|
|
712
745
|
const server = new FastMCP({
|
|
713
746
|
name: "My Server",
|
|
714
747
|
version: "1.0.0",
|
|
715
|
-
authenticate: ({request}) => {
|
|
748
|
+
authenticate: ({ request }) => {
|
|
716
749
|
const apiKey = request.headers["x-api-key"];
|
|
717
750
|
|
|
718
|
-
if (apiKey !==
|
|
751
|
+
if (apiKey !== "123") {
|
|
719
752
|
throw new Response(null, {
|
|
720
753
|
status: 401,
|
|
721
754
|
statusText: "Unauthorized",
|
|
@@ -725,7 +758,7 @@ const server = new FastMCP({
|
|
|
725
758
|
// Whatever you return here will be accessible in the `context.session` object.
|
|
726
759
|
return {
|
|
727
760
|
id: 1,
|
|
728
|
-
}
|
|
761
|
+
};
|
|
729
762
|
},
|
|
730
763
|
});
|
|
731
764
|
```
|
|
@@ -741,6 +774,19 @@ server.addTool({
|
|
|
741
774
|
});
|
|
742
775
|
```
|
|
743
776
|
|
|
777
|
+
### Providing Instructions
|
|
778
|
+
|
|
779
|
+
You can provide instructions to the server using the `instructions` option:
|
|
780
|
+
|
|
781
|
+
```ts
|
|
782
|
+
const server = new FastMCP({
|
|
783
|
+
name: "My Server",
|
|
784
|
+
version: "1.0.0",
|
|
785
|
+
instructions:
|
|
786
|
+
'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.',
|
|
787
|
+
});
|
|
788
|
+
```
|
|
789
|
+
|
|
744
790
|
### Sessions
|
|
745
791
|
|
|
746
792
|
The `session` object is an instance of `FastMCPSession` and it describes active client sessions.
|
|
@@ -870,10 +916,7 @@ Follow the guide https://modelcontextprotocol.io/quickstart/user and add the fol
|
|
|
870
916
|
"mcpServers": {
|
|
871
917
|
"my-mcp-server": {
|
|
872
918
|
"command": "npx",
|
|
873
|
-
"args": [
|
|
874
|
-
"tsx",
|
|
875
|
-
"/PATH/TO/YOUR_PROJECT/src/index.ts"
|
|
876
|
-
],
|
|
919
|
+
"args": ["tsx", "/PATH/TO/YOUR_PROJECT/src/index.ts"],
|
|
877
920
|
"env": {
|
|
878
921
|
"YOUR_ENV_VAR": "value"
|
|
879
922
|
}
|
package/dist/FastMCP.d.ts
CHANGED
|
@@ -101,10 +101,43 @@ type Completion = {
|
|
|
101
101
|
total?: number;
|
|
102
102
|
hasMore?: boolean;
|
|
103
103
|
};
|
|
104
|
+
/**
|
|
105
|
+
* Tool annotations as defined in MCP Specification (2025-03-26)
|
|
106
|
+
* These provide hints about a tool's behavior.
|
|
107
|
+
*/
|
|
108
|
+
type ToolAnnotations = {
|
|
109
|
+
/**
|
|
110
|
+
* A human-readable title for the tool, useful for UI display
|
|
111
|
+
*/
|
|
112
|
+
title?: string;
|
|
113
|
+
/**
|
|
114
|
+
* If true, indicates the tool does not modify its environment
|
|
115
|
+
* @default false
|
|
116
|
+
*/
|
|
117
|
+
readOnlyHint?: boolean;
|
|
118
|
+
/**
|
|
119
|
+
* If true, the tool may perform destructive updates
|
|
120
|
+
* Only meaningful when readOnlyHint is false
|
|
121
|
+
* @default true
|
|
122
|
+
*/
|
|
123
|
+
destructiveHint?: boolean;
|
|
124
|
+
/**
|
|
125
|
+
* If true, calling the tool repeatedly with the same arguments has no additional effect
|
|
126
|
+
* Only meaningful when readOnlyHint is false
|
|
127
|
+
* @default false
|
|
128
|
+
*/
|
|
129
|
+
idempotentHint?: boolean;
|
|
130
|
+
/**
|
|
131
|
+
* If true, the tool may interact with an "open world" of external entities
|
|
132
|
+
* @default true
|
|
133
|
+
*/
|
|
134
|
+
openWorldHint?: boolean;
|
|
135
|
+
};
|
|
104
136
|
type Tool<T extends FastMCPSessionAuth, Params extends ToolParameters = ToolParameters> = {
|
|
105
137
|
name: string;
|
|
106
138
|
description?: string;
|
|
107
139
|
parameters?: Params;
|
|
140
|
+
annotations?: ToolAnnotations;
|
|
108
141
|
execute: (args: StandardSchemaV1.InferOutput<Params>, context: Context<T>) => Promise<string | ContentResult | TextContent | ImageContent | AudioContent>;
|
|
109
142
|
};
|
|
110
143
|
type ResourceResult = {
|
|
@@ -192,6 +225,7 @@ type ServerOptions<T extends FastMCPSessionAuth> = {
|
|
|
192
225
|
name: string;
|
|
193
226
|
version: `${number}.${number}.${number}`;
|
|
194
227
|
authenticate?: Authenticate<T>;
|
|
228
|
+
instructions?: string;
|
|
195
229
|
};
|
|
196
230
|
type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency";
|
|
197
231
|
declare const FastMCPSessionEventEmitterBase: {
|
|
@@ -208,10 +242,11 @@ type SamplingResponse = {
|
|
|
208
242
|
type FastMCPSessionAuth = Record<string, unknown> | undefined;
|
|
209
243
|
declare class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> extends FastMCPSessionEventEmitter {
|
|
210
244
|
#private;
|
|
211
|
-
constructor({ auth, name, version, tools, resources, resourcesTemplates, prompts, }: {
|
|
245
|
+
constructor({ auth, name, version, instructions, tools, resources, resourcesTemplates, prompts, }: {
|
|
212
246
|
auth?: T;
|
|
213
247
|
name: string;
|
|
214
248
|
version: string;
|
|
249
|
+
instructions?: string;
|
|
215
250
|
tools: Tool<T>[];
|
|
216
251
|
resources: Resource[];
|
|
217
252
|
resourcesTemplates: InputResourceTemplate[];
|
package/dist/FastMCP.js
CHANGED
|
@@ -24,9 +24,7 @@ import { EventEmitter } from "events";
|
|
|
24
24
|
import Fuse from "fuse.js";
|
|
25
25
|
import { startSSEServer } from "mcp-proxy";
|
|
26
26
|
import parseURITemplate from "uri-templates";
|
|
27
|
-
import {
|
|
28
|
-
fetch
|
|
29
|
-
} from "undici";
|
|
27
|
+
import { fetch } from "undici";
|
|
30
28
|
var imageContent = async (input) => {
|
|
31
29
|
let rawData;
|
|
32
30
|
if ("url" in input) {
|
|
@@ -65,7 +63,9 @@ var audioContent = async (input) => {
|
|
|
65
63
|
} else if ("buffer" in input) {
|
|
66
64
|
rawData = input.buffer;
|
|
67
65
|
} else {
|
|
68
|
-
throw new Error(
|
|
66
|
+
throw new Error(
|
|
67
|
+
"Invalid input: Provide a valid 'url', 'path', or 'buffer'"
|
|
68
|
+
);
|
|
69
69
|
}
|
|
70
70
|
const mimeType = await fileTypeFromBuffer(rawData);
|
|
71
71
|
const base64Data = rawData.toString("base64");
|
|
@@ -148,6 +148,7 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
|
|
|
148
148
|
auth,
|
|
149
149
|
name,
|
|
150
150
|
version,
|
|
151
|
+
instructions,
|
|
151
152
|
tools,
|
|
152
153
|
resources,
|
|
153
154
|
resourcesTemplates,
|
|
@@ -170,7 +171,7 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
|
|
|
170
171
|
this.#capabilities.logging = {};
|
|
171
172
|
this.#server = new Server(
|
|
172
173
|
{ name, version },
|
|
173
|
-
{ capabilities: this.#capabilities }
|
|
174
|
+
{ capabilities: this.#capabilities, instructions }
|
|
174
175
|
);
|
|
175
176
|
this.setupErrorHandling();
|
|
176
177
|
this.setupLoggingHandlers();
|
|
@@ -284,9 +285,11 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
|
|
|
284
285
|
const roots = await this.#server.listRoots();
|
|
285
286
|
this.#roots = roots.roots;
|
|
286
287
|
} catch (e) {
|
|
287
|
-
console.error(
|
|
288
|
+
console.error(
|
|
289
|
+
`[FastMCP error] received error listing roots.
|
|
288
290
|
|
|
289
|
-
${e instanceof Error ? e.stack : JSON.stringify(e)}`
|
|
291
|
+
${e instanceof Error ? e.stack : JSON.stringify(e)}`
|
|
292
|
+
);
|
|
290
293
|
}
|
|
291
294
|
}
|
|
292
295
|
if (this.#clientCapabilities) {
|
|
@@ -403,13 +406,16 @@ ${e instanceof Error ? e.stack : JSON.stringify(e)}`);
|
|
|
403
406
|
setupToolHandlers(tools) {
|
|
404
407
|
this.#server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
405
408
|
return {
|
|
406
|
-
tools: await Promise.all(
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
409
|
+
tools: await Promise.all(
|
|
410
|
+
tools.map(async (tool) => {
|
|
411
|
+
return {
|
|
412
|
+
name: tool.name,
|
|
413
|
+
description: tool.description,
|
|
414
|
+
inputSchema: tool.parameters ? await toJsonSchema(tool.parameters) : void 0,
|
|
415
|
+
annotations: tool.annotations
|
|
416
|
+
};
|
|
417
|
+
})
|
|
418
|
+
)
|
|
413
419
|
};
|
|
414
420
|
});
|
|
415
421
|
this.#server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
@@ -727,6 +733,7 @@ var FastMCP = class extends FastMCPEventEmitter {
|
|
|
727
733
|
const session = new FastMCPSession({
|
|
728
734
|
name: this.#options.name,
|
|
729
735
|
version: this.#options.version,
|
|
736
|
+
instructions: this.#options.instructions,
|
|
730
737
|
tools: this.#tools,
|
|
731
738
|
resources: this.#resources,
|
|
732
739
|
resourcesTemplates: this.#resourcesTemplates,
|
package/dist/FastMCP.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/FastMCP.ts"],"sourcesContent":["import { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n AudioContent,\n CallToolRequestSchema,\n ClientCapabilities,\n CompleteRequestSchema,\n CreateMessageRequestSchema,\n ErrorCode,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n Root,\n RootsListChangedNotificationSchema,\n ServerCapabilities,\n SetLevelRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { toJsonSchema } from \"xsschema\";\nimport { z } from \"zod\";\nimport { setTimeout as delay } from \"timers/promises\";\nimport { readFile } from \"fs/promises\";\nimport { fileTypeFromBuffer } from \"file-type\";\nimport { StrictEventEmitter } from \"strict-event-emitter-types\";\nimport { EventEmitter } from \"events\";\nimport Fuse from \"fuse.js\";\nimport { startSSEServer } from \"mcp-proxy\";\nimport { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport parseURITemplate from \"uri-templates\";\nimport http from \"http\";\nimport {\n fetch\n} from \"undici\";\n\nexport type SSEServer = {\n close: () => Promise<void>;\n};\n\ntype FastMCPEvents<T extends FastMCPSessionAuth> = {\n connect: (event: { session: FastMCPSession<T> }) => void;\n disconnect: (event: { session: FastMCPSession<T> }) => void;\n};\n\ntype FastMCPSessionEvents = {\n rootsChanged: (event: { roots: Root[] }) => void;\n error: (event: { error: Error }) => void;\n};\n\n/**\n * Generates an image content object from a URL, file path, or buffer.\n */\nexport const imageContent = async (\n input: { url: string } | { path: string } | { buffer: Buffer },\n): Promise<ImageContent> => {\n let rawData: Buffer;\n\n if (\"url\" in input) {\n const response = await fetch(input.url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch image from URL: ${response.statusText}`);\n }\n\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in input) {\n rawData = await readFile(input.path);\n } else if (\"buffer\" in input) {\n rawData = input.buffer;\n } else {\n throw new Error(\n \"Invalid input: Provide a valid 'url', 'path', or 'buffer'\",\n );\n }\n\n const mimeType = await fileTypeFromBuffer(rawData);\n\n const base64Data = rawData.toString(\"base64\");\n\n return {\n type: \"image\",\n data: base64Data,\n mimeType: mimeType?.mime ?? \"image/png\",\n } as const;\n};\n\nexport const audioContent = async (input: { url: string } | { path: string } | { buffer: Buffer }): Promise<AudioContent> => {\n let rawData: Buffer;\n\n if (\"url\" in input) {\n const response = await fetch(input.url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch audio from URL: ${response.statusText}`);\n }\n\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in input) {\n rawData = await readFile(input.path);\n } else if (\"buffer\" in input) {\n rawData = input.buffer;\n } else {\n throw new Error(\"Invalid input: Provide a valid 'url', 'path', or 'buffer'\");\n }\n\n const mimeType = await fileTypeFromBuffer(rawData);\n\n const base64Data = rawData.toString(\"base64\");\n\n return {\n type: \"audio\",\n data: base64Data,\n mimeType: mimeType?.mime ?? \"audio/mpeg\",\n } as const;\n};\n\nabstract class FastMCPError extends Error {\n public constructor(message?: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\ntype Extra = unknown;\n\ntype Extras = Record<string, Extra>;\n\nexport class UnexpectedStateError extends FastMCPError {\n public extras?: Extras;\n\n public constructor(message: string, extras?: Extras) {\n super(message);\n this.name = new.target.name;\n this.extras = extras;\n }\n}\n\n/**\n * An error that is meant to be surfaced to the user.\n */\nexport class UserError extends UnexpectedStateError {}\n\ntype ToolParameters = StandardSchemaV1;\n\ntype Literal = boolean | null | number | string | undefined;\n\ntype SerializableValue =\n | Literal\n | SerializableValue[]\n | { [key: string]: SerializableValue };\n\ntype Progress = {\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: number;\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total?: number;\n};\n\ntype Context<T extends FastMCPSessionAuth> = {\n session: T | undefined;\n reportProgress: (progress: Progress) => Promise<void>;\n log: {\n debug: (message: string, data?: SerializableValue) => void;\n error: (message: string, data?: SerializableValue) => void;\n info: (message: string, data?: SerializableValue) => void;\n warn: (message: string, data?: SerializableValue) => void;\n };\n};\n\ntype TextContent = {\n type: \"text\";\n text: string;\n};\n\nconst TextContentZodSchema = z\n .object({\n type: z.literal(\"text\"),\n /**\n * The text content of the message.\n */\n text: z.string(),\n })\n .strict() satisfies z.ZodType<TextContent>;\n\ntype ImageContent = {\n type: \"image\";\n data: string;\n mimeType: string;\n};\n\nconst ImageContentZodSchema = z\n .object({\n type: z.literal(\"image\"),\n /**\n * The base64-encoded image data.\n */\n data: z.string().base64(),\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n })\n .strict() satisfies z.ZodType<ImageContent>;\n\ntype Content = TextContent | ImageContent;\n\nconst ContentZodSchema = z.discriminatedUnion(\"type\", [\n TextContentZodSchema,\n ImageContentZodSchema,\n]) satisfies z.ZodType<Content>;\n\ntype ContentResult = {\n content: Content[];\n isError?: boolean;\n};\n\nconst ContentResultZodSchema = z\n .object({\n content: ContentZodSchema.array(),\n isError: z.boolean().optional(),\n })\n .strict() satisfies z.ZodType<ContentResult>;\n\ntype Completion = {\n values: string[];\n total?: number;\n hasMore?: boolean;\n};\n\n/**\n * https://github.com/modelcontextprotocol/typescript-sdk/blob/3164da64d085ec4e022ae881329eee7b72f208d4/src/types.ts#L983-L1003\n */\nconst CompletionZodSchema = z.object({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean()),\n}) satisfies z.ZodType<Completion>;\n\ntype Tool<T extends FastMCPSessionAuth, Params extends ToolParameters = ToolParameters> = {\n name: string;\n description?: string;\n parameters?: Params;\n execute: (\n args: StandardSchemaV1.InferOutput<Params>,\n context: Context<T>,\n ) => Promise<string | ContentResult | TextContent | ImageContent | AudioContent>;\n};\n\ntype ResourceResult =\n | {\n text: string;\n }\n | {\n blob: string;\n };\n\ntype InputResourceTemplateArgument = Readonly<{\n name: string;\n description?: string;\n complete?: ArgumentValueCompleter;\n}>;\n\ntype ResourceTemplateArgument = Readonly<{\n name: string;\n description?: string;\n complete?: ArgumentValueCompleter;\n}>;\n\ntype ResourceTemplate<\n Arguments extends ResourceTemplateArgument[] = ResourceTemplateArgument[],\n> = {\n uriTemplate: string;\n name: string;\n description?: string;\n mimeType?: string;\n arguments: Arguments;\n complete?: (name: string, value: string) => Promise<Completion>;\n load: (\n args: ResourceTemplateArgumentsToObject<Arguments>,\n ) => Promise<ResourceResult>;\n};\n\ntype ResourceTemplateArgumentsToObject<T extends { name: string }[]> = {\n [K in T[number][\"name\"]]: string;\n};\n\ntype InputResourceTemplate<\n Arguments extends ResourceTemplateArgument[] = ResourceTemplateArgument[],\n> = {\n uriTemplate: string;\n name: string;\n description?: string;\n mimeType?: string;\n arguments: Arguments;\n load: (\n args: ResourceTemplateArgumentsToObject<Arguments>,\n ) => Promise<ResourceResult>;\n};\n\ntype Resource = {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n load: () => Promise<ResourceResult | ResourceResult[]>;\n complete?: (name: string, value: string) => Promise<Completion>;\n};\n\ntype ArgumentValueCompleter = (value: string) => Promise<Completion>;\n\ntype InputPromptArgument = Readonly<{\n name: string;\n description?: string;\n required?: boolean;\n complete?: ArgumentValueCompleter;\n enum?: string[];\n}>;\n\ntype PromptArgumentsToObject<T extends { name: string; required?: boolean }[]> =\n {\n [K in T[number][\"name\"]]: Extract<\n T[number],\n { name: K }\n >[\"required\"] extends true\n ? string\n : string | undefined;\n };\n\ntype InputPrompt<\n Arguments extends InputPromptArgument[] = InputPromptArgument[],\n Args = PromptArgumentsToObject<Arguments>,\n> = {\n name: string;\n description?: string;\n arguments?: InputPromptArgument[];\n load: (args: Args) => Promise<string>;\n};\n\ntype PromptArgument = Readonly<{\n name: string;\n description?: string;\n required?: boolean;\n complete?: ArgumentValueCompleter;\n enum?: string[];\n}>;\n\ntype Prompt<\n Arguments extends PromptArgument[] = PromptArgument[],\n Args = PromptArgumentsToObject<Arguments>,\n> = {\n arguments?: PromptArgument[];\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (args: Args) => Promise<string>;\n name: string;\n};\n\ntype ServerOptions<T extends FastMCPSessionAuth> = {\n name: string;\n version: `${number}.${number}.${number}`;\n authenticate?: Authenticate<T>;\n};\n\ntype LoggingLevel =\n | \"debug\"\n | \"info\"\n | \"notice\"\n | \"warning\"\n | \"error\"\n | \"critical\"\n | \"alert\"\n | \"emergency\";\n\nconst FastMCPSessionEventEmitterBase: {\n new (): StrictEventEmitter<EventEmitter, FastMCPSessionEvents>;\n} = EventEmitter;\n\nclass FastMCPSessionEventEmitter extends FastMCPSessionEventEmitterBase {}\n\ntype SamplingResponse = {\n model: string;\n stopReason?: \"endTurn\" | \"stopSequence\" | \"maxTokens\" | string;\n role: \"user\" | \"assistant\";\n content: TextContent | ImageContent | AudioContent;\n};\n\ntype FastMCPSessionAuth = Record<string, unknown> | undefined;\n\nexport class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> extends FastMCPSessionEventEmitter {\n #capabilities: ServerCapabilities = {};\n #clientCapabilities?: ClientCapabilities;\n #loggingLevel: LoggingLevel = \"info\";\n #prompts: Prompt[] = [];\n #resources: Resource[] = [];\n #resourceTemplates: ResourceTemplate[] = [];\n #roots: Root[] = [];\n #server: Server;\n #auth: T | undefined;\n\n constructor({\n auth,\n name,\n version,\n tools,\n resources,\n resourcesTemplates,\n prompts,\n }: {\n auth?: T;\n name: string;\n version: string;\n tools: Tool<T>[];\n resources: Resource[];\n resourcesTemplates: InputResourceTemplate[];\n prompts: Prompt[];\n }) {\n super();\n\n this.#auth = auth;\n\n if (tools.length) {\n this.#capabilities.tools = {};\n }\n\n if (resources.length || resourcesTemplates.length) {\n this.#capabilities.resources = {};\n }\n\n if (prompts.length) {\n for (const prompt of prompts) {\n this.addPrompt(prompt);\n }\n\n this.#capabilities.prompts = {};\n }\n\n this.#capabilities.logging = {};\n\n this.#server = new Server(\n { name: name, version: version },\n { capabilities: this.#capabilities },\n );\n\n this.setupErrorHandling();\n this.setupLoggingHandlers();\n this.setupRootsHandlers();\n this.setupCompleteHandlers();\n\n if (tools.length) {\n this.setupToolHandlers(tools);\n }\n\n if (resources.length || resourcesTemplates.length) {\n for (const resource of resources) {\n this.addResource(resource);\n }\n\n this.setupResourceHandlers(resources);\n\n if (resourcesTemplates.length) {\n for (const resourceTemplate of resourcesTemplates) {\n this.addResourceTemplate(resourceTemplate);\n }\n\n this.setupResourceTemplateHandlers(resourcesTemplates);\n }\n }\n\n if (prompts.length) {\n this.setupPromptHandlers(prompts);\n }\n }\n\n private addResource(inputResource: Resource) {\n this.#resources.push(inputResource);\n }\n\n private addResourceTemplate(inputResourceTemplate: InputResourceTemplate) {\n const completers: Record<string, ArgumentValueCompleter> = {};\n\n for (const argument of inputResourceTemplate.arguments ?? []) {\n if (argument.complete) {\n completers[argument.name] = argument.complete;\n }\n }\n\n const resourceTemplate = {\n ...inputResourceTemplate,\n complete: async (name: string, value: string) => {\n if (completers[name]) {\n return await completers[name](value);\n }\n\n return {\n values: [],\n };\n },\n };\n\n this.#resourceTemplates.push(resourceTemplate);\n }\n\n private addPrompt(inputPrompt: InputPrompt) {\n const completers: Record<string, ArgumentValueCompleter> = {};\n const enums: Record<string, string[]> = {};\n\n for (const argument of inputPrompt.arguments ?? []) {\n if (argument.complete) {\n completers[argument.name] = argument.complete;\n }\n\n if (argument.enum) {\n enums[argument.name] = argument.enum;\n }\n }\n\n const prompt = {\n ...inputPrompt,\n complete: async (name: string, value: string) => {\n if (completers[name]) {\n return await completers[name](value);\n }\n\n if (enums[name]) {\n const fuse = new Fuse(enums[name], {\n keys: [\"value\"],\n });\n\n const result = fuse.search(value);\n\n return {\n values: result.map((item) => item.item),\n total: result.length,\n };\n }\n\n return {\n values: [],\n };\n },\n };\n\n this.#prompts.push(prompt);\n }\n\n public get clientCapabilities(): ClientCapabilities | null {\n return this.#clientCapabilities ?? null;\n }\n\n public get server(): Server {\n return this.#server;\n }\n\n #pingInterval: ReturnType<typeof setInterval> | null = null;\n\n public async requestSampling(\n message: z.infer<typeof CreateMessageRequestSchema>[\"params\"],\n ): Promise<SamplingResponse> {\n return this.#server.createMessage(message);\n }\n\n public async connect(transport: Transport) {\n if (this.#server.transport) {\n throw new UnexpectedStateError(\"Server is already connected\");\n }\n\n await this.#server.connect(transport);\n\n let attempt = 0;\n\n while (attempt++ < 10) {\n const capabilities = await this.#server.getClientCapabilities();\n\n if (capabilities) {\n this.#clientCapabilities = capabilities;\n\n break;\n }\n\n await delay(100);\n }\n\n if (!this.#clientCapabilities) {\n console.warn('[FastMCP warning] could not infer client capabilities')\n }\n\n if (this.#clientCapabilities?.roots?.listChanged) {\n try {\n const roots = await this.#server.listRoots();\n this.#roots = roots.roots;\n } catch(e) {\n console.error(`[FastMCP error] received error listing roots.\\n\\n${e instanceof Error ? e.stack : JSON.stringify(e)}`)\n }\n }\n\n if (this.#clientCapabilities) {\n this.#pingInterval = setInterval(async () => {\n try {\n await this.#server.ping();\n } catch {\n // The reason we are not emitting an error here is because some clients\n // seem to not respond to the ping request, and we don't want to crash the server,\n // e.g., https://github.com/punkpeye/fastmcp/issues/38. \n console.warn(\"[FastMCP warning] server is not responding to ping\")\n }\n }, 1000);\n }\n }\n\n public get roots(): Root[] {\n return this.#roots;\n }\n\n public async close() {\n if (this.#pingInterval) {\n clearInterval(this.#pingInterval);\n }\n\n try {\n await this.#server.close();\n } catch (error) {\n console.error(\"[FastMCP error]\", \"could not close server\", error);\n }\n }\n\n private setupErrorHandling() {\n this.#server.onerror = (error) => {\n console.error(\"[FastMCP error]\", error);\n };\n }\n\n public get loggingLevel(): LoggingLevel {\n return this.#loggingLevel;\n }\n\n private setupCompleteHandlers() {\n this.#server.setRequestHandler(CompleteRequestSchema, async (request) => {\n if (request.params.ref.type === \"ref/prompt\") {\n const prompt = this.#prompts.find(\n (prompt) => prompt.name === request.params.ref.name,\n );\n\n if (!prompt) {\n throw new UnexpectedStateError(\"Unknown prompt\", {\n request,\n });\n }\n\n if (!prompt.complete) {\n throw new UnexpectedStateError(\"Prompt does not support completion\", {\n request,\n });\n }\n\n const completion = CompletionZodSchema.parse(\n await prompt.complete(\n request.params.argument.name,\n request.params.argument.value,\n ),\n );\n\n return {\n completion,\n };\n }\n\n if (request.params.ref.type === \"ref/resource\") {\n const resource = this.#resourceTemplates.find(\n (resource) => resource.uriTemplate === request.params.ref.uri,\n );\n\n if (!resource) {\n throw new UnexpectedStateError(\"Unknown resource\", {\n request,\n });\n }\n\n if (!(\"uriTemplate\" in resource)) {\n throw new UnexpectedStateError(\"Unexpected resource\");\n }\n\n if (!resource.complete) {\n throw new UnexpectedStateError(\n \"Resource does not support completion\",\n {\n request,\n },\n );\n }\n\n const completion = CompletionZodSchema.parse(\n await resource.complete(\n request.params.argument.name,\n request.params.argument.value,\n ),\n );\n\n return {\n completion,\n };\n }\n\n throw new UnexpectedStateError(\"Unexpected completion request\", {\n request,\n });\n });\n }\n\n private setupRootsHandlers() {\n this.#server.setNotificationHandler(\n RootsListChangedNotificationSchema,\n () => {\n this.#server.listRoots().then((roots) => {\n this.#roots = roots.roots;\n\n this.emit(\"rootsChanged\", {\n roots: roots.roots,\n });\n });\n },\n );\n }\n\n private setupLoggingHandlers() {\n this.#server.setRequestHandler(SetLevelRequestSchema, (request) => {\n this.#loggingLevel = request.params.level;\n\n return {};\n });\n }\n\n private setupToolHandlers(tools: Tool<T>[]) {\n this.#server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: await Promise.all(tools.map(async (tool) => {\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.parameters\n ? await toJsonSchema(tool.parameters)\n : undefined,\n };\n })),\n };\n });\n\n this.#server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const tool = tools.find((tool) => tool.name === request.params.name);\n\n if (!tool) {\n throw new McpError(\n ErrorCode.MethodNotFound,\n `Unknown tool: ${request.params.name}`,\n );\n }\n\n let args: any = undefined;\n\n if (tool.parameters) {\n const parsed = await tool.parameters[\"~standard\"].validate(\n request.params.arguments\n );\n\n if (parsed.issues) {\n throw new McpError(\n ErrorCode.InvalidParams,\n `Invalid ${request.params.name} parameters`,\n );\n }\n\n args = parsed.value;\n }\n\n const progressToken = request.params?._meta?.progressToken;\n\n let result: ContentResult;\n\n try {\n const reportProgress = async (progress: Progress) => {\n await this.#server.notification({\n method: \"notifications/progress\",\n params: {\n ...progress,\n progressToken,\n },\n });\n };\n\n const log = {\n debug: (message: string, context?: SerializableValue) => {\n this.#server.sendLoggingMessage({\n level: \"debug\",\n data: {\n message,\n context,\n },\n });\n },\n error: (message: string, context?: SerializableValue) => {\n this.#server.sendLoggingMessage({\n level: \"error\",\n data: {\n message,\n context,\n },\n });\n },\n info: (message: string, context?: SerializableValue) => {\n this.#server.sendLoggingMessage({\n level: \"info\",\n data: {\n message,\n context,\n },\n });\n },\n warn: (message: string, context?: SerializableValue) => {\n this.#server.sendLoggingMessage({\n level: \"warning\",\n data: {\n message,\n context,\n },\n });\n },\n };\n\n const maybeStringResult = await tool.execute(args, {\n reportProgress,\n log,\n session: this.#auth,\n });\n\n if (typeof maybeStringResult === \"string\") {\n result = ContentResultZodSchema.parse({\n content: [{ type: \"text\", text: maybeStringResult }],\n });\n } else if (\"type\" in maybeStringResult) {\n result = ContentResultZodSchema.parse({\n content: [maybeStringResult],\n });\n } else {\n result = ContentResultZodSchema.parse(maybeStringResult);\n }\n } catch (error) {\n if (error instanceof UserError) {\n return {\n content: [{ type: \"text\", text: error.message }],\n isError: true,\n };\n }\n\n return {\n content: [{ type: \"text\", text: `Error: ${error}` }],\n isError: true,\n };\n }\n\n return result;\n });\n }\n\n private setupResourceHandlers(resources: Resource[]) {\n this.#server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return {\n resources: resources.map((resource) => {\n return {\n uri: resource.uri,\n name: resource.name,\n mimeType: resource.mimeType,\n };\n }),\n };\n });\n\n this.#server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request) => {\n if (\"uri\" in request.params) {\n const resource = resources.find(\n (resource) =>\n \"uri\" in resource && resource.uri === request.params.uri,\n );\n\n if (!resource) {\n for (const resourceTemplate of this.#resourceTemplates) {\n const uriTemplate = parseURITemplate(\n resourceTemplate.uriTemplate,\n );\n\n const match = uriTemplate.fromUri(request.params.uri);\n\n if (!match) {\n continue;\n }\n\n const uri = uriTemplate.fill(match);\n\n const result = await resourceTemplate.load(match);\n\n return {\n contents: [\n {\n uri: uri,\n mimeType: resourceTemplate.mimeType,\n name: resourceTemplate.name,\n ...result,\n },\n ],\n };\n }\n\n throw new McpError(\n ErrorCode.MethodNotFound,\n `Unknown resource: ${request.params.uri}`,\n );\n }\n\n if (!(\"uri\" in resource)) {\n throw new UnexpectedStateError(\"Resource does not support reading\");\n }\n\n let maybeArrayResult: Awaited<ReturnType<Resource[\"load\"]>>;\n\n try {\n maybeArrayResult = await resource.load();\n } catch (error) {\n throw new McpError(\n ErrorCode.InternalError,\n `Error reading resource: ${error}`,\n {\n uri: resource.uri,\n },\n );\n }\n\n if (Array.isArray(maybeArrayResult)) {\n return {\n contents: maybeArrayResult.map((result) => ({\n uri: resource.uri,\n mimeType: resource.mimeType,\n name: resource.name,\n ...result,\n })),\n };\n } else {\n return {\n contents: [\n {\n uri: resource.uri,\n mimeType: resource.mimeType,\n name: resource.name,\n ...maybeArrayResult,\n },\n ],\n };\n }\n }\n\n throw new UnexpectedStateError(\"Unknown resource request\", {\n request,\n });\n },\n );\n }\n\n private setupResourceTemplateHandlers(resourceTemplates: ResourceTemplate[]) {\n this.#server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n async () => {\n return {\n resourceTemplates: resourceTemplates.map((resourceTemplate) => {\n return {\n name: resourceTemplate.name,\n uriTemplate: resourceTemplate.uriTemplate,\n };\n }),\n };\n },\n );\n }\n\n private setupPromptHandlers(prompts: Prompt[]) {\n this.#server.setRequestHandler(ListPromptsRequestSchema, async () => {\n return {\n prompts: prompts.map((prompt) => {\n return {\n name: prompt.name,\n description: prompt.description,\n arguments: prompt.arguments,\n complete: prompt.complete,\n };\n }),\n };\n });\n\n this.#server.setRequestHandler(GetPromptRequestSchema, async (request) => {\n const prompt = prompts.find(\n (prompt) => prompt.name === request.params.name,\n );\n\n if (!prompt) {\n throw new McpError(\n ErrorCode.MethodNotFound,\n `Unknown prompt: ${request.params.name}`,\n );\n }\n\n const args = request.params.arguments;\n\n for (const arg of prompt.arguments ?? []) {\n if (arg.required && !(args && arg.name in args)) {\n throw new McpError(\n ErrorCode.InvalidRequest,\n `Missing required argument: ${arg.name}`,\n );\n }\n }\n\n let result: Awaited<ReturnType<Prompt[\"load\"]>>;\n\n try {\n result = await prompt.load(args as Record<string, string | undefined>);\n } catch (error) {\n throw new McpError(\n ErrorCode.InternalError,\n `Error loading prompt: ${error}`,\n );\n }\n\n return {\n description: prompt.description,\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text: result },\n },\n ],\n };\n });\n }\n}\n\nconst FastMCPEventEmitterBase: {\n new (): StrictEventEmitter<EventEmitter, FastMCPEvents<FastMCPSessionAuth>>;\n} = EventEmitter;\n\nclass FastMCPEventEmitter extends FastMCPEventEmitterBase {}\n\ntype Authenticate<T> = (request: http.IncomingMessage) => Promise<T>;\n\nexport class FastMCP<T extends Record<string, unknown> | undefined = undefined> extends FastMCPEventEmitter {\n #options: ServerOptions<T>;\n #prompts: InputPrompt[] = [];\n #resources: Resource[] = [];\n #resourcesTemplates: InputResourceTemplate[] = [];\n #sessions: FastMCPSession<T>[] = [];\n #sseServer: SSEServer | null = null;\n #tools: Tool<T>[] = [];\n #authenticate: Authenticate<T> | undefined;\n\n constructor(public options: ServerOptions<T>) {\n super();\n\n this.#options = options;\n this.#authenticate = options.authenticate;\n }\n\n public get sessions(): FastMCPSession<T>[] {\n return this.#sessions;\n }\n\n /**\n * Adds a tool to the server.\n */\n public addTool<Params extends ToolParameters>(tool: Tool<T, Params>) {\n this.#tools.push(tool as unknown as Tool<T>);\n }\n\n /**\n * Adds a resource to the server.\n */\n public addResource(resource: Resource) {\n this.#resources.push(resource);\n }\n\n /**\n * Adds a resource template to the server.\n */\n public addResourceTemplate<\n const Args extends InputResourceTemplateArgument[],\n >(resource: InputResourceTemplate<Args>) {\n this.#resourcesTemplates.push(resource);\n }\n\n /**\n * Adds a prompt to the server.\n */\n public addPrompt<const Args extends InputPromptArgument[]>(\n prompt: InputPrompt<Args>,\n ) {\n this.#prompts.push(prompt);\n }\n\n /**\n * Starts the server.\n */\n public async start(\n options:\n | { transportType: \"stdio\" }\n | {\n transportType: \"sse\";\n sse: { endpoint: `/${string}`; port: number };\n } = {\n transportType: \"stdio\",\n },\n ) {\n if (options.transportType === \"stdio\") {\n const transport = new StdioServerTransport();\n\n const session = new FastMCPSession<T>({\n name: this.#options.name,\n version: this.#options.version,\n tools: this.#tools,\n resources: this.#resources,\n resourcesTemplates: this.#resourcesTemplates,\n prompts: this.#prompts,\n });\n\n await session.connect(transport);\n\n this.#sessions.push(session);\n\n this.emit(\"connect\", {\n session,\n });\n\n } else if (options.transportType === \"sse\") {\n this.#sseServer = await startSSEServer<FastMCPSession<T>>({\n endpoint: options.sse.endpoint as `/${string}`,\n port: options.sse.port,\n createServer: async (request) => {\n let auth: T | undefined;\n\n if (this.#authenticate) {\n auth = await this.#authenticate(request);\n }\n\n return new FastMCPSession<T>({\n auth,\n name: this.#options.name,\n version: this.#options.version,\n tools: this.#tools,\n resources: this.#resources,\n resourcesTemplates: this.#resourcesTemplates,\n prompts: this.#prompts,\n });\n },\n onClose: (session) => {\n this.emit(\"disconnect\", {\n session,\n });\n },\n onConnect: async (session) => {\n this.#sessions.push(session);\n\n this.emit(\"connect\", {\n session,\n });\n },\n });\n\n console.info(\n `[FastMCP info] server is running on SSE at http://localhost:${options.sse.port}${options.sse.endpoint}`,\n );\n } else {\n throw new Error(\"Invalid transport type\");\n }\n }\n\n /**\n * Stops the server.\n */\n public async stop() {\n if (this.#sseServer) {\n this.#sseServer.close();\n }\n }\n}\n\nexport type { Context };\nexport type { Tool, ToolParameters };\nexport type { Content, TextContent, ImageContent, ContentResult };\nexport type { Progress, SerializableValue };\nexport type { Resource, ResourceResult };\nexport type { ResourceTemplate, ResourceTemplateArgument };\nexport type { Prompt, PromptArgument };\nexport type { InputPrompt, InputPromptArgument };\nexport type { ServerOptions, LoggingLevel };\nexport type { FastMCPEvents, FastMCPSessionEvents };\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EAEE;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,cAAc,aAAa;AACpC,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAC7B,OAAO,UAAU;AACjB,SAAS,sBAAsB;AAE/B,OAAO,sBAAsB;AAE7B;AAAA,EACE;AAAA,OACK;AAmBA,IAAM,eAAe,OAC1B,UAC0B;AAC1B,MAAI;AAEJ,MAAI,SAAS,OAAO;AAClB,UAAM,WAAW,MAAM,MAAM,MAAM,GAAG;AAEtC,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,IAAI,MAAM,mCAAmC,SAAS,UAAU,EAAE;AAAA,IAC1E;AAEA,cAAU,OAAO,KAAK,MAAM,SAAS,YAAY,CAAC;AAAA,EACpD,WAAW,UAAU,OAAO;AAC1B,cAAU,MAAM,SAAS,MAAM,IAAI;AAAA,EACrC,WAAW,YAAY,OAAO;AAC5B,cAAU,MAAM;AAAA,EAClB,OAAO;AACL,U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sources":["../src/FastMCP.ts"],"sourcesContent":["import { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n AudioContent,\n CallToolRequestSchema,\n ClientCapabilities,\n CompleteRequestSchema,\n CreateMessageRequestSchema,\n ErrorCode,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n Root,\n RootsListChangedNotificationSchema,\n ServerCapabilities,\n SetLevelRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { toJsonSchema } from \"xsschema\";\nimport { z } from \"zod\";\nimport { setTimeout as delay } from \"timers/promises\";\nimport { readFile } from \"fs/promises\";\nimport { fileTypeFromBuffer } from \"file-type\";\nimport { StrictEventEmitter } from \"strict-event-emitter-types\";\nimport { EventEmitter } from \"events\";\nimport Fuse from \"fuse.js\";\nimport { startSSEServer } from \"mcp-proxy\";\nimport { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport parseURITemplate from \"uri-templates\";\nimport http from \"http\";\nimport { fetch } from \"undici\";\n\nexport type SSEServer = {\n close: () => Promise<void>;\n};\n\ntype FastMCPEvents<T extends FastMCPSessionAuth> = {\n connect: (event: { session: FastMCPSession<T> }) => void;\n disconnect: (event: { session: FastMCPSession<T> }) => void;\n};\n\ntype FastMCPSessionEvents = {\n rootsChanged: (event: { roots: Root[] }) => void;\n error: (event: { error: Error }) => void;\n};\n\n/**\n * Generates an image content object from a URL, file path, or buffer.\n */\nexport const imageContent = async (\n input: { url: string } | { path: string } | { buffer: Buffer },\n): Promise<ImageContent> => {\n let rawData: Buffer;\n\n if (\"url\" in input) {\n const response = await fetch(input.url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch image from URL: ${response.statusText}`);\n }\n\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in input) {\n rawData = await readFile(input.path);\n } else if (\"buffer\" in input) {\n rawData = input.buffer;\n } else {\n throw new Error(\n \"Invalid input: Provide a valid 'url', 'path', or 'buffer'\",\n );\n }\n\n const mimeType = await fileTypeFromBuffer(rawData);\n\n const base64Data = rawData.toString(\"base64\");\n\n return {\n type: \"image\",\n data: base64Data,\n mimeType: mimeType?.mime ?? \"image/png\",\n } as const;\n};\n\nexport const audioContent = async (\n input: { url: string } | { path: string } | { buffer: Buffer },\n): Promise<AudioContent> => {\n let rawData: Buffer;\n\n if (\"url\" in input) {\n const response = await fetch(input.url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch audio from URL: ${response.statusText}`);\n }\n\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in input) {\n rawData = await readFile(input.path);\n } else if (\"buffer\" in input) {\n rawData = input.buffer;\n } else {\n throw new Error(\n \"Invalid input: Provide a valid 'url', 'path', or 'buffer'\",\n );\n }\n\n const mimeType = await fileTypeFromBuffer(rawData);\n\n const base64Data = rawData.toString(\"base64\");\n\n return {\n type: \"audio\",\n data: base64Data,\n mimeType: mimeType?.mime ?? \"audio/mpeg\",\n } as const;\n};\n\nabstract class FastMCPError extends Error {\n public constructor(message?: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\ntype Extra = unknown;\n\ntype Extras = Record<string, Extra>;\n\nexport class UnexpectedStateError extends FastMCPError {\n public extras?: Extras;\n\n public constructor(message: string, extras?: Extras) {\n super(message);\n this.name = new.target.name;\n this.extras = extras;\n }\n}\n\n/**\n * An error that is meant to be surfaced to the user.\n */\nexport class UserError extends UnexpectedStateError {}\n\ntype ToolParameters = StandardSchemaV1;\n\ntype Literal = boolean | null | number | string | undefined;\n\ntype SerializableValue =\n | Literal\n | SerializableValue[]\n | { [key: string]: SerializableValue };\n\ntype Progress = {\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: number;\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total?: number;\n};\n\ntype Context<T extends FastMCPSessionAuth> = {\n session: T | undefined;\n reportProgress: (progress: Progress) => Promise<void>;\n log: {\n debug: (message: string, data?: SerializableValue) => void;\n error: (message: string, data?: SerializableValue) => void;\n info: (message: string, data?: SerializableValue) => void;\n warn: (message: string, data?: SerializableValue) => void;\n };\n};\n\ntype TextContent = {\n type: \"text\";\n text: string;\n};\n\nconst TextContentZodSchema = z\n .object({\n type: z.literal(\"text\"),\n /**\n * The text content of the message.\n */\n text: z.string(),\n })\n .strict() satisfies z.ZodType<TextContent>;\n\ntype ImageContent = {\n type: \"image\";\n data: string;\n mimeType: string;\n};\n\nconst ImageContentZodSchema = z\n .object({\n type: z.literal(\"image\"),\n /**\n * The base64-encoded image data.\n */\n data: z.string().base64(),\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n })\n .strict() satisfies z.ZodType<ImageContent>;\n\ntype Content = TextContent | ImageContent;\n\nconst ContentZodSchema = z.discriminatedUnion(\"type\", [\n TextContentZodSchema,\n ImageContentZodSchema,\n]) satisfies z.ZodType<Content>;\n\ntype ContentResult = {\n content: Content[];\n isError?: boolean;\n};\n\nconst ContentResultZodSchema = z\n .object({\n content: ContentZodSchema.array(),\n isError: z.boolean().optional(),\n })\n .strict() satisfies z.ZodType<ContentResult>;\n\ntype Completion = {\n values: string[];\n total?: number;\n hasMore?: boolean;\n};\n\n/**\n * https://github.com/modelcontextprotocol/typescript-sdk/blob/3164da64d085ec4e022ae881329eee7b72f208d4/src/types.ts#L983-L1003\n */\nconst CompletionZodSchema = z.object({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean()),\n}) satisfies z.ZodType<Completion>;\n\n/**\n * Tool annotations as defined in MCP Specification (2025-03-26)\n * These provide hints about a tool's behavior.\n */\ntype ToolAnnotations = {\n /**\n * A human-readable title for the tool, useful for UI display\n */\n title?: string;\n\n /**\n * If true, indicates the tool does not modify its environment\n * @default false\n */\n readOnlyHint?: boolean;\n\n /**\n * If true, the tool may perform destructive updates\n * Only meaningful when readOnlyHint is false\n * @default true\n */\n destructiveHint?: boolean;\n\n /**\n * If true, calling the tool repeatedly with the same arguments has no additional effect\n * Only meaningful when readOnlyHint is false\n * @default false\n */\n idempotentHint?: boolean;\n\n /**\n * If true, the tool may interact with an \"open world\" of external entities\n * @default true\n */\n openWorldHint?: boolean;\n};\n\ntype Tool<\n T extends FastMCPSessionAuth,\n Params extends ToolParameters = ToolParameters,\n> = {\n name: string;\n description?: string;\n parameters?: Params;\n annotations?: ToolAnnotations;\n execute: (\n args: StandardSchemaV1.InferOutput<Params>,\n context: Context<T>,\n ) => Promise<\n string | ContentResult | TextContent | ImageContent | AudioContent\n >;\n};\n\ntype ResourceResult =\n | {\n text: string;\n }\n | {\n blob: string;\n };\n\ntype InputResourceTemplateArgument = Readonly<{\n name: string;\n description?: string;\n complete?: ArgumentValueCompleter;\n}>;\n\ntype ResourceTemplateArgument = Readonly<{\n name: string;\n description?: string;\n complete?: ArgumentValueCompleter;\n}>;\n\ntype ResourceTemplate<\n Arguments extends ResourceTemplateArgument[] = ResourceTemplateArgument[],\n> = {\n uriTemplate: string;\n name: string;\n description?: string;\n mimeType?: string;\n arguments: Arguments;\n complete?: (name: string, value: string) => Promise<Completion>;\n load: (\n args: ResourceTemplateArgumentsToObject<Arguments>,\n ) => Promise<ResourceResult>;\n};\n\ntype ResourceTemplateArgumentsToObject<T extends { name: string }[]> = {\n [K in T[number][\"name\"]]: string;\n};\n\ntype InputResourceTemplate<\n Arguments extends ResourceTemplateArgument[] = ResourceTemplateArgument[],\n> = {\n uriTemplate: string;\n name: string;\n description?: string;\n mimeType?: string;\n arguments: Arguments;\n load: (\n args: ResourceTemplateArgumentsToObject<Arguments>,\n ) => Promise<ResourceResult>;\n};\n\ntype Resource = {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n load: () => Promise<ResourceResult | ResourceResult[]>;\n complete?: (name: string, value: string) => Promise<Completion>;\n};\n\ntype ArgumentValueCompleter = (value: string) => Promise<Completion>;\n\ntype InputPromptArgument = Readonly<{\n name: string;\n description?: string;\n required?: boolean;\n complete?: ArgumentValueCompleter;\n enum?: string[];\n}>;\n\ntype PromptArgumentsToObject<T extends { name: string; required?: boolean }[]> =\n {\n [K in T[number][\"name\"]]: Extract<\n T[number],\n { name: K }\n >[\"required\"] extends true\n ? string\n : string | undefined;\n };\n\ntype InputPrompt<\n Arguments extends InputPromptArgument[] = InputPromptArgument[],\n Args = PromptArgumentsToObject<Arguments>,\n> = {\n name: string;\n description?: string;\n arguments?: InputPromptArgument[];\n load: (args: Args) => Promise<string>;\n};\n\ntype PromptArgument = Readonly<{\n name: string;\n description?: string;\n required?: boolean;\n complete?: ArgumentValueCompleter;\n enum?: string[];\n}>;\n\ntype Prompt<\n Arguments extends PromptArgument[] = PromptArgument[],\n Args = PromptArgumentsToObject<Arguments>,\n> = {\n arguments?: PromptArgument[];\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (args: Args) => Promise<string>;\n name: string;\n};\n\ntype ServerOptions<T extends FastMCPSessionAuth> = {\n name: string;\n version: `${number}.${number}.${number}`;\n authenticate?: Authenticate<T>;\n instructions?: string;\n};\n\ntype LoggingLevel =\n | \"debug\"\n | \"info\"\n | \"notice\"\n | \"warning\"\n | \"error\"\n | \"critical\"\n | \"alert\"\n | \"emergency\";\n\nconst FastMCPSessionEventEmitterBase: {\n new (): StrictEventEmitter<EventEmitter, FastMCPSessionEvents>;\n} = EventEmitter;\n\nclass FastMCPSessionEventEmitter extends FastMCPSessionEventEmitterBase {}\n\ntype SamplingResponse = {\n model: string;\n stopReason?: \"endTurn\" | \"stopSequence\" | \"maxTokens\" | string;\n role: \"user\" | \"assistant\";\n content: TextContent | ImageContent | AudioContent;\n};\n\ntype FastMCPSessionAuth = Record<string, unknown> | undefined;\n\nexport class FastMCPSession<\n T extends FastMCPSessionAuth = FastMCPSessionAuth,\n> extends FastMCPSessionEventEmitter {\n #capabilities: ServerCapabilities = {};\n #clientCapabilities?: ClientCapabilities;\n #loggingLevel: LoggingLevel = \"info\";\n #prompts: Prompt[] = [];\n #resources: Resource[] = [];\n #resourceTemplates: ResourceTemplate[] = [];\n #roots: Root[] = [];\n #server: Server;\n #auth: T | undefined;\n\n constructor({\n auth,\n name,\n version,\n instructions,\n tools,\n resources,\n resourcesTemplates,\n prompts,\n }: {\n auth?: T;\n name: string;\n version: string;\n instructions?: string;\n tools: Tool<T>[];\n resources: Resource[];\n resourcesTemplates: InputResourceTemplate[];\n prompts: Prompt[];\n }) {\n super();\n\n this.#auth = auth;\n\n if (tools.length) {\n this.#capabilities.tools = {};\n }\n\n if (resources.length || resourcesTemplates.length) {\n this.#capabilities.resources = {};\n }\n\n if (prompts.length) {\n for (const prompt of prompts) {\n this.addPrompt(prompt);\n }\n\n this.#capabilities.prompts = {};\n }\n\n this.#capabilities.logging = {};\n\n this.#server = new Server(\n { name: name, version: version },\n { capabilities: this.#capabilities, instructions: instructions },\n );\n\n this.setupErrorHandling();\n this.setupLoggingHandlers();\n this.setupRootsHandlers();\n this.setupCompleteHandlers();\n\n if (tools.length) {\n this.setupToolHandlers(tools);\n }\n\n if (resources.length || resourcesTemplates.length) {\n for (const resource of resources) {\n this.addResource(resource);\n }\n\n this.setupResourceHandlers(resources);\n\n if (resourcesTemplates.length) {\n for (const resourceTemplate of resourcesTemplates) {\n this.addResourceTemplate(resourceTemplate);\n }\n\n this.setupResourceTemplateHandlers(resourcesTemplates);\n }\n }\n\n if (prompts.length) {\n this.setupPromptHandlers(prompts);\n }\n }\n\n private addResource(inputResource: Resource) {\n this.#resources.push(inputResource);\n }\n\n private addResourceTemplate(inputResourceTemplate: InputResourceTemplate) {\n const completers: Record<string, ArgumentValueCompleter> = {};\n\n for (const argument of inputResourceTemplate.arguments ?? []) {\n if (argument.complete) {\n completers[argument.name] = argument.complete;\n }\n }\n\n const resourceTemplate = {\n ...inputResourceTemplate,\n complete: async (name: string, value: string) => {\n if (completers[name]) {\n return await completers[name](value);\n }\n\n return {\n values: [],\n };\n },\n };\n\n this.#resourceTemplates.push(resourceTemplate);\n }\n\n private addPrompt(inputPrompt: InputPrompt) {\n const completers: Record<string, ArgumentValueCompleter> = {};\n const enums: Record<string, string[]> = {};\n\n for (const argument of inputPrompt.arguments ?? []) {\n if (argument.complete) {\n completers[argument.name] = argument.complete;\n }\n\n if (argument.enum) {\n enums[argument.name] = argument.enum;\n }\n }\n\n const prompt = {\n ...inputPrompt,\n complete: async (name: string, value: string) => {\n if (completers[name]) {\n return await completers[name](value);\n }\n\n if (enums[name]) {\n const fuse = new Fuse(enums[name], {\n keys: [\"value\"],\n });\n\n const result = fuse.search(value);\n\n return {\n values: result.map((item) => item.item),\n total: result.length,\n };\n }\n\n return {\n values: [],\n };\n },\n };\n\n this.#prompts.push(prompt);\n }\n\n public get clientCapabilities(): ClientCapabilities | null {\n return this.#clientCapabilities ?? null;\n }\n\n public get server(): Server {\n return this.#server;\n }\n\n #pingInterval: ReturnType<typeof setInterval> | null = null;\n\n public async requestSampling(\n message: z.infer<typeof CreateMessageRequestSchema>[\"params\"],\n ): Promise<SamplingResponse> {\n return this.#server.createMessage(message);\n }\n\n public async connect(transport: Transport) {\n if (this.#server.transport) {\n throw new UnexpectedStateError(\"Server is already connected\");\n }\n\n await this.#server.connect(transport);\n\n let attempt = 0;\n\n while (attempt++ < 10) {\n const capabilities = await this.#server.getClientCapabilities();\n\n if (capabilities) {\n this.#clientCapabilities = capabilities;\n\n break;\n }\n\n await delay(100);\n }\n\n if (!this.#clientCapabilities) {\n console.warn(\"[FastMCP warning] could not infer client capabilities\");\n }\n\n if (this.#clientCapabilities?.roots?.listChanged) {\n try {\n const roots = await this.#server.listRoots();\n this.#roots = roots.roots;\n } catch (e) {\n console.error(\n `[FastMCP error] received error listing roots.\\n\\n${e instanceof Error ? e.stack : JSON.stringify(e)}`,\n );\n }\n }\n\n if (this.#clientCapabilities) {\n this.#pingInterval = setInterval(async () => {\n try {\n await this.#server.ping();\n } catch {\n // The reason we are not emitting an error here is because some clients\n // seem to not respond to the ping request, and we don't want to crash the server,\n // e.g., https://github.com/punkpeye/fastmcp/issues/38.\n console.warn(\"[FastMCP warning] server is not responding to ping\");\n }\n }, 1000);\n }\n }\n\n public get roots(): Root[] {\n return this.#roots;\n }\n\n public async close() {\n if (this.#pingInterval) {\n clearInterval(this.#pingInterval);\n }\n\n try {\n await this.#server.close();\n } catch (error) {\n console.error(\"[FastMCP error]\", \"could not close server\", error);\n }\n }\n\n private setupErrorHandling() {\n this.#server.onerror = (error) => {\n console.error(\"[FastMCP error]\", error);\n };\n }\n\n public get loggingLevel(): LoggingLevel {\n return this.#loggingLevel;\n }\n\n private setupCompleteHandlers() {\n this.#server.setRequestHandler(CompleteRequestSchema, async (request) => {\n if (request.params.ref.type === \"ref/prompt\") {\n const prompt = this.#prompts.find(\n (prompt) => prompt.name === request.params.ref.name,\n );\n\n if (!prompt) {\n throw new UnexpectedStateError(\"Unknown prompt\", {\n request,\n });\n }\n\n if (!prompt.complete) {\n throw new UnexpectedStateError(\"Prompt does not support completion\", {\n request,\n });\n }\n\n const completion = CompletionZodSchema.parse(\n await prompt.complete(\n request.params.argument.name,\n request.params.argument.value,\n ),\n );\n\n return {\n completion,\n };\n }\n\n if (request.params.ref.type === \"ref/resource\") {\n const resource = this.#resourceTemplates.find(\n (resource) => resource.uriTemplate === request.params.ref.uri,\n );\n\n if (!resource) {\n throw new UnexpectedStateError(\"Unknown resource\", {\n request,\n });\n }\n\n if (!(\"uriTemplate\" in resource)) {\n throw new UnexpectedStateError(\"Unexpected resource\");\n }\n\n if (!resource.complete) {\n throw new UnexpectedStateError(\n \"Resource does not support completion\",\n {\n request,\n },\n );\n }\n\n const completion = CompletionZodSchema.parse(\n await resource.complete(\n request.params.argument.name,\n request.params.argument.value,\n ),\n );\n\n return {\n completion,\n };\n }\n\n throw new UnexpectedStateError(\"Unexpected completion request\", {\n request,\n });\n });\n }\n\n private setupRootsHandlers() {\n this.#server.setNotificationHandler(\n RootsListChangedNotificationSchema,\n () => {\n this.#server.listRoots().then((roots) => {\n this.#roots = roots.roots;\n\n this.emit(\"rootsChanged\", {\n roots: roots.roots,\n });\n });\n },\n );\n }\n\n private setupLoggingHandlers() {\n this.#server.setRequestHandler(SetLevelRequestSchema, (request) => {\n this.#loggingLevel = request.params.level;\n\n return {};\n });\n }\n\n private setupToolHandlers(tools: Tool<T>[]) {\n this.#server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: await Promise.all(\n tools.map(async (tool) => {\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.parameters\n ? await toJsonSchema(tool.parameters)\n : undefined,\n annotations: tool.annotations,\n };\n }),\n ),\n };\n });\n\n this.#server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const tool = tools.find((tool) => tool.name === request.params.name);\n\n if (!tool) {\n throw new McpError(\n ErrorCode.MethodNotFound,\n `Unknown tool: ${request.params.name}`,\n );\n }\n\n let args: any = undefined;\n\n if (tool.parameters) {\n const parsed = await tool.parameters[\"~standard\"].validate(\n request.params.arguments,\n );\n\n if (parsed.issues) {\n throw new McpError(\n ErrorCode.InvalidParams,\n `Invalid ${request.params.name} parameters`,\n );\n }\n\n args = parsed.value;\n }\n\n const progressToken = request.params?._meta?.progressToken;\n\n let result: ContentResult;\n\n try {\n const reportProgress = async (progress: Progress) => {\n await this.#server.notification({\n method: \"notifications/progress\",\n params: {\n ...progress,\n progressToken,\n },\n });\n };\n\n const log = {\n debug: (message: string, context?: SerializableValue) => {\n this.#server.sendLoggingMessage({\n level: \"debug\",\n data: {\n message,\n context,\n },\n });\n },\n error: (message: string, context?: SerializableValue) => {\n this.#server.sendLoggingMessage({\n level: \"error\",\n data: {\n message,\n context,\n },\n });\n },\n info: (message: string, context?: SerializableValue) => {\n this.#server.sendLoggingMessage({\n level: \"info\",\n data: {\n message,\n context,\n },\n });\n },\n warn: (message: string, context?: SerializableValue) => {\n this.#server.sendLoggingMessage({\n level: \"warning\",\n data: {\n message,\n context,\n },\n });\n },\n };\n\n const maybeStringResult = await tool.execute(args, {\n reportProgress,\n log,\n session: this.#auth,\n });\n\n if (typeof maybeStringResult === \"string\") {\n result = ContentResultZodSchema.parse({\n content: [{ type: \"text\", text: maybeStringResult }],\n });\n } else if (\"type\" in maybeStringResult) {\n result = ContentResultZodSchema.parse({\n content: [maybeStringResult],\n });\n } else {\n result = ContentResultZodSchema.parse(maybeStringResult);\n }\n } catch (error) {\n if (error instanceof UserError) {\n return {\n content: [{ type: \"text\", text: error.message }],\n isError: true,\n };\n }\n\n return {\n content: [{ type: \"text\", text: `Error: ${error}` }],\n isError: true,\n };\n }\n\n return result;\n });\n }\n\n private setupResourceHandlers(resources: Resource[]) {\n this.#server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return {\n resources: resources.map((resource) => {\n return {\n uri: resource.uri,\n name: resource.name,\n mimeType: resource.mimeType,\n };\n }),\n };\n });\n\n this.#server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request) => {\n if (\"uri\" in request.params) {\n const resource = resources.find(\n (resource) =>\n \"uri\" in resource && resource.uri === request.params.uri,\n );\n\n if (!resource) {\n for (const resourceTemplate of this.#resourceTemplates) {\n const uriTemplate = parseURITemplate(\n resourceTemplate.uriTemplate,\n );\n\n const match = uriTemplate.fromUri(request.params.uri);\n\n if (!match) {\n continue;\n }\n\n const uri = uriTemplate.fill(match);\n\n const result = await resourceTemplate.load(match);\n\n return {\n contents: [\n {\n uri: uri,\n mimeType: resourceTemplate.mimeType,\n name: resourceTemplate.name,\n ...result,\n },\n ],\n };\n }\n\n throw new McpError(\n ErrorCode.MethodNotFound,\n `Unknown resource: ${request.params.uri}`,\n );\n }\n\n if (!(\"uri\" in resource)) {\n throw new UnexpectedStateError(\"Resource does not support reading\");\n }\n\n let maybeArrayResult: Awaited<ReturnType<Resource[\"load\"]>>;\n\n try {\n maybeArrayResult = await resource.load();\n } catch (error) {\n throw new McpError(\n ErrorCode.InternalError,\n `Error reading resource: ${error}`,\n {\n uri: resource.uri,\n },\n );\n }\n\n if (Array.isArray(maybeArrayResult)) {\n return {\n contents: maybeArrayResult.map((result) => ({\n uri: resource.uri,\n mimeType: resource.mimeType,\n name: resource.name,\n ...result,\n })),\n };\n } else {\n return {\n contents: [\n {\n uri: resource.uri,\n mimeType: resource.mimeType,\n name: resource.name,\n ...maybeArrayResult,\n },\n ],\n };\n }\n }\n\n throw new UnexpectedStateError(\"Unknown resource request\", {\n request,\n });\n },\n );\n }\n\n private setupResourceTemplateHandlers(resourceTemplates: ResourceTemplate[]) {\n this.#server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n async () => {\n return {\n resourceTemplates: resourceTemplates.map((resourceTemplate) => {\n return {\n name: resourceTemplate.name,\n uriTemplate: resourceTemplate.uriTemplate,\n };\n }),\n };\n },\n );\n }\n\n private setupPromptHandlers(prompts: Prompt[]) {\n this.#server.setRequestHandler(ListPromptsRequestSchema, async () => {\n return {\n prompts: prompts.map((prompt) => {\n return {\n name: prompt.name,\n description: prompt.description,\n arguments: prompt.arguments,\n complete: prompt.complete,\n };\n }),\n };\n });\n\n this.#server.setRequestHandler(GetPromptRequestSchema, async (request) => {\n const prompt = prompts.find(\n (prompt) => prompt.name === request.params.name,\n );\n\n if (!prompt) {\n throw new McpError(\n ErrorCode.MethodNotFound,\n `Unknown prompt: ${request.params.name}`,\n );\n }\n\n const args = request.params.arguments;\n\n for (const arg of prompt.arguments ?? []) {\n if (arg.required && !(args && arg.name in args)) {\n throw new McpError(\n ErrorCode.InvalidRequest,\n `Missing required argument: ${arg.name}`,\n );\n }\n }\n\n let result: Awaited<ReturnType<Prompt[\"load\"]>>;\n\n try {\n result = await prompt.load(args as Record<string, string | undefined>);\n } catch (error) {\n throw new McpError(\n ErrorCode.InternalError,\n `Error loading prompt: ${error}`,\n );\n }\n\n return {\n description: prompt.description,\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text: result },\n },\n ],\n };\n });\n }\n}\n\nconst FastMCPEventEmitterBase: {\n new (): StrictEventEmitter<EventEmitter, FastMCPEvents<FastMCPSessionAuth>>;\n} = EventEmitter;\n\nclass FastMCPEventEmitter extends FastMCPEventEmitterBase {}\n\ntype Authenticate<T> = (request: http.IncomingMessage) => Promise<T>;\n\nexport class FastMCP<\n T extends Record<string, unknown> | undefined = undefined,\n> extends FastMCPEventEmitter {\n #options: ServerOptions<T>;\n #prompts: InputPrompt[] = [];\n #resources: Resource[] = [];\n #resourcesTemplates: InputResourceTemplate[] = [];\n #sessions: FastMCPSession<T>[] = [];\n #sseServer: SSEServer | null = null;\n #tools: Tool<T>[] = [];\n #authenticate: Authenticate<T> | undefined;\n\n constructor(public options: ServerOptions<T>) {\n super();\n\n this.#options = options;\n this.#authenticate = options.authenticate;\n }\n\n public get sessions(): FastMCPSession<T>[] {\n return this.#sessions;\n }\n\n /**\n * Adds a tool to the server.\n */\n public addTool<Params extends ToolParameters>(tool: Tool<T, Params>) {\n this.#tools.push(tool as unknown as Tool<T>);\n }\n\n /**\n * Adds a resource to the server.\n */\n public addResource(resource: Resource) {\n this.#resources.push(resource);\n }\n\n /**\n * Adds a resource template to the server.\n */\n public addResourceTemplate<\n const Args extends InputResourceTemplateArgument[],\n >(resource: InputResourceTemplate<Args>) {\n this.#resourcesTemplates.push(resource);\n }\n\n /**\n * Adds a prompt to the server.\n */\n public addPrompt<const Args extends InputPromptArgument[]>(\n prompt: InputPrompt<Args>,\n ) {\n this.#prompts.push(prompt);\n }\n\n /**\n * Starts the server.\n */\n public async start(\n options:\n | { transportType: \"stdio\" }\n | {\n transportType: \"sse\";\n sse: { endpoint: `/${string}`; port: number };\n } = {\n transportType: \"stdio\",\n },\n ) {\n if (options.transportType === \"stdio\") {\n const transport = new StdioServerTransport();\n\n const session = new FastMCPSession<T>({\n name: this.#options.name,\n version: this.#options.version,\n instructions: this.#options.instructions,\n tools: this.#tools,\n resources: this.#resources,\n resourcesTemplates: this.#resourcesTemplates,\n prompts: this.#prompts,\n });\n\n await session.connect(transport);\n\n this.#sessions.push(session);\n\n this.emit(\"connect\", {\n session,\n });\n } else if (options.transportType === \"sse\") {\n this.#sseServer = await startSSEServer<FastMCPSession<T>>({\n endpoint: options.sse.endpoint as `/${string}`,\n port: options.sse.port,\n createServer: async (request) => {\n let auth: T | undefined;\n\n if (this.#authenticate) {\n auth = await this.#authenticate(request);\n }\n\n return new FastMCPSession<T>({\n auth,\n name: this.#options.name,\n version: this.#options.version,\n tools: this.#tools,\n resources: this.#resources,\n resourcesTemplates: this.#resourcesTemplates,\n prompts: this.#prompts,\n });\n },\n onClose: (session) => {\n this.emit(\"disconnect\", {\n session,\n });\n },\n onConnect: async (session) => {\n this.#sessions.push(session);\n\n this.emit(\"connect\", {\n session,\n });\n },\n });\n\n console.info(\n `[FastMCP info] server is running on SSE at http://localhost:${options.sse.port}${options.sse.endpoint}`,\n );\n } else {\n throw new Error(\"Invalid transport type\");\n }\n }\n\n /**\n * Stops the server.\n */\n public async stop() {\n if (this.#sseServer) {\n this.#sseServer.close();\n }\n }\n}\n\nexport type { Context };\nexport type { Tool, ToolParameters };\nexport type { Content, TextContent, ImageContent, ContentResult };\nexport type { Progress, SerializableValue };\nexport type { Resource, ResourceResult };\nexport type { ResourceTemplate, ResourceTemplateArgument };\nexport type { Prompt, PromptArgument };\nexport type { InputPrompt, InputPromptArgument };\nexport type { ServerOptions, LoggingLevel };\nexport type { FastMCPEvents, FastMCPSessionEvents };\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EAEE;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,OACK;AAEP,SA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AK,SAAS;AAAA,YACvB,OAAO,KAAK;AAAA,YACZ,WAAW,KAAK;AAAA,YAChB,oBAAoB,KAAK;AAAA,YACzB,SAAS,KAAK;AAAA,UAChB,CAAC;AAAA,QACH;AAAA,QACA,SAAS,CAAC,YAAY;AACpB,eAAK,KAAK,cAAc;AAAA,YACtB;AAAA,UACF,CAAC;AAAA,QACH;AAAA,QACA,WAAW,OAAO,YAAY;AAC5B,eAAK,UAAU,KAAK,OAAO;AAE3B,eAAK,KAAK,WAAW;AAAA,YACnB;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAED,cAAQ;AAAA,QACN,+DAA+D,QAAQ,IAAI,IAAI,GAAG,QAAQ,IAAI,QAAQ;AAAA,MACxG;AAAA,IACF,OAAO;AACL,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAa,OAAO;AAClB,QAAI,KAAK,YAAY;AACnB,WAAK,WAAW,MAAM;AAAA,IACxB;AAAA,EACF;AACF;","names":["prompt","resource","tool"]}
|
package/jsr.json
CHANGED
package/package.json
CHANGED
package/src/FastMCP.test.ts
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
PingRequestSchema,
|
|
15
15
|
Root,
|
|
16
16
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
17
|
-
import { createEventSource, EventSourceClient } from
|
|
17
|
+
import { createEventSource, EventSourceClient } from "eventsource-client";
|
|
18
18
|
|
|
19
19
|
const runWithTestServer = async ({
|
|
20
20
|
run,
|
|
@@ -68,7 +68,6 @@ const runWithTestServer = async ({
|
|
|
68
68
|
|
|
69
69
|
const session = await new Promise<FastMCPSession>((resolve) => {
|
|
70
70
|
server.on("connect", (event) => {
|
|
71
|
-
|
|
72
71
|
resolve(event.session);
|
|
73
72
|
});
|
|
74
73
|
|
|
@@ -1310,7 +1309,9 @@ test("throws ErrorCode.InvalidParams if tool parameters do not match zod schema"
|
|
|
1310
1309
|
expect(error.code).toBe(ErrorCode.InvalidParams);
|
|
1311
1310
|
|
|
1312
1311
|
// @ts-expect-error - we know that error is an McpError
|
|
1313
|
-
expect(error.message).toBe(
|
|
1312
|
+
expect(error.message).toBe(
|
|
1313
|
+
"MCP error -32602: MCP error -32602: Invalid add parameters",
|
|
1314
|
+
);
|
|
1314
1315
|
}
|
|
1315
1316
|
},
|
|
1316
1317
|
});
|
|
@@ -1354,7 +1355,9 @@ test("server remains usable after InvalidParams error", async () => {
|
|
|
1354
1355
|
expect(error.code).toBe(ErrorCode.InvalidParams);
|
|
1355
1356
|
|
|
1356
1357
|
// @ts-expect-error - we know that error is an McpError
|
|
1357
|
-
expect(error.message).toBe(
|
|
1358
|
+
expect(error.message).toBe(
|
|
1359
|
+
"MCP error -32602: MCP error -32602: Invalid add parameters",
|
|
1360
|
+
);
|
|
1358
1361
|
}
|
|
1359
1362
|
|
|
1360
1363
|
expect(
|
|
@@ -1515,10 +1518,10 @@ test("closing event source does not produce error", async () => {
|
|
|
1515
1518
|
const eventSource = await new Promise<EventSourceClient>((onMessage) => {
|
|
1516
1519
|
const eventSource = createEventSource({
|
|
1517
1520
|
onConnect: () => {
|
|
1518
|
-
console.info(
|
|
1521
|
+
console.info("connected");
|
|
1519
1522
|
},
|
|
1520
1523
|
onDisconnect: () => {
|
|
1521
|
-
console.info(
|
|
1524
|
+
console.info("disconnected");
|
|
1522
1525
|
},
|
|
1523
1526
|
onMessage: () => {
|
|
1524
1527
|
onMessage(eventSource);
|
|
@@ -1527,7 +1530,7 @@ test("closing event source does not produce error", async () => {
|
|
|
1527
1530
|
});
|
|
1528
1531
|
});
|
|
1529
1532
|
|
|
1530
|
-
expect(eventSource.readyState).toBe(
|
|
1533
|
+
expect(eventSource.readyState).toBe("open");
|
|
1531
1534
|
|
|
1532
1535
|
eventSource.close();
|
|
1533
1536
|
|
|
@@ -1547,7 +1550,7 @@ test("provides auth to tools", async () => {
|
|
|
1547
1550
|
};
|
|
1548
1551
|
});
|
|
1549
1552
|
|
|
1550
|
-
const server = new FastMCP<{id: number}>({
|
|
1553
|
+
const server = new FastMCP<{ id: number }>({
|
|
1551
1554
|
name: "Test",
|
|
1552
1555
|
version: "1.0.0",
|
|
1553
1556
|
authenticate,
|
|
@@ -1604,7 +1607,10 @@ test("provides auth to tools", async () => {
|
|
|
1604
1607
|
|
|
1605
1608
|
await client.connect(transport);
|
|
1606
1609
|
|
|
1607
|
-
expect(
|
|
1610
|
+
expect(
|
|
1611
|
+
authenticate,
|
|
1612
|
+
"authenticate should have been called",
|
|
1613
|
+
).toHaveBeenCalledTimes(1);
|
|
1608
1614
|
|
|
1609
1615
|
expect(
|
|
1610
1616
|
await client.callTool({
|
|
@@ -1620,25 +1626,28 @@ test("provides auth to tools", async () => {
|
|
|
1620
1626
|
|
|
1621
1627
|
expect(execute, "execute should have been called").toHaveBeenCalledTimes(1);
|
|
1622
1628
|
|
|
1623
|
-
expect(execute).toHaveBeenCalledWith(
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1629
|
+
expect(execute).toHaveBeenCalledWith(
|
|
1630
|
+
{
|
|
1631
|
+
a: 1,
|
|
1632
|
+
b: 2,
|
|
1633
|
+
},
|
|
1634
|
+
{
|
|
1635
|
+
log: {
|
|
1636
|
+
debug: expect.any(Function),
|
|
1637
|
+
error: expect.any(Function),
|
|
1638
|
+
info: expect.any(Function),
|
|
1639
|
+
warn: expect.any(Function),
|
|
1640
|
+
},
|
|
1641
|
+
reportProgress: expect.any(Function),
|
|
1642
|
+
session: { id: 1 },
|
|
1643
|
+
},
|
|
1644
|
+
);
|
|
1636
1645
|
});
|
|
1637
1646
|
|
|
1638
1647
|
test("blocks unauthorized requests", async () => {
|
|
1639
1648
|
const port = await getRandomPort();
|
|
1640
1649
|
|
|
1641
|
-
const server = new FastMCP<{id: number}>({
|
|
1650
|
+
const server = new FastMCP<{ id: number }>({
|
|
1642
1651
|
name: "Test",
|
|
1643
1652
|
version: "1.0.0",
|
|
1644
1653
|
authenticate: async () => {
|
|
@@ -1674,4 +1683,4 @@ test("blocks unauthorized requests", async () => {
|
|
|
1674
1683
|
expect(async () => {
|
|
1675
1684
|
await client.connect(transport);
|
|
1676
1685
|
}).rejects.toThrow("SSE error: Non-200 status code (401)");
|
|
1677
|
-
});
|
|
1686
|
+
});
|
package/src/FastMCP.ts
CHANGED
|
@@ -32,9 +32,7 @@ import { startSSEServer } from "mcp-proxy";
|
|
|
32
32
|
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
33
33
|
import parseURITemplate from "uri-templates";
|
|
34
34
|
import http from "http";
|
|
35
|
-
import {
|
|
36
|
-
fetch
|
|
37
|
-
} from "undici";
|
|
35
|
+
import { fetch } from "undici";
|
|
38
36
|
|
|
39
37
|
export type SSEServer = {
|
|
40
38
|
close: () => Promise<void>;
|
|
@@ -87,7 +85,9 @@ export const imageContent = async (
|
|
|
87
85
|
} as const;
|
|
88
86
|
};
|
|
89
87
|
|
|
90
|
-
export const audioContent = async (
|
|
88
|
+
export const audioContent = async (
|
|
89
|
+
input: { url: string } | { path: string } | { buffer: Buffer },
|
|
90
|
+
): Promise<AudioContent> => {
|
|
91
91
|
let rawData: Buffer;
|
|
92
92
|
|
|
93
93
|
if ("url" in input) {
|
|
@@ -103,7 +103,9 @@ export const audioContent = async (input: { url: string } | { path: string } | {
|
|
|
103
103
|
} else if ("buffer" in input) {
|
|
104
104
|
rawData = input.buffer;
|
|
105
105
|
} else {
|
|
106
|
-
throw new Error(
|
|
106
|
+
throw new Error(
|
|
107
|
+
"Invalid input: Provide a valid 'url', 'path', or 'buffer'",
|
|
108
|
+
);
|
|
107
109
|
}
|
|
108
110
|
|
|
109
111
|
const mimeType = await fileTypeFromBuffer(rawData);
|
|
@@ -252,14 +254,57 @@ const CompletionZodSchema = z.object({
|
|
|
252
254
|
hasMore: z.optional(z.boolean()),
|
|
253
255
|
}) satisfies z.ZodType<Completion>;
|
|
254
256
|
|
|
255
|
-
|
|
257
|
+
/**
|
|
258
|
+
* Tool annotations as defined in MCP Specification (2025-03-26)
|
|
259
|
+
* These provide hints about a tool's behavior.
|
|
260
|
+
*/
|
|
261
|
+
type ToolAnnotations = {
|
|
262
|
+
/**
|
|
263
|
+
* A human-readable title for the tool, useful for UI display
|
|
264
|
+
*/
|
|
265
|
+
title?: string;
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* If true, indicates the tool does not modify its environment
|
|
269
|
+
* @default false
|
|
270
|
+
*/
|
|
271
|
+
readOnlyHint?: boolean;
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* If true, the tool may perform destructive updates
|
|
275
|
+
* Only meaningful when readOnlyHint is false
|
|
276
|
+
* @default true
|
|
277
|
+
*/
|
|
278
|
+
destructiveHint?: boolean;
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* If true, calling the tool repeatedly with the same arguments has no additional effect
|
|
282
|
+
* Only meaningful when readOnlyHint is false
|
|
283
|
+
* @default false
|
|
284
|
+
*/
|
|
285
|
+
idempotentHint?: boolean;
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* If true, the tool may interact with an "open world" of external entities
|
|
289
|
+
* @default true
|
|
290
|
+
*/
|
|
291
|
+
openWorldHint?: boolean;
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
type Tool<
|
|
295
|
+
T extends FastMCPSessionAuth,
|
|
296
|
+
Params extends ToolParameters = ToolParameters,
|
|
297
|
+
> = {
|
|
256
298
|
name: string;
|
|
257
299
|
description?: string;
|
|
258
300
|
parameters?: Params;
|
|
301
|
+
annotations?: ToolAnnotations;
|
|
259
302
|
execute: (
|
|
260
303
|
args: StandardSchemaV1.InferOutput<Params>,
|
|
261
304
|
context: Context<T>,
|
|
262
|
-
) => Promise<
|
|
305
|
+
) => Promise<
|
|
306
|
+
string | ContentResult | TextContent | ImageContent | AudioContent
|
|
307
|
+
>;
|
|
263
308
|
};
|
|
264
309
|
|
|
265
310
|
type ResourceResult =
|
|
@@ -375,6 +420,7 @@ type ServerOptions<T extends FastMCPSessionAuth> = {
|
|
|
375
420
|
name: string;
|
|
376
421
|
version: `${number}.${number}.${number}`;
|
|
377
422
|
authenticate?: Authenticate<T>;
|
|
423
|
+
instructions?: string;
|
|
378
424
|
};
|
|
379
425
|
|
|
380
426
|
type LoggingLevel =
|
|
@@ -402,7 +448,9 @@ type SamplingResponse = {
|
|
|
402
448
|
|
|
403
449
|
type FastMCPSessionAuth = Record<string, unknown> | undefined;
|
|
404
450
|
|
|
405
|
-
export class FastMCPSession<
|
|
451
|
+
export class FastMCPSession<
|
|
452
|
+
T extends FastMCPSessionAuth = FastMCPSessionAuth,
|
|
453
|
+
> extends FastMCPSessionEventEmitter {
|
|
406
454
|
#capabilities: ServerCapabilities = {};
|
|
407
455
|
#clientCapabilities?: ClientCapabilities;
|
|
408
456
|
#loggingLevel: LoggingLevel = "info";
|
|
@@ -417,6 +465,7 @@ export class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> e
|
|
|
417
465
|
auth,
|
|
418
466
|
name,
|
|
419
467
|
version,
|
|
468
|
+
instructions,
|
|
420
469
|
tools,
|
|
421
470
|
resources,
|
|
422
471
|
resourcesTemplates,
|
|
@@ -425,6 +474,7 @@ export class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> e
|
|
|
425
474
|
auth?: T;
|
|
426
475
|
name: string;
|
|
427
476
|
version: string;
|
|
477
|
+
instructions?: string;
|
|
428
478
|
tools: Tool<T>[];
|
|
429
479
|
resources: Resource[];
|
|
430
480
|
resourcesTemplates: InputResourceTemplate[];
|
|
@@ -454,7 +504,7 @@ export class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> e
|
|
|
454
504
|
|
|
455
505
|
this.#server = new Server(
|
|
456
506
|
{ name: name, version: version },
|
|
457
|
-
{ capabilities: this.#capabilities },
|
|
507
|
+
{ capabilities: this.#capabilities, instructions: instructions },
|
|
458
508
|
);
|
|
459
509
|
|
|
460
510
|
this.setupErrorHandling();
|
|
@@ -597,15 +647,17 @@ export class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> e
|
|
|
597
647
|
}
|
|
598
648
|
|
|
599
649
|
if (!this.#clientCapabilities) {
|
|
600
|
-
console.warn(
|
|
650
|
+
console.warn("[FastMCP warning] could not infer client capabilities");
|
|
601
651
|
}
|
|
602
652
|
|
|
603
653
|
if (this.#clientCapabilities?.roots?.listChanged) {
|
|
604
654
|
try {
|
|
605
655
|
const roots = await this.#server.listRoots();
|
|
606
656
|
this.#roots = roots.roots;
|
|
607
|
-
} catch(e) {
|
|
608
|
-
console.error(
|
|
657
|
+
} catch (e) {
|
|
658
|
+
console.error(
|
|
659
|
+
`[FastMCP error] received error listing roots.\n\n${e instanceof Error ? e.stack : JSON.stringify(e)}`,
|
|
660
|
+
);
|
|
609
661
|
}
|
|
610
662
|
}
|
|
611
663
|
|
|
@@ -616,8 +668,8 @@ export class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> e
|
|
|
616
668
|
} catch {
|
|
617
669
|
// The reason we are not emitting an error here is because some clients
|
|
618
670
|
// seem to not respond to the ping request, and we don't want to crash the server,
|
|
619
|
-
// e.g., https://github.com/punkpeye/fastmcp/issues/38.
|
|
620
|
-
console.warn("[FastMCP warning] server is not responding to ping")
|
|
671
|
+
// e.g., https://github.com/punkpeye/fastmcp/issues/38.
|
|
672
|
+
console.warn("[FastMCP warning] server is not responding to ping");
|
|
621
673
|
}
|
|
622
674
|
}, 1000);
|
|
623
675
|
}
|
|
@@ -748,15 +800,18 @@ export class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> e
|
|
|
748
800
|
private setupToolHandlers(tools: Tool<T>[]) {
|
|
749
801
|
this.#server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
750
802
|
return {
|
|
751
|
-
tools: await Promise.all(
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
803
|
+
tools: await Promise.all(
|
|
804
|
+
tools.map(async (tool) => {
|
|
805
|
+
return {
|
|
806
|
+
name: tool.name,
|
|
807
|
+
description: tool.description,
|
|
808
|
+
inputSchema: tool.parameters
|
|
809
|
+
? await toJsonSchema(tool.parameters)
|
|
810
|
+
: undefined,
|
|
811
|
+
annotations: tool.annotations,
|
|
812
|
+
};
|
|
813
|
+
}),
|
|
814
|
+
),
|
|
760
815
|
};
|
|
761
816
|
});
|
|
762
817
|
|
|
@@ -774,7 +829,7 @@ export class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> e
|
|
|
774
829
|
|
|
775
830
|
if (tool.parameters) {
|
|
776
831
|
const parsed = await tool.parameters["~standard"].validate(
|
|
777
|
-
request.params.arguments
|
|
832
|
+
request.params.arguments,
|
|
778
833
|
);
|
|
779
834
|
|
|
780
835
|
if (parsed.issues) {
|
|
@@ -1065,7 +1120,9 @@ class FastMCPEventEmitter extends FastMCPEventEmitterBase {}
|
|
|
1065
1120
|
|
|
1066
1121
|
type Authenticate<T> = (request: http.IncomingMessage) => Promise<T>;
|
|
1067
1122
|
|
|
1068
|
-
export class FastMCP<
|
|
1123
|
+
export class FastMCP<
|
|
1124
|
+
T extends Record<string, unknown> | undefined = undefined,
|
|
1125
|
+
> extends FastMCPEventEmitter {
|
|
1069
1126
|
#options: ServerOptions<T>;
|
|
1070
1127
|
#prompts: InputPrompt[] = [];
|
|
1071
1128
|
#resources: Resource[] = [];
|
|
@@ -1137,6 +1194,7 @@ export class FastMCP<T extends Record<string, unknown> | undefined = undefined>
|
|
|
1137
1194
|
const session = new FastMCPSession<T>({
|
|
1138
1195
|
name: this.#options.name,
|
|
1139
1196
|
version: this.#options.version,
|
|
1197
|
+
instructions: this.#options.instructions,
|
|
1140
1198
|
tools: this.#tools,
|
|
1141
1199
|
resources: this.#resources,
|
|
1142
1200
|
resourcesTemplates: this.#resourcesTemplates,
|
|
@@ -1150,7 +1208,6 @@ export class FastMCP<T extends Record<string, unknown> | undefined = undefined>
|
|
|
1150
1208
|
this.emit("connect", {
|
|
1151
1209
|
session,
|
|
1152
1210
|
});
|
|
1153
|
-
|
|
1154
1211
|
} else if (options.transportType === "sse") {
|
|
1155
1212
|
this.#sseServer = await startSSEServer<FastMCPSession<T>>({
|
|
1156
1213
|
endpoint: options.sse.endpoint as `/${string}`,
|
package/src/examples/addition.ts
CHANGED
|
@@ -21,6 +21,11 @@ server.addTool({
|
|
|
21
21
|
name: "add-zod",
|
|
22
22
|
description: "Add two numbers (using Zod schema)",
|
|
23
23
|
parameters: AddParamsZod,
|
|
24
|
+
annotations: {
|
|
25
|
+
title: "Addition (Zod)",
|
|
26
|
+
readOnlyHint: true, // This tool doesn't modify anything
|
|
27
|
+
openWorldHint: false, // This tool doesn't interact with external systems
|
|
28
|
+
},
|
|
24
29
|
execute: async (args) => {
|
|
25
30
|
// args is typed as { a: number, b: number }
|
|
26
31
|
console.log(`[Zod] Adding ${args.a} and ${args.b}`);
|
|
@@ -38,6 +43,13 @@ server.addTool({
|
|
|
38
43
|
name: "add-arktype",
|
|
39
44
|
description: "Add two numbers (using ArkType schema)",
|
|
40
45
|
parameters: AddParamsArkType,
|
|
46
|
+
annotations: {
|
|
47
|
+
title: "Addition (ArkType)",
|
|
48
|
+
readOnlyHint: false, // Example showing a modifying tool
|
|
49
|
+
destructiveHint: true, // This would perform destructive operations
|
|
50
|
+
idempotentHint: true, // But operations can be repeated safely
|
|
51
|
+
openWorldHint: true, // Interacts with external systems
|
|
52
|
+
},
|
|
41
53
|
execute: async (args) => {
|
|
42
54
|
// args is typed as { a: number, b: number } based on AddParamsArkType.infer
|
|
43
55
|
console.log(`[ArkType] Adding ${args.a} and ${args.b}`);
|
|
@@ -55,6 +67,11 @@ server.addTool({
|
|
|
55
67
|
name: "add-valibot",
|
|
56
68
|
description: "Add two numbers (using Valibot schema)",
|
|
57
69
|
parameters: AddParamsValibot,
|
|
70
|
+
annotations: {
|
|
71
|
+
title: "Addition (Valibot)",
|
|
72
|
+
readOnlyHint: true,
|
|
73
|
+
openWorldHint: false,
|
|
74
|
+
},
|
|
58
75
|
execute: async (args) => {
|
|
59
76
|
console.log(`[Valibot] Adding ${args.a} and ${args.b}`);
|
|
60
77
|
return String(args.a + args.b);
|