fastmcp 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ name: Run Tests
2
+ on:
3
+ pull_request:
4
+ branches:
5
+ - main
6
+ types:
7
+ - opened
8
+ - synchronize
9
+ - reopened
10
+ - ready_for_review
11
+ jobs:
12
+ test:
13
+ runs-on: ubuntu-latest
14
+ name: Test
15
+ strategy:
16
+ fail-fast: true
17
+ matrix:
18
+ node:
19
+ - 22
20
+ steps:
21
+ - name: Checkout repository
22
+ uses: actions/checkout@v4
23
+ with:
24
+ fetch-depth: 0
25
+ - uses: pnpm/action-setup@v4
26
+ with:
27
+ version: 9
28
+ - name: Setup NodeJS ${{ matrix.node }}
29
+ uses: actions/setup-node@v4
30
+ with:
31
+ node-version: ${{ matrix.node }}
32
+ cache: "pnpm"
33
+ cache-dependency-path: "**/pnpm-lock.yaml"
34
+ - name: Install dependencies
35
+ run: pnpm install
36
+ - name: Run tests
37
+ run: pnpm test
@@ -0,0 +1,45 @@
1
+ name: Release
2
+ on:
3
+ push:
4
+ branches:
5
+ - main
6
+ jobs:
7
+ test:
8
+ environment: release
9
+ name: Test
10
+ strategy:
11
+ fail-fast: true
12
+ matrix:
13
+ node:
14
+ - 22
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - name: setup repository
18
+ uses: actions/checkout@v4
19
+ with:
20
+ fetch-depth: 0
21
+ - uses: pnpm/action-setup@v4
22
+ with:
23
+ version: 9
24
+ - name: setup node.js
25
+ uses: actions/setup-node@v4
26
+ with:
27
+ cache: "pnpm"
28
+ node-version: ${{ matrix.node }}
29
+ - name: Setup NodeJS ${{ matrix.node }}
30
+ uses: actions/setup-node@v4
31
+ with:
32
+ node-version: ${{ matrix.node }}
33
+ cache: "pnpm"
34
+ cache-dependency-path: "**/pnpm-lock.yaml"
35
+ - name: Install dependencies
36
+ run: pnpm install
37
+ - name: Run tests
38
+ run: pnpm test
39
+ - name: Build
40
+ run: pnpm build
41
+ - name: Release
42
+ run: pnpm semantic-release
43
+ env:
44
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
45
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ The MIT License (MIT)
2
+ =====================
3
+
4
+ Copyright © 2024 Frank Fiegel (frank@glama.ai)
5
+
6
+ Permission is hereby granted, free of charge, to any person
7
+ obtaining a copy of this software and associated documentation
8
+ files (the “Software”), to deal in the Software without
9
+ restriction, including without limitation the rights to use,
10
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the
12
+ Software is furnished to do so, subject to the following
13
+ conditions:
14
+
15
+ The above copyright notice and this permission notice shall be
16
+ included in all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
19
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25
+ OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,197 @@
1
+ # FastMCP
2
+
3
+ A TypeScript framework for building [MCP](https://modelcontextprotocol.io/) servers.
4
+
5
+ > [!NOTE]
6
+ > For a Python implementation, see [FastMCP](https://github.com/jlowin/fastmcp).
7
+
8
+ ## Features
9
+
10
+ - Simple Tool, Resource, Prompt definition
11
+ - Full TypeScript support
12
+ - Built-in error handling
13
+ - Built-in CLI for testing and debugging
14
+ - Built-in support for SSE
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install fastmcp
20
+ ```
21
+
22
+ ## Quickstart
23
+
24
+ ```ts
25
+ import { FastMCP } from "fastmcp";
26
+ import { z } from "zod";
27
+
28
+ const server = new FastMCP({
29
+ name: "My Server",
30
+ version: "1.0.0",
31
+ });
32
+
33
+ server.addTool({
34
+ name: "add",
35
+ description: "Add two numbers",
36
+ parameters: z.object({
37
+ a: z.number(),
38
+ b: z.number(),
39
+ }),
40
+ execute: async (args) => {
41
+ return args.a + args.b;
42
+ },
43
+ });
44
+
45
+ server.start({
46
+ transportType: "stdio",
47
+ });
48
+ ```
49
+
50
+ You can test the server in terminal with:
51
+
52
+ ```bash
53
+ npx fastmcp dev server.js
54
+ ```
55
+
56
+ ### SSE
57
+
58
+ You can also run the server with SSE support:
59
+
60
+ ```ts
61
+ server.start({
62
+ transportType: "sse",
63
+ sse: {
64
+ endpoint: "/sse",
65
+ port: 8080,
66
+ },
67
+ });
68
+ ```
69
+
70
+ This will start the server and listen for SSE connections on `http://localhost:8080/sse`.
71
+
72
+ You can then use `SSEClientTransport` to connect to the server:
73
+
74
+ ```ts
75
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
76
+
77
+ const client = new Client(
78
+ {
79
+ name: "example-client",
80
+ version: "1.0.0",
81
+ },
82
+ {
83
+ capabilities: {},
84
+ },
85
+ );
86
+
87
+ const transport = new SSEClientTransport(new URL(`http://localhost:8080/sse`));
88
+
89
+ await client.connect(transport);
90
+ ```
91
+
92
+ ## Core Concepts
93
+
94
+ ### Tools
95
+
96
+ [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.
97
+
98
+ ```js
99
+ server.addTool({
100
+ name: "fetch",
101
+ description: "Fetch the content of a url",
102
+ parameters: z.object({
103
+ url: z.string(),
104
+ }),
105
+ execute: async (args) => {
106
+ const content = await fetchWebpageContent(args.url);
107
+ return content;
108
+ },
109
+ });
110
+ ```
111
+
112
+ ### Resources
113
+
114
+ [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:
115
+
116
+ - File contents
117
+ - Screenshots and images
118
+ - Log files
119
+ - And more
120
+
121
+ Each resource is identified by a unique URI and can contain either text or binary data.
122
+
123
+ ```js
124
+ server.addResource({
125
+ uri: "file:///logs/app.log",
126
+ name: "Application Logs",
127
+ mimeType: "text/plain",
128
+ async load() {
129
+ return {
130
+ text: await readLogFile(),
131
+ };
132
+ },
133
+ });
134
+ ```
135
+
136
+ You can also return binary contents in `load`:
137
+
138
+ ```js
139
+ async load() {
140
+ return {
141
+ blob: 'base64-encoded-data'
142
+ }
143
+ }
144
+ ```
145
+
146
+ ### Prompts
147
+
148
+ [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.
149
+
150
+ ```js
151
+ server.addPrompt({
152
+ name: "git-commit",
153
+ description: "Generate a Git commit message",
154
+ arguments: [
155
+ {
156
+ name: "changes",
157
+ description: "Git diff or description of changes",
158
+ required: true,
159
+ },
160
+ ],
161
+ load: async (args) => {
162
+ return `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}`;
163
+ },
164
+ });
165
+ ```
166
+
167
+ ## Running Your Server
168
+
169
+ ### Test with `mcp-cli`
170
+
171
+ The fastest way to test and debug your server is with `fastmcp dev`:
172
+
173
+ ```bash
174
+ npx fastmcp dev server.js
175
+ npx fastmcp dev server.ts
176
+ ```
177
+
178
+ This will run your server with [`mcp-cli`](https://github.com/wong2/mcp-cli) for testing and debugging your MCP server in the terminal.
179
+
180
+ ### Inspect with `MCP Inspector`
181
+
182
+ Another way is to use the official [`MCP Inspector`](https://modelcontextprotocol.io/docs/tools/inspector) to inspect your server with a Web UI:
183
+
184
+ ```bash
185
+ npx fastmcp inspect server.ts
186
+ ```
187
+
188
+ ## Showcase
189
+
190
+ > [!NOTE]
191
+ > If you've developed a server using FastMCP, please [submit a PR](https://github.com/punkpeye/fastmcp) to showcase it here!
192
+
193
+ ## Acknowledgements
194
+
195
+ - FastMCP is inspired by the [Python implementation](https://github.com/jlowin/fastmcp) by [Jonathan Lowin](https://github.com/jlowin).
196
+ - Parts of codebase were adopted from [LiteMCP](https://github.com/wong2/litemcp).
197
+ - Parts of codebase were adopted from [Model Context protocolでSSEをやってみる](https://dev.classmethod.jp/articles/mcp-sse/).
@@ -0,0 +1,69 @@
1
+ import { z } from 'zod';
2
+
3
+ type ToolParameters = z.ZodTypeAny;
4
+ type Tool<Params extends ToolParameters = ToolParameters> = {
5
+ name: string;
6
+ description?: string;
7
+ parameters?: Params;
8
+ execute: (args: z.infer<Params>) => Promise<unknown>;
9
+ };
10
+ type Resource = {
11
+ uri: string;
12
+ name: string;
13
+ description?: string;
14
+ mimeType?: string;
15
+ load: () => Promise<{
16
+ text: string;
17
+ } | {
18
+ blob: string;
19
+ }>;
20
+ };
21
+ type PromptArgument = Readonly<{
22
+ name: string;
23
+ description?: string;
24
+ required?: boolean;
25
+ }>;
26
+ type ArgumentsToObject<T extends PromptArgument[]> = {
27
+ [K in T[number]["name"]]: Extract<T[number], {
28
+ name: K;
29
+ }>["required"] extends true ? string : string | undefined;
30
+ };
31
+ type Prompt<Arguments extends PromptArgument[] = PromptArgument[], Args = ArgumentsToObject<Arguments>> = {
32
+ name: string;
33
+ description?: string;
34
+ arguments?: Arguments;
35
+ load: (args: Args) => Promise<string>;
36
+ };
37
+ type ServerOptions = {
38
+ name: string;
39
+ version: `${number}.${number}.${number}`;
40
+ };
41
+ declare class FastMCP {
42
+ #private;
43
+ options: ServerOptions;
44
+ constructor(options: ServerOptions);
45
+ private setupHandlers;
46
+ private setupErrorHandling;
47
+ private setupToolHandlers;
48
+ private setupResourceHandlers;
49
+ private setupPromptHandlers;
50
+ addTool<Params extends ToolParameters>(tool: Tool<Params>): void;
51
+ addResource(resource: Resource): void;
52
+ addPrompt<const Args extends PromptArgument[]>(prompt: Prompt<Args>): void;
53
+ start(options?: {
54
+ transportType: "stdio";
55
+ } | {
56
+ transportType: "sse";
57
+ sse: {
58
+ endpoint: `/${string}`;
59
+ port: number;
60
+ };
61
+ }): Promise<void>;
62
+ /**
63
+ * @see https://dev.classmethod.jp/articles/mcp-sse/
64
+ */
65
+ private startSending;
66
+ stop(): Promise<void>;
67
+ }
68
+
69
+ export { FastMCP };
@@ -0,0 +1,318 @@
1
+ // src/FastMCP.ts
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
5
+ import {
6
+ CallToolRequestSchema,
7
+ ErrorCode,
8
+ GetPromptRequestSchema,
9
+ ListPromptsRequestSchema,
10
+ ListResourcesRequestSchema,
11
+ ListToolsRequestSchema,
12
+ McpError,
13
+ ReadResourceRequestSchema
14
+ } from "@modelcontextprotocol/sdk/types.js";
15
+ import { zodToJsonSchema } from "zod-to-json-schema";
16
+ import http from "http";
17
+ var FastMCP = class {
18
+ constructor(options) {
19
+ this.options = options;
20
+ this.#options = options;
21
+ this.#tools = [];
22
+ this.#resources = [];
23
+ this.#prompts = [];
24
+ }
25
+ #tools;
26
+ #resources;
27
+ #prompts;
28
+ #server = null;
29
+ #options;
30
+ setupHandlers(server) {
31
+ this.setupErrorHandling(server);
32
+ if (this.#tools.length) {
33
+ this.setupToolHandlers(server);
34
+ }
35
+ if (this.#resources.length) {
36
+ this.setupResourceHandlers(server);
37
+ }
38
+ if (this.#prompts.length) {
39
+ this.setupPromptHandlers(server);
40
+ }
41
+ }
42
+ setupErrorHandling(server) {
43
+ server.onerror = (error) => {
44
+ console.error("[MCP Error]", error);
45
+ };
46
+ process.on("SIGINT", async () => {
47
+ await server.close();
48
+ process.exit(0);
49
+ });
50
+ }
51
+ setupToolHandlers(server) {
52
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
53
+ return {
54
+ tools: this.#tools.map((tool) => {
55
+ return {
56
+ name: tool.name,
57
+ description: tool.description,
58
+ inputSchema: tool.parameters ? zodToJsonSchema(tool.parameters) : void 0
59
+ };
60
+ })
61
+ };
62
+ });
63
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
64
+ const tool = this.#tools.find(
65
+ (tool2) => tool2.name === request.params.name
66
+ );
67
+ if (!tool) {
68
+ throw new McpError(
69
+ ErrorCode.MethodNotFound,
70
+ `Unknown tool: ${request.params.name}`
71
+ );
72
+ }
73
+ let args = void 0;
74
+ if (tool.parameters) {
75
+ const parsed = tool.parameters.safeParse(request.params.arguments);
76
+ if (!parsed.success) {
77
+ throw new McpError(
78
+ ErrorCode.InvalidRequest,
79
+ `Invalid ${request.params.name} arguments`
80
+ );
81
+ }
82
+ args = parsed.data;
83
+ }
84
+ let result;
85
+ try {
86
+ result = await tool.execute(args);
87
+ } catch (error) {
88
+ return {
89
+ content: [{ type: "text", text: `Error: ${error}` }],
90
+ isError: true
91
+ };
92
+ }
93
+ if (typeof result === "string") {
94
+ return {
95
+ content: [{ type: "text", text: result }]
96
+ };
97
+ }
98
+ return {
99
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
100
+ };
101
+ });
102
+ }
103
+ setupResourceHandlers(server) {
104
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
105
+ return {
106
+ resources: this.#resources.map((resource) => {
107
+ return {
108
+ uri: resource.uri,
109
+ name: resource.name,
110
+ mimeType: resource.mimeType
111
+ };
112
+ })
113
+ };
114
+ });
115
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
116
+ const resource = this.#resources.find(
117
+ (resource2) => resource2.uri === request.params.uri
118
+ );
119
+ if (!resource) {
120
+ throw new McpError(
121
+ ErrorCode.MethodNotFound,
122
+ `Unknown resource: ${request.params.uri}`
123
+ );
124
+ }
125
+ let result;
126
+ try {
127
+ result = await resource.load();
128
+ } catch (error) {
129
+ throw new McpError(
130
+ ErrorCode.InternalError,
131
+ `Error reading resource: ${error}`,
132
+ {
133
+ uri: resource.uri
134
+ }
135
+ );
136
+ }
137
+ return {
138
+ contents: [
139
+ {
140
+ uri: resource.uri,
141
+ mimeType: resource.mimeType,
142
+ ...result
143
+ }
144
+ ]
145
+ };
146
+ });
147
+ }
148
+ setupPromptHandlers(server) {
149
+ server.setRequestHandler(ListPromptsRequestSchema, async () => {
150
+ return {
151
+ prompts: this.#prompts.map((prompt) => {
152
+ return {
153
+ name: prompt.name,
154
+ description: prompt.description,
155
+ arguments: prompt.arguments
156
+ };
157
+ })
158
+ };
159
+ });
160
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
161
+ const prompt = this.#prompts.find(
162
+ (prompt2) => prompt2.name === request.params.name
163
+ );
164
+ if (!prompt) {
165
+ throw new McpError(
166
+ ErrorCode.MethodNotFound,
167
+ `Unknown prompt: ${request.params.name}`
168
+ );
169
+ }
170
+ const args = request.params.arguments;
171
+ if (prompt.arguments) {
172
+ for (const arg of prompt.arguments) {
173
+ if (arg.required && !(args && arg.name in args)) {
174
+ throw new McpError(
175
+ ErrorCode.InvalidRequest,
176
+ `Missing required argument: ${arg.name}`
177
+ );
178
+ }
179
+ }
180
+ }
181
+ let result;
182
+ try {
183
+ result = await prompt.load(args);
184
+ } catch (error) {
185
+ throw new McpError(
186
+ ErrorCode.InternalError,
187
+ `Error loading prompt: ${error}`
188
+ );
189
+ }
190
+ return {
191
+ description: prompt.description,
192
+ messages: [
193
+ {
194
+ role: "user",
195
+ content: { type: "text", text: result }
196
+ }
197
+ ]
198
+ };
199
+ });
200
+ }
201
+ addTool(tool) {
202
+ this.#tools.push(tool);
203
+ }
204
+ addResource(resource) {
205
+ this.#resources.push(resource);
206
+ }
207
+ addPrompt(prompt) {
208
+ this.#prompts.push(prompt);
209
+ }
210
+ #httpServer = null;
211
+ async start(options = {
212
+ transportType: "stdio"
213
+ }) {
214
+ const capabilities = {};
215
+ if (this.#tools.length) {
216
+ capabilities.tools = {};
217
+ }
218
+ if (this.#resources.length) {
219
+ capabilities.resources = {};
220
+ }
221
+ if (this.#prompts.length) {
222
+ capabilities.prompts = {};
223
+ }
224
+ this.#server = new Server(
225
+ { name: this.#options.name, version: this.#options.version },
226
+ { capabilities }
227
+ );
228
+ this.setupHandlers(this.#server);
229
+ if (options.transportType === "stdio") {
230
+ const transport = new StdioServerTransport();
231
+ await this.#server.connect(transport);
232
+ console.error(`server is running on stdio`);
233
+ } else if (options.transportType === "sse") {
234
+ let activeTransport = null;
235
+ this.#httpServer = http.createServer(async (req, res) => {
236
+ if (req.method === "GET" && req.url === options.sse.endpoint) {
237
+ const transport = new SSEServerTransport("/messages", res);
238
+ activeTransport = transport;
239
+ if (!this.#server) {
240
+ throw new Error("Server not initialized");
241
+ }
242
+ await this.#server.connect(transport);
243
+ res.on("close", () => {
244
+ console.log("SSE connection closed");
245
+ if (activeTransport === transport) {
246
+ activeTransport = null;
247
+ }
248
+ });
249
+ this.startSending(transport);
250
+ return;
251
+ }
252
+ if (req.method === "POST" && req.url?.startsWith("/messages")) {
253
+ if (!activeTransport) {
254
+ res.writeHead(400).end("No active transport");
255
+ return;
256
+ }
257
+ await activeTransport.handlePostMessage(req, res);
258
+ return;
259
+ }
260
+ res.writeHead(404).end();
261
+ });
262
+ this.#httpServer.listen(options.sse.port, "0.0.0.0");
263
+ console.error(
264
+ `server is running on SSE at http://localhost:${options.sse.port}${options.sse.endpoint}`
265
+ );
266
+ } else {
267
+ throw new Error("Invalid transport type");
268
+ }
269
+ }
270
+ /**
271
+ * @see https://dev.classmethod.jp/articles/mcp-sse/
272
+ */
273
+ async startSending(transport) {
274
+ try {
275
+ await transport.send({
276
+ jsonrpc: "2.0",
277
+ method: "sse/connection",
278
+ params: { message: "SSE Connection established" }
279
+ });
280
+ let messageCount = 0;
281
+ const interval = setInterval(async () => {
282
+ messageCount++;
283
+ const message = `Message ${messageCount} at ${(/* @__PURE__ */ new Date()).toISOString()}`;
284
+ try {
285
+ await transport.send({
286
+ jsonrpc: "2.0",
287
+ method: "sse/message",
288
+ params: { data: message }
289
+ });
290
+ console.log(`Sent: ${message}`);
291
+ if (messageCount === 10) {
292
+ clearInterval(interval);
293
+ await transport.send({
294
+ jsonrpc: "2.0",
295
+ method: "sse/complete",
296
+ params: { message: "Stream completed" }
297
+ });
298
+ console.log("Stream completed");
299
+ }
300
+ } catch (error) {
301
+ console.error("Error sending message:", error);
302
+ clearInterval(interval);
303
+ }
304
+ }, 1e3);
305
+ } catch (error) {
306
+ console.error("Error in startSending:", error);
307
+ }
308
+ }
309
+ async stop() {
310
+ if (this.#httpServer) {
311
+ this.#httpServer.close();
312
+ }
313
+ }
314
+ };
315
+ export {
316
+ FastMCP
317
+ };
318
+ //# sourceMappingURL=FastMCP.js.map