fastmcp 2.2.6__py3-none-any.whl → 2.2.8__py3-none-any.whl

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.
@@ -1,810 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: fastmcp
3
- Version: 2.2.6
4
- Summary: The fast, Pythonic way to build MCP servers.
5
- Project-URL: Homepage, https://gofastmcp.com
6
- Project-URL: Repository, https://github.com/jlowin/fastmcp
7
- Project-URL: Documentation, https://gofastmcp.com
8
- Author: Jeremiah Lowin
9
- License-Expression: Apache-2.0
10
- License-File: LICENSE
11
- Keywords: agent,fastmcp,llm,mcp,mcp client,mcp server,model context protocol
12
- Classifier: Intended Audience :: Developers
13
- Classifier: License :: OSI Approved :: Apache Software License
14
- Classifier: Programming Language :: Python :: 3.10
15
- Classifier: Programming Language :: Python :: 3.11
16
- Classifier: Programming Language :: Python :: 3.12
17
- Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
- Classifier: Typing :: Typed
19
- Requires-Python: >=3.10
20
- Requires-Dist: exceptiongroup>=1.2.2
21
- Requires-Dist: httpx>=0.28.1
22
- Requires-Dist: mcp<2.0.0,>=1.6.0
23
- Requires-Dist: openapi-pydantic>=0.5.1
24
- Requires-Dist: python-dotenv>=1.1.0
25
- Requires-Dist: rich>=13.9.4
26
- Requires-Dist: typer>=0.15.2
27
- Requires-Dist: websockets>=14.0
28
- Description-Content-Type: text/markdown
29
-
30
- <div align="center">
31
-
32
- <!-- omit in toc -->
33
- # FastMCP v2 🚀
34
- <strong>The fast, Pythonic way to build MCP servers and clients.</strong>
35
-
36
- [![Docs](https://img.shields.io/badge/docs-gofastmcp.com-blue)](https://gofastmcp.com)
37
- [![PyPI - Version](https://img.shields.io/pypi/v/fastmcp.svg)](https://pypi.org/project/fastmcp)
38
- [![Tests](https://github.com/jlowin/fastmcp/actions/workflows/run-tests.yml/badge.svg)](https://github.com/jlowin/fastmcp/actions/workflows/run-tests.yml)
39
- [![License](https://img.shields.io/github/license/jlowin/fastmcp.svg)](https://github.com/jlowin/fastmcp/blob/main/LICENSE)
40
-
41
- <a href="https://trendshift.io/repositories/13266" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13266" alt="jlowin%2Ffastmcp | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
42
- </div>
43
-
44
- The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) is a new, standardized way to provide context and tools to your LLMs, and FastMCP makes building MCP servers and clients simple and intuitive. Create tools, expose resources, define prompts, and connect components with clean, Pythonic code.
45
-
46
- ```python
47
- # server.py
48
- from fastmcp import FastMCP
49
-
50
- mcp = FastMCP("Demo 🚀")
51
-
52
- @mcp.tool()
53
- def add(a: int, b: int) -> int:
54
- """Add two numbers"""
55
- return a + b
56
-
57
- if __name__ == "__main__":
58
- mcp.run()
59
- ```
60
-
61
-
62
- Run the server locally:
63
- ```bash
64
- fastmcp run server.py
65
- ```
66
-
67
- FastMCP handles the complex protocol details and server management, letting you focus on building great tools and applications. It's designed to feel natural to Python developers.
68
-
69
-
70
- <!-- omit in toc -->
71
- ## Table of Contents
72
-
73
- - [What is MCP?](#what-is-mcp)
74
- - [Why FastMCP?](#why-fastmcp)
75
- - [Key Features](#key-features)
76
- - [Servers](#servers)
77
- - [Clients](#clients)
78
- - [What's New in v2?](#whats-new-in-v2)
79
- - [Documentation](#documentation)
80
- - [Installation](#installation)
81
- - [Quickstart](#quickstart)
82
- - [Core Concepts](#core-concepts)
83
- - [The `FastMCP` Server](#the-fastmcp-server)
84
- - [Tools](#tools)
85
- - [Resources](#resources)
86
- - [Prompts](#prompts)
87
- - [Context](#context)
88
- - [Images](#images)
89
- - [MCP Clients](#mcp-clients)
90
- - [Client Methods](#client-methods)
91
- - [Transport Options](#transport-options)
92
- - [LLM Sampling](#llm-sampling)
93
- - [Roots Access](#roots-access)
94
- - [Advanced Features](#advanced-features)
95
- - [Proxy Servers](#proxy-servers)
96
- - [Composing MCP Servers](#composing-mcp-servers)
97
- - [OpenAPI \& FastAPI Generation](#openapi--fastapi-generation)
98
- - [Handling `stderr`](#handling-stderr)
99
- - [Running Your Server](#running-your-server)
100
- - [Development Mode (Recommended for Building \& Testing)](#development-mode-recommended-for-building--testing)
101
- - [Claude Desktop Integration (For Regular Use)](#claude-desktop-integration-for-regular-use)
102
- - [Direct Execution (For Advanced Use Cases)](#direct-execution-for-advanced-use-cases)
103
- - [Server Object Names](#server-object-names)
104
- - [Examples](#examples)
105
- - [Contributing](#contributing)
106
- - [Prerequisites](#prerequisites)
107
- - [Setup](#setup)
108
- - [Testing](#testing)
109
- - [Formatting \& Linting](#formatting--linting)
110
- - [Pull Requests](#pull-requests)
111
-
112
-
113
- ## What is MCP?
114
-
115
- The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. MCP servers can:
116
-
117
- - Expose data through **Resources** (think GET endpoints; load info into context)
118
- - Provide functionality through **Tools** (think POST/PUT endpoints; execute actions)
119
- - Define interaction patterns through **Prompts** (reusable templates)
120
- - And more!
121
-
122
- FastMCP provides a high-level, Pythonic interface for building and interacting with these servers.
123
-
124
- ## Why FastMCP?
125
-
126
- The MCP protocol is powerful but implementing it involves a lot of boilerplate - server setup, protocol handlers, content types, error management. FastMCP handles all the complex protocol details and server management, so you can focus on building great tools. It's designed to be high-level and Pythonic; in most cases, decorating a function is all you need.
127
-
128
- FastMCP aims to be:
129
-
130
-
131
- 🚀 **Fast:** High-level interface means less code and faster development
132
-
133
- 🍀 **Simple:** Build MCP servers with minimal boilerplate
134
-
135
- 🐍 **Pythonic:** Feels natural to Python developers
136
-
137
- 🔍 **Complete:** FastMCP aims to provide a full implementation of the core MCP specification for both servers and clients
138
-
139
- ## Key Features
140
-
141
- ### Servers
142
- - **Create** servers with minimal boilerplate using intuitive decorators
143
- - **Proxy** existing servers to modify configuration or transport
144
- - **Compose** servers into complex applications
145
- - **Generate** servers from OpenAPI specs or FastAPI objects
146
-
147
- ### Clients
148
- - **Interact** with MCP servers programmatically
149
- - **Connect** to any MCP server using any transport
150
- - **Test** your servers without manual intervention
151
- - **Innovate** with core MCP capabilities like LLM sampling
152
-
153
-
154
- ## What's New in v2?
155
-
156
- FastMCP 1.0 made it so easy to build MCP servers that it's now part of the [official Model Context Protocol Python SDK](https://github.com/modelcontextprotocol/python-sdk)! For basic use cases, you can use the upstream version by importing `mcp.server.fastmcp.FastMCP` (or installing `fastmcp=1.0`).
157
-
158
- Based on how the MCP ecosystem is evolving, FastMCP 2.0 builds on that foundation to introduce a variety of new features (and more experimental ideas). It adds advanced features like proxying and composing MCP servers, as well as automatically generating them from OpenAPI specs or FastAPI objects. FastMCP 2.0 also introduces new client-side functionality like LLM sampling.
159
-
160
-
161
- ## Documentation
162
-
163
- 📚 FastMCP's documentation is available at [gofastmcp.com](https://gofastmcp.com).
164
-
165
- ---
166
-
167
- ### Installation
168
-
169
- We strongly recommend installing FastMCP with [uv](https://docs.astral.sh/uv/), as it is required for deploying servers via the CLI:
170
-
171
- ```bash
172
- uv pip install fastmcp
173
- ```
174
-
175
- Note: on macOS, uv may need to be installed with Homebrew (`brew install uv`) in order to make it available to the Claude Desktop app.
176
-
177
- For development, install with:
178
- ```bash
179
- # Clone the repo first
180
- git clone https://github.com/jlowin/fastmcp.git
181
- cd fastmcp
182
- # Install with dev dependencies
183
- uv sync
184
- ```
185
-
186
- ### Quickstart
187
-
188
- Let's create a simple MCP server that exposes a calculator tool and some data:
189
-
190
- ```python
191
- # server.py
192
- from fastmcp import FastMCP
193
-
194
- # Create an MCP server
195
- mcp = FastMCP("Demo")
196
-
197
- # Add an addition tool
198
- @mcp.tool()
199
- def add(a: int, b: int) -> int:
200
- """Add two numbers"""
201
- return a + b
202
-
203
- # Add a dynamic greeting resource
204
- @mcp.resource("greeting://{name}")
205
- def get_greeting(name: str) -> str:
206
- """Get a personalized greeting"""
207
- return f"Hello, {name}!"
208
- ```
209
-
210
- You can install this server in [Claude Desktop](https://claude.ai/download) and interact with it right away by running:
211
- ```bash
212
- fastmcp install server.py
213
- ```
214
-
215
- ![MCP Inspector](/docs/assets/demo-inspector.png)
216
-
217
-
218
- ## Core Concepts
219
-
220
- These are the building blocks for creating MCP servers, using the familiar decorator-based approach.
221
-
222
- ### The `FastMCP` Server
223
-
224
- The central object representing your MCP application. It handles connections, protocol details, and routing.
225
-
226
- ```python
227
- from fastmcp import FastMCP
228
-
229
- # Create a named server
230
- mcp = FastMCP("My App")
231
-
232
- # Specify dependencies needed when deployed via `fastmcp install`
233
- mcp = FastMCP("My App", dependencies=["pandas", "numpy"])
234
- ```
235
-
236
- ### Tools
237
-
238
- Tools allow LLMs to perform actions by executing your Python functions. They are ideal for tasks that involve computation, external API calls, or side effects.
239
-
240
- Decorate synchronous or asynchronous functions with `@mcp.tool()`. FastMCP automatically generates the necessary MCP schema based on type hints and docstrings. Pydantic models can be used for complex inputs.
241
-
242
- ```python
243
- import httpx
244
- from pydantic import BaseModel
245
-
246
- class UserInfo(BaseModel):
247
- user_id: int
248
- notify: bool = False
249
-
250
- @mcp.tool()
251
- async def send_notification(user: UserInfo, message: str) -> dict:
252
- """Sends a notification to a user if requested."""
253
- if user.notify:
254
- # Simulate sending notification
255
- print(f"Notifying user {user.user_id}: {message}")
256
- return {"status": "sent", "user_id": user.user_id}
257
- return {"status": "skipped", "user_id": user.user_id}
258
-
259
- @mcp.tool()
260
- def get_stock_price(ticker: str) -> float:
261
- """Gets the current price for a stock ticker."""
262
- # Replace with actual API call
263
- prices = {"AAPL": 180.50, "GOOG": 140.20}
264
- return prices.get(ticker.upper(), 0.0)
265
- ```
266
-
267
- ### Resources
268
-
269
- Resources expose data to LLMs. They should primarily provide information without significant computation or side effects (like GET requests).
270
-
271
- Decorate functions with `@mcp.resource("your://uri")`. Use curly braces `{}` in the URI to define dynamic resources (templates) where parts of the URI become function parameters.
272
-
273
- ```python
274
- # Static resource returning simple text
275
- @mcp.resource("config://app-version")
276
- def get_app_version() -> str:
277
- """Returns the application version."""
278
- return "v2.1.0"
279
-
280
- # Dynamic resource template expecting a 'user_id' from the URI
281
- @mcp.resource("db://users/{user_id}/email")
282
- async def get_user_email(user_id: str) -> str:
283
- """Retrieves the email address for a given user ID."""
284
- # Replace with actual database lookup
285
- emails = {"123": "alice@example.com", "456": "bob@example.com"}
286
- return emails.get(user_id, "not_found@example.com")
287
-
288
- # Resource returning JSON data
289
- @mcp.resource("data://product-categories")
290
- def get_categories() -> list[str]:
291
- """Returns a list of available product categories."""
292
- return ["Electronics", "Books", "Home Goods"]
293
- ```
294
-
295
- ### Prompts
296
-
297
- Prompts define reusable templates or interaction patterns for the LLM. They help guide the LLM on how to use your server's capabilities effectively.
298
-
299
- Decorate functions with `@mcp.prompt()`. The function should return the desired prompt content, which can be a simple string, a `Message` object (like `UserMessage` or `AssistantMessage`), or a list of these.
300
-
301
- ```python
302
- from fastmcp.prompts.base import UserMessage, AssistantMessage
303
-
304
- @mcp.prompt()
305
- def ask_review(code_snippet: str) -> str:
306
- """Generates a standard code review request."""
307
- return f"Please review the following code snippet for potential bugs and style issues:\n```python\n{code_snippet}\n```"
308
-
309
- @mcp.prompt()
310
- def debug_session_start(error_message: str) -> list[Message]:
311
- """Initiates a debugging help session."""
312
- return [
313
- UserMessage(f"I encountered an error:\n{error_message}"),
314
- AssistantMessage("Okay, I can help with that. Can you provide the full traceback and tell me what you were trying to do?")
315
- ]
316
- ```
317
-
318
- ### Context
319
-
320
- Gain access to MCP server capabilities *within* your tool or resource functions by adding a parameter type-hinted with `fastmcp.Context`.
321
-
322
- ```python
323
- from fastmcp import Context, FastMCP
324
-
325
- mcp = FastMCP("Context Demo")
326
-
327
- @mcp.resource("system://status")
328
- async def get_system_status(ctx: Context) -> dict:
329
- """Checks system status and logs information."""
330
- await ctx.info("Checking system status...")
331
- # Perform checks
332
- await ctx.report_progress(1, 1) # Report completion
333
- return {"status": "OK", "load": 0.5, "client": ctx.client_id}
334
-
335
- @mcp.tool()
336
- async def process_large_file(file_uri: str, ctx: Context) -> str:
337
- """Processes a large file, reporting progress and reading resources."""
338
- await ctx.info(f"Starting processing for {file_uri}")
339
- # Read the resource using the context
340
- file_content_resource = await ctx.read_resource(file_uri)
341
- file_content = file_content_resource[0].content # Assuming single text content
342
- lines = file_content.splitlines()
343
- total_lines = len(lines)
344
-
345
- for i, line in enumerate(lines):
346
- # Process line...
347
- if (i + 1) % 100 == 0: # Report progress every 100 lines
348
- await ctx.report_progress(i + 1, total_lines)
349
-
350
- await ctx.info(f"Finished processing {file_uri}")
351
- return f"Processed {total_lines} lines."
352
-
353
- ```
354
-
355
- The `Context` object provides:
356
- * Logging: `ctx.debug()`, `ctx.info()`, `ctx.warning()`, `ctx.error()`
357
- * Progress Reporting: `ctx.report_progress(current, total)`
358
- * Resource Access: `await ctx.read_resource(uri)`
359
- * Request Info: `ctx.request_id`, `ctx.client_id`
360
- * Sampling (Advanced): `await ctx.sample(...)` to ask the connected LLM client for completions.
361
-
362
- ### Images
363
-
364
- Easily handle image outputs using the `fastmcp.Image` helper class.
365
-
366
- <Tip>
367
- The below code requires the `pillow` library to be installed.
368
- </Tip>
369
-
370
- ```python
371
- from mcp.server.fastmcp import FastMCP, Image
372
- from io import BytesIO
373
- try:
374
- from PIL import Image as PILImage
375
- except ImportError:
376
- raise ImportError("Please install the `pillow` library to run this example.")
377
-
378
- mcp = FastMCP("My App")
379
-
380
- @mcp.tool()
381
- def create_thumbnail(image_path: str) -> Image:
382
- """Create a thumbnail from an image"""
383
- img = PILImage.open(image_path)
384
- img.thumbnail((100, 100))
385
- buffer = BytesIO()
386
- img.save(buffer, format="PNG")
387
- return Image(data=buffer.getvalue(), format="png")
388
- ```
389
- Return the `Image` helper class from your tool to send an image to the client. The `Image` helper class handles the conversion to/from the base64-encoded format required by the MCP protocol. It works with either a path to an image file, or a bytes object.
390
-
391
-
392
- ### MCP Clients
393
-
394
- The `Client` class lets you interact with any MCP server (not just FastMCP ones) from Python code:
395
-
396
- ```python
397
- from fastmcp import Client
398
-
399
- async with Client("path/to/server") as client:
400
- # Call a tool
401
- result = await client.call_tool("weather", {"location": "San Francisco"})
402
- print(result)
403
-
404
- # Read a resource
405
- res = await client.read_resource("db://users/123/profile")
406
- print(res)
407
- ```
408
-
409
- You can connect to servers using any supported transport protocol (Stdio, SSE, FastMCP, etc.). If you don't specify a transport, the `Client` class automatically attempts to detect an appropriate one from your connection string or server object.
410
-
411
- #### Client Methods
412
-
413
- The `Client` class exposes several methods for interacting with MCP servers.
414
-
415
- ```python
416
- async with Client("path/to/server") as client:
417
- # List available tools
418
- tools = await client.list_tools()
419
-
420
- # List available resources
421
- resources = await client.list_resources()
422
-
423
- # Call a tool with arguments
424
- result = await client.call_tool("generate_report", {"user_id": 123})
425
-
426
- # Read a resource
427
- user_data = await client.read_resource("db://users/123/profile")
428
-
429
- # Get a prompt
430
- greeting = await client.get_prompt("welcome", {"name": "Alice"})
431
-
432
- # Send progress updates
433
- await client.progress("task-123", 50, 100) # 50% complete
434
-
435
- # Basic connectivity testing
436
- await client.ping()
437
- ```
438
-
439
- These methods correspond directly to MCP protocol operations, making it easy to interact with any MCP-compatible server (not just FastMCP ones).
440
-
441
- #### Transport Options
442
-
443
- FastMCP supports various transport protocols for connecting to MCP servers:
444
-
445
- ```python
446
- from fastmcp import Client
447
- from fastmcp.client.transports import (
448
- SSETransport,
449
- PythonStdioTransport,
450
- FastMCPTransport
451
- )
452
-
453
- # Connect to a server over SSE (common for web-based MCP servers)
454
- async with Client(SSETransport("http://localhost:8000/mcp")) as client:
455
- # Use client here...
456
-
457
- # Connect to a Python script using stdio (useful for local tools)
458
- async with Client(PythonStdioTransport("path/to/script.py")) as client:
459
- # Use client here...
460
-
461
- # Connect directly to a FastMCP server object in the same process
462
- from your_app import mcp_server
463
- async with Client(FastMCPTransport(mcp_server)) as client:
464
- # Use client here...
465
- ```
466
-
467
- Common transport options include:
468
- - `SSETransport`: Connect to a server via Server-Sent Events (HTTP)
469
- - `PythonStdioTransport`: Run a Python script and communicate via stdio
470
- - `FastMCPTransport`: Connect directly to a FastMCP server object
471
- - `WSTransport`: Connect via WebSockets
472
-
473
- In addition, if you pass a connection string or `FastMCP` server object to the `Client` constructor, it will try to automatically detect the appropriate transport.
474
-
475
- #### LLM Sampling
476
-
477
- Sampling is an MCP feature that allows a server to request a completion from the client LLM, enabling sophisticated use cases while maintaining security and privacy on the server.
478
-
479
- ```python
480
- import marvin # Or any other LLM client
481
- from fastmcp import Client, Context, FastMCP
482
- from fastmcp.client.sampling import RequestContext, SamplingMessage, SamplingParams
483
-
484
- # -- SERVER SIDE --
485
- # Create a server that requests LLM completions from the client
486
-
487
- mcp = FastMCP("Sampling Example")
488
-
489
- @mcp.tool()
490
- async def generate_poem(topic: str, context: Context) -> str:
491
- """Generate a short poem about the given topic."""
492
- # The server requests a completion from the client LLM
493
- response = await context.sample(
494
- f"Write a short poem about {topic}",
495
- system_prompt="You are a talented poet who writes concise, evocative verses."
496
- )
497
- return response.text
498
-
499
- @mcp.tool()
500
- async def summarize_document(document_uri: str, context: Context) -> str:
501
- """Summarize a document using client-side LLM capabilities."""
502
- # First read the document as a resource
503
- doc_resource = await context.read_resource(document_uri)
504
- doc_content = doc_resource[0].content # Assuming single text content
505
-
506
- # Then ask the client LLM to summarize it
507
- response = await context.sample(
508
- f"Summarize the following document:\n\n{doc_content}",
509
- system_prompt="You are an expert summarizer. Create a concise summary."
510
- )
511
- return response.text
512
-
513
- # -- CLIENT SIDE --
514
- # Create a client that handles the sampling requests
515
-
516
- async def sampling_handler(
517
- messages: list[SamplingMessage],
518
- params: SamplingParams,
519
- ctx: RequestContext,
520
- ) -> str:
521
- """Handle sampling requests from the server using your preferred LLM."""
522
- # Extract the messages and system prompt
523
- prompt = [m.content.text for m in messages if m.content.type == "text"]
524
- system_instruction = params.systemPrompt or "You are a helpful assistant."
525
-
526
- # Use your preferred LLM client to generate completions
527
- return await marvin.say_async(
528
- message=prompt,
529
- instructions=system_instruction,
530
- )
531
-
532
- # Connect them together
533
- async with Client(mcp, sampling_handler=sampling_handler) as client:
534
- result = await client.call_tool("generate_poem", {"topic": "autumn leaves"})
535
- print(result.content[0].text)
536
- ```
537
-
538
- This pattern is powerful because:
539
- 1. The server can delegate text generation to the client LLM
540
- 2. The server remains focused on business logic and data handling
541
- 3. The client maintains control over which LLM is used and how requests are handled
542
- 4. No sensitive data needs to be sent to external APIs
543
-
544
- #### Roots Access
545
-
546
- FastMCP exposes the MCP roots functionality, allowing clients to specify which file system roots they can access. This creates a secure boundary for tools that need to work with files. Note that the server must account for client roots explicitly.
547
-
548
- ```python
549
- from fastmcp import Client, RootsList
550
-
551
- # Specify file roots that the client can access
552
- roots = ["file:///path/to/allowed/directory"]
553
-
554
- async with Client(mcp_server, roots=roots) as client:
555
- # Now tools in the MCP server can access files in the specified roots
556
- await client.call_tool("process_file", {"filename": "data.csv"})
557
- ```
558
-
559
- ## Advanced Features
560
-
561
- Building on the core concepts, FastMCP v2 introduces powerful features for more complex scenarios:
562
-
563
-
564
- ### Proxy Servers
565
-
566
- Create a FastMCP server that acts as an intermediary, proxying requests to another MCP endpoint (which could be a server or another client connection).
567
-
568
- **Use Cases:**
569
-
570
- * **Transport Conversion:** Expose a server running on Stdio (like many local tools) over SSE or WebSockets, making it accessible to web clients or Claude Desktop.
571
- * **Adding Functionality:** Wrap an existing server to add authentication, request logging, or modified tool behavior.
572
- * **Aggregating Servers:** Combine multiple backend MCP servers behind a single proxy interface (though `mount` might be simpler for this).
573
-
574
- ```python
575
- import asyncio
576
- from fastmcp import FastMCP, Client
577
- from fastmcp.client.transports import PythonStdioTransport
578
-
579
- # Create a client that connects to the original server
580
- proxy_client = Client(
581
- transport=PythonStdioTransport('path/to/original_stdio_server.py'),
582
- )
583
-
584
- # Create a proxy server that connects to the client and exposes its capabilities
585
- proxy = FastMCP.from_client(proxy_client, name="Stdio-to-SSE Proxy")
586
-
587
- if __name__ == "__main__":
588
- proxy.run(transport='sse')
589
- ```
590
-
591
- `FastMCP.from_client` is a class method that connects to the target, discovers its capabilities, and dynamically builds the proxy server instance.
592
-
593
-
594
-
595
- ### Composing MCP Servers
596
-
597
- Structure larger MCP applications by creating modular FastMCP servers and "mounting" them onto a parent server. This automatically handles prefixing for tool names and resource URIs, preventing conflicts.
598
-
599
- ```python
600
- from fastmcp import FastMCP
601
-
602
- # --- Weather MCP ---
603
- weather_mcp = FastMCP("Weather Service")
604
-
605
- @weather_mcp.tool()
606
- def get_forecast(city: str):
607
- return f"Sunny in {city}"
608
-
609
- @weather_mcp.resource("data://temp/{city}")
610
- def get_temp(city: str):
611
- return 25.0
612
-
613
- # --- News MCP ---
614
- news_mcp = FastMCP("News Service")
615
-
616
- @news_mcp.tool()
617
- def fetch_headlines():
618
- return ["Big news!", "Other news"]
619
-
620
- @news_mcp.resource("data://latest_story")
621
- def get_story():
622
- return "A story happened."
623
-
624
- # --- Composite MCP ---
625
-
626
- mcp = FastMCP("Composite")
627
-
628
- # Mount sub-apps with prefixes
629
- mcp.mount("weather", weather_mcp) # Tools prefixed "weather/", resources prefixed "weather+"
630
- mcp.mount("news", news_mcp) # Tools prefixed "news/", resources prefixed "news+"
631
-
632
- @mcp.tool()
633
- def ping():
634
- return "Composite OK"
635
-
636
-
637
- if __name__ == "__main__":
638
- mcp.run()
639
- ```
640
-
641
- This promotes code organization and reusability for complex MCP systems.
642
-
643
- ### OpenAPI & FastAPI Generation
644
-
645
- Leverage your existing web APIs by automatically generating FastMCP servers from them.
646
-
647
- By default, the following rules are applied:
648
- - `GET` requests -> MCP resources
649
- - `GET` requests with path parameters -> MCP resource templates
650
- - All other HTTP methods -> MCP tools
651
-
652
- You can override these rules to customize or even ignore certain endpoints.
653
-
654
- **From FastAPI:**
655
-
656
- ```python
657
- from fastapi import FastAPI
658
- from fastmcp import FastMCP
659
-
660
- # Your existing FastAPI application
661
- fastapi_app = FastAPI(title="My Existing API")
662
-
663
- @fastapi_app.get("/status")
664
- def get_status():
665
- return {"status": "running"}
666
-
667
- @fastapi_app.post("/items")
668
- def create_item(name: str, price: float):
669
- return {"id": 1, "name": name, "price": price}
670
-
671
- # Generate an MCP server directly from the FastAPI app
672
- mcp_server = FastMCP.from_fastapi(fastapi_app)
673
-
674
- if __name__ == "__main__":
675
- mcp_server.run()
676
- ```
677
-
678
- **From an OpenAPI Specification:**
679
-
680
- ```python
681
- import httpx
682
- import json
683
- from fastmcp import FastMCP
684
-
685
- # Load the OpenAPI spec (dict)
686
- # with open("my_api_spec.json", "r") as f:
687
- # openapi_spec = json.load(f)
688
- openapi_spec = { ... } # Your spec dict
689
-
690
- # Create an HTTP client to make requests to the actual API endpoint
691
- http_client = httpx.AsyncClient(base_url="https://api.yourservice.com")
692
-
693
- # Generate the MCP server
694
- mcp_server = FastMCP.from_openapi(openapi_spec, client=http_client)
695
-
696
- if __name__ == "__main__":
697
- mcp_server.run()
698
- ```
699
-
700
- ### Handling `stderr`
701
- The MCP spec allows for the server to write anything it wants to `stderr`, and it
702
- doesn't specify the format in any way. FastMCP will forward the server's `stderr`
703
- to the client's `stderr`.
704
-
705
- ## Running Your Server
706
-
707
- Choose the method that best suits your needs:
708
-
709
- ### Development Mode (Recommended for Building & Testing)
710
-
711
- Use `fastmcp dev` for an interactive testing environment with the MCP Inspector.
712
-
713
- ```bash
714
- fastmcp dev your_server_file.py
715
- # With temporary dependencies
716
- fastmcp dev your_server_file.py --with pandas --with numpy
717
- # With local package in editable mode
718
- fastmcp dev your_server_file.py --with-editable .
719
- ```
720
-
721
- ### Claude Desktop Integration (For Regular Use)
722
-
723
- Use `fastmcp install` to set up your server for persistent use within the Claude Desktop app. It handles creating an isolated environment using `uv`.
724
-
725
- ```bash
726
- fastmcp install your_server_file.py
727
- # With a custom name in Claude
728
- fastmcp install your_server_file.py --name "My Analysis Tool"
729
- # With extra packages and environment variables
730
- fastmcp install server.py --with requests -v API_KEY=123 -f .env
731
- ```
732
-
733
- ### Direct Execution (For Advanced Use Cases)
734
-
735
- Run your server script directly for custom deployments or integrations outside of Claude. You manage the environment and dependencies yourself.
736
-
737
- Add to your `your_server_file.py`:
738
- ```python
739
- if __name__ == "__main__":
740
- mcp.run() # Assuming 'mcp' is your FastMCP instance
741
- ```
742
- Run with:
743
- ```bash
744
- python your_server_file.py
745
- # or
746
- uv run python your_server_file.py
747
- ```
748
-
749
- ### Server Object Names
750
-
751
- If your `FastMCP` instance is not named `mcp`, `server`, or `app`, specify it using `file:object` syntax for the `dev` and `install` commands:
752
-
753
- ```bash
754
- fastmcp dev my_module.py:my_mcp_instance
755
- fastmcp install api.py:api_app
756
- ```
757
-
758
- ## Examples
759
-
760
- Explore the `examples/` directory for code samples demonstrating various features:
761
-
762
- * `simple_echo.py`: Basic tool, resource, and prompt.
763
- * `complex_inputs.py`: Using Pydantic models for tool inputs.
764
- * `mount_example.py`: Mounting multiple FastMCP servers.
765
- * `sampling.py`: Using LLM completions within your MCP server.
766
- * `screenshot.py`: Tool returning an Image object.
767
- * `text_me.py`: Tool interacting with an external API.
768
- * `memory.py`: More complex example with database interaction.
769
-
770
- ## Contributing
771
-
772
- Contributions make the open-source community vibrant! We welcome improvements and features.
773
-
774
- <details>
775
-
776
- <summary><h3>Open Developer Guide</h3></summary>
777
-
778
- #### Prerequisites
779
-
780
- * Python 3.10+
781
- * [uv](https://docs.astral.sh/uv/)
782
-
783
- #### Setup
784
-
785
- 1. Clone: `git clone https://github.com/jlowin/fastmcp.git && cd fastmcp`
786
- 2. Install Env & Dependencies: `uv venv && uv sync` (Activate the `.venv` after creation)
787
-
788
- #### Testing
789
-
790
- Run the test suite:
791
- ```bash
792
- uv run pytest -vv
793
- ```
794
-
795
- #### Formatting & Linting
796
-
797
- We use `ruff` via `pre-commit`.
798
- 1. Install hooks: `pre-commit install`
799
- 2. Run checks: `pre-commit run --all-files`
800
-
801
- #### Pull Requests
802
-
803
- 1. Fork the repository.
804
- 2. Create a feature branch.
805
- 3. Make changes, commit, and push to your fork.
806
- 4. Open a pull request against the `main` branch of `jlowin/fastmcp`.
807
-
808
- Please open an issue or discussion for questions or suggestions!
809
-
810
- </details>