fastmcp 0.2.0__py3-none-any.whl → 0.3.1__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.
- fastmcp/__init__.py +8 -2
- fastmcp/cli/__init__.py +3 -1
- fastmcp/cli/claude.py +20 -18
- fastmcp/cli/cli.py +20 -16
- fastmcp/prompts/__init__.py +4 -0
- fastmcp/prompts/base.py +149 -0
- fastmcp/prompts/manager.py +50 -0
- fastmcp/prompts/prompt_manager.py +36 -0
- fastmcp/resources/__init__.py +23 -0
- fastmcp/resources/base.py +63 -0
- fastmcp/resources/resource_manager.py +94 -0
- fastmcp/resources/templates.py +80 -0
- fastmcp/resources/types.py +171 -0
- fastmcp/server.py +449 -112
- fastmcp/tools/__init__.py +4 -0
- fastmcp/tools/base.py +79 -0
- fastmcp/tools/tool_manager.py +55 -0
- fastmcp/utilities/logging.py +6 -5
- fastmcp/utilities/types.py +53 -0
- fastmcp-0.3.1.dist-info/METADATA +407 -0
- fastmcp-0.3.1.dist-info/RECORD +26 -0
- {fastmcp-0.2.0.dist-info → fastmcp-0.3.1.dist-info}/WHEEL +1 -2
- fastmcp-0.3.1.dist-info/licenses/LICENSE +201 -0
- fastmcp/_version.py +0 -16
- fastmcp/app.py +0 -6
- fastmcp/resources.py +0 -232
- fastmcp/tools.py +0 -150
- fastmcp-0.2.0.dist-info/METADATA +0 -143
- fastmcp-0.2.0.dist-info/RECORD +0 -17
- fastmcp-0.2.0.dist-info/top_level.txt +0 -1
- {fastmcp-0.2.0.dist-info → fastmcp-0.3.1.dist-info}/entry_points.txt +0 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
fastmcp/_version.py
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
# file generated by setuptools_scm
|
|
2
|
-
# don't change, don't track in version control
|
|
3
|
-
TYPE_CHECKING = False
|
|
4
|
-
if TYPE_CHECKING:
|
|
5
|
-
from typing import Tuple, Union
|
|
6
|
-
VERSION_TUPLE = Tuple[Union[int, str], ...]
|
|
7
|
-
else:
|
|
8
|
-
VERSION_TUPLE = object
|
|
9
|
-
|
|
10
|
-
version: str
|
|
11
|
-
__version__: str
|
|
12
|
-
__version_tuple__: VERSION_TUPLE
|
|
13
|
-
version_tuple: VERSION_TUPLE
|
|
14
|
-
|
|
15
|
-
__version__ = version = '0.2.0'
|
|
16
|
-
__version_tuple__ = version_tuple = (0, 2, 0)
|
fastmcp/app.py
DELETED
fastmcp/resources.py
DELETED
|
@@ -1,232 +0,0 @@
|
|
|
1
|
-
import pydantic.json
|
|
2
|
-
|
|
3
|
-
import abc
|
|
4
|
-
import asyncio
|
|
5
|
-
import json
|
|
6
|
-
from pathlib import Path
|
|
7
|
-
from typing import Dict, Optional, Callable, Any, Union, Awaitable
|
|
8
|
-
|
|
9
|
-
import httpx
|
|
10
|
-
from pydantic import BaseModel, field_validator
|
|
11
|
-
from pydantic.networks import _BaseUrl
|
|
12
|
-
|
|
13
|
-
from .utilities.logging import get_logger
|
|
14
|
-
|
|
15
|
-
logger = get_logger(__name__)
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
class Resource(BaseModel):
|
|
19
|
-
"""Base class for all resources.
|
|
20
|
-
|
|
21
|
-
Resources can contain either text (UTF-8 encoded) or binary data.
|
|
22
|
-
Text resources are suitable for source code, logs, JSON, etc.
|
|
23
|
-
Binary resources are suitable for images, PDFs, audio, etc.
|
|
24
|
-
"""
|
|
25
|
-
|
|
26
|
-
uri: _BaseUrl
|
|
27
|
-
name: str
|
|
28
|
-
description: Optional[str] = None
|
|
29
|
-
mime_type: Optional[str] = None
|
|
30
|
-
is_binary: bool = False
|
|
31
|
-
|
|
32
|
-
@field_validator("name", mode="before")
|
|
33
|
-
@classmethod
|
|
34
|
-
def set_default_name(cls, name: str | None, info) -> str:
|
|
35
|
-
"""Set default name from URI if not provided."""
|
|
36
|
-
if name is not None:
|
|
37
|
-
return name
|
|
38
|
-
# Extract everything after the protocol (e.g., "desktop" from "resource://desktop")
|
|
39
|
-
uri = info.data.get("uri")
|
|
40
|
-
if uri:
|
|
41
|
-
return str(uri).split("://", 1)[1]
|
|
42
|
-
raise ValueError("Either name or uri must be provided")
|
|
43
|
-
|
|
44
|
-
@abc.abstractmethod
|
|
45
|
-
async def read(self) -> Union[str, bytes]:
|
|
46
|
-
"""Read the resource content.
|
|
47
|
-
|
|
48
|
-
Returns:
|
|
49
|
-
Union[str, bytes]: Text content as str for text resources,
|
|
50
|
-
binary content as bytes for binary resources
|
|
51
|
-
"""
|
|
52
|
-
return ""
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
class FunctionResource(Resource):
|
|
56
|
-
"""A resource that is generated by a function call.
|
|
57
|
-
|
|
58
|
-
The function can be sync or async and must return a string, bytes,
|
|
59
|
-
or another Resource.
|
|
60
|
-
"""
|
|
61
|
-
|
|
62
|
-
func: Union[Callable[[], Any], Callable[[], Awaitable[Any]]]
|
|
63
|
-
is_async: bool = False
|
|
64
|
-
|
|
65
|
-
def __init__(self, **data):
|
|
66
|
-
super().__init__(**data)
|
|
67
|
-
self.is_async = asyncio.iscoroutinefunction(self.func)
|
|
68
|
-
|
|
69
|
-
async def read(self) -> Union[str, bytes]:
|
|
70
|
-
"""Read the resource content by calling the function."""
|
|
71
|
-
try:
|
|
72
|
-
result = (
|
|
73
|
-
await self.func()
|
|
74
|
-
if self.is_async
|
|
75
|
-
else await asyncio.to_thread(self.func)
|
|
76
|
-
)
|
|
77
|
-
|
|
78
|
-
if isinstance(result, Resource):
|
|
79
|
-
return await result.read()
|
|
80
|
-
if isinstance(result, bytes):
|
|
81
|
-
return result
|
|
82
|
-
if not isinstance(result, str):
|
|
83
|
-
try:
|
|
84
|
-
return json.dumps(result, default=pydantic.json.pydantic_encoder)
|
|
85
|
-
except json.JSONDecodeError:
|
|
86
|
-
return str(result)
|
|
87
|
-
return result
|
|
88
|
-
except Exception as e:
|
|
89
|
-
raise ValueError(f"Error calling function {self.func.__name__}: {e}")
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
class FileResource(Resource):
|
|
93
|
-
"""A file resource."""
|
|
94
|
-
|
|
95
|
-
path: Path
|
|
96
|
-
|
|
97
|
-
@field_validator("path")
|
|
98
|
-
@classmethod
|
|
99
|
-
def validate_absolute_path(cls, path: Path) -> Path:
|
|
100
|
-
"""Ensure path is absolute."""
|
|
101
|
-
if not path.is_absolute():
|
|
102
|
-
raise ValueError(f"Path must be absolute: {path}")
|
|
103
|
-
return path
|
|
104
|
-
|
|
105
|
-
async def read(self) -> Union[str, bytes]:
|
|
106
|
-
"""Read the file content."""
|
|
107
|
-
try:
|
|
108
|
-
if self.is_binary:
|
|
109
|
-
return await asyncio.to_thread(self.path.read_bytes)
|
|
110
|
-
return await asyncio.to_thread(self.path.read_text)
|
|
111
|
-
except FileNotFoundError:
|
|
112
|
-
raise FileNotFoundError(f"File not found: {self.path}")
|
|
113
|
-
except PermissionError:
|
|
114
|
-
raise PermissionError(f"Permission denied: {self.path}")
|
|
115
|
-
except Exception as e:
|
|
116
|
-
raise ValueError(f"Error reading file {self.path}: {e}")
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
class HttpResource(Resource):
|
|
120
|
-
"""An HTTP resource."""
|
|
121
|
-
|
|
122
|
-
url: str
|
|
123
|
-
headers: Optional[Dict[str, str]] = None
|
|
124
|
-
|
|
125
|
-
async def read(self) -> Union[str, bytes]:
|
|
126
|
-
"""Read the HTTP resource content."""
|
|
127
|
-
try:
|
|
128
|
-
async with httpx.AsyncClient() as client:
|
|
129
|
-
response = await client.get(self.url, headers=self.headers)
|
|
130
|
-
response.raise_for_status()
|
|
131
|
-
return response.content if self.is_binary else response.text
|
|
132
|
-
except httpx.HTTPStatusError as e:
|
|
133
|
-
raise ValueError(f"HTTP error {e.response.status_code}: {e}")
|
|
134
|
-
except httpx.RequestError as e:
|
|
135
|
-
raise ValueError(f"Request failed: {e}")
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
class DirectoryResource(Resource):
|
|
139
|
-
"""A directory resource."""
|
|
140
|
-
|
|
141
|
-
path: Path
|
|
142
|
-
recursive: bool = False
|
|
143
|
-
pattern: Optional[str] = None
|
|
144
|
-
mime_type: Optional[str] = "application/json"
|
|
145
|
-
|
|
146
|
-
@field_validator("path")
|
|
147
|
-
@classmethod
|
|
148
|
-
def validate_absolute_path(cls, path: Path) -> Path:
|
|
149
|
-
"""Ensure path is absolute."""
|
|
150
|
-
if not path.is_absolute():
|
|
151
|
-
raise ValueError(f"Path must be absolute: {path}")
|
|
152
|
-
return path
|
|
153
|
-
|
|
154
|
-
def list_files(self) -> list[Path]:
|
|
155
|
-
"""List files in the directory."""
|
|
156
|
-
if not self.path.exists():
|
|
157
|
-
raise FileNotFoundError(f"Directory not found: {self.path}")
|
|
158
|
-
if not self.path.is_dir():
|
|
159
|
-
raise NotADirectoryError(f"Not a directory: {self.path}")
|
|
160
|
-
|
|
161
|
-
try:
|
|
162
|
-
if self.pattern:
|
|
163
|
-
return (
|
|
164
|
-
list(self.path.glob(self.pattern))
|
|
165
|
-
if not self.recursive
|
|
166
|
-
else list(self.path.rglob(self.pattern))
|
|
167
|
-
)
|
|
168
|
-
return (
|
|
169
|
-
list(self.path.glob("*"))
|
|
170
|
-
if not self.recursive
|
|
171
|
-
else list(self.path.rglob("*"))
|
|
172
|
-
)
|
|
173
|
-
except Exception as e:
|
|
174
|
-
raise ValueError(f"Error listing directory {self.path}: {e}")
|
|
175
|
-
|
|
176
|
-
async def read(self) -> str: # Always returns JSON string
|
|
177
|
-
"""Read the directory listing."""
|
|
178
|
-
try:
|
|
179
|
-
files = await asyncio.to_thread(self.list_files)
|
|
180
|
-
file_list = [str(f.relative_to(self.path)) for f in files if f.is_file()]
|
|
181
|
-
return json.dumps({"files": file_list}, indent=2)
|
|
182
|
-
except Exception as e:
|
|
183
|
-
raise ValueError(f"Error reading directory {self.path}: {e}")
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
class ResourceManager:
|
|
187
|
-
"""Manages FastMCP resources."""
|
|
188
|
-
|
|
189
|
-
def __init__(self, warn_on_duplicate_resources: bool = True):
|
|
190
|
-
self._resources: Dict[str, Resource] = {}
|
|
191
|
-
self.warn_on_duplicate_resources = warn_on_duplicate_resources
|
|
192
|
-
|
|
193
|
-
def get_resource(self, uri: Union[_BaseUrl, str]) -> Optional[Resource]:
|
|
194
|
-
"""Get resource by URI."""
|
|
195
|
-
uri = str(uri)
|
|
196
|
-
logger.debug("Getting resource", extra={"uri": uri})
|
|
197
|
-
|
|
198
|
-
if resource := self._resources.get(uri):
|
|
199
|
-
return resource
|
|
200
|
-
|
|
201
|
-
raise ValueError(f"Unknown resource: {uri}")
|
|
202
|
-
|
|
203
|
-
def list_resources(self) -> list[Resource]:
|
|
204
|
-
"""List all registered resources."""
|
|
205
|
-
logger.debug("Listing resources", extra={"count": len(self._resources)})
|
|
206
|
-
return list(self._resources.values())
|
|
207
|
-
|
|
208
|
-
def add_resource(self, resource: Resource) -> Resource:
|
|
209
|
-
"""Add a resource to the manager.
|
|
210
|
-
|
|
211
|
-
Args:
|
|
212
|
-
resource: A Resource instance to add
|
|
213
|
-
|
|
214
|
-
Returns:
|
|
215
|
-
The added resource. If a resource with the same URI already exists,
|
|
216
|
-
returns the existing resource.
|
|
217
|
-
"""
|
|
218
|
-
logger.debug(
|
|
219
|
-
"Adding resource",
|
|
220
|
-
extra={
|
|
221
|
-
"uri": resource.uri,
|
|
222
|
-
"type": type(resource).__name__,
|
|
223
|
-
"name": resource.name,
|
|
224
|
-
},
|
|
225
|
-
)
|
|
226
|
-
existing = self._resources.get(str(resource.uri))
|
|
227
|
-
if existing:
|
|
228
|
-
if self.warn_on_duplicate_resources:
|
|
229
|
-
logger.warning(f"Resource already exists: {resource.uri}")
|
|
230
|
-
return existing
|
|
231
|
-
self._resources[str(resource.uri)] = resource
|
|
232
|
-
return resource
|
fastmcp/tools.py
DELETED
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
"""Tool management for FastMCP."""
|
|
2
|
-
|
|
3
|
-
import base64
|
|
4
|
-
import inspect
|
|
5
|
-
from pathlib import Path
|
|
6
|
-
from typing import Any, Callable, Dict, Optional, Union
|
|
7
|
-
|
|
8
|
-
from mcp.types import ImageContent
|
|
9
|
-
from pydantic import BaseModel, Field, TypeAdapter, validate_call
|
|
10
|
-
|
|
11
|
-
from .exceptions import ToolError
|
|
12
|
-
from .utilities.logging import get_logger
|
|
13
|
-
|
|
14
|
-
logger = get_logger(__name__)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class Image:
|
|
18
|
-
"""Helper class for returning images from tools."""
|
|
19
|
-
|
|
20
|
-
def __init__(
|
|
21
|
-
self,
|
|
22
|
-
path: Optional[Union[str, Path]] = None,
|
|
23
|
-
data: Optional[bytes] = None,
|
|
24
|
-
format: Optional[str] = None,
|
|
25
|
-
):
|
|
26
|
-
if path is None and data is None:
|
|
27
|
-
raise ValueError("Either path or data must be provided")
|
|
28
|
-
if path is not None and data is not None:
|
|
29
|
-
raise ValueError("Only one of path or data can be provided")
|
|
30
|
-
|
|
31
|
-
self.path = Path(path) if path else None
|
|
32
|
-
self.data = data
|
|
33
|
-
self._format = format
|
|
34
|
-
self._mime_type = self._get_mime_type()
|
|
35
|
-
|
|
36
|
-
def _get_mime_type(self) -> str:
|
|
37
|
-
"""Get MIME type from format or guess from file extension."""
|
|
38
|
-
if self._format:
|
|
39
|
-
return f"image/{self._format.lower()}"
|
|
40
|
-
|
|
41
|
-
if self.path:
|
|
42
|
-
suffix = self.path.suffix.lower()
|
|
43
|
-
return {
|
|
44
|
-
".png": "image/png",
|
|
45
|
-
".jpg": "image/jpeg",
|
|
46
|
-
".jpeg": "image/jpeg",
|
|
47
|
-
".gif": "image/gif",
|
|
48
|
-
".webp": "image/webp",
|
|
49
|
-
}.get(suffix, "application/octet-stream")
|
|
50
|
-
return "image/png" # default for raw binary data
|
|
51
|
-
|
|
52
|
-
def to_image_content(self) -> ImageContent:
|
|
53
|
-
"""Convert to MCP ImageContent."""
|
|
54
|
-
if self.path:
|
|
55
|
-
with open(self.path, "rb") as f:
|
|
56
|
-
data = base64.b64encode(f.read()).decode()
|
|
57
|
-
else:
|
|
58
|
-
data = base64.b64encode(self.data).decode()
|
|
59
|
-
|
|
60
|
-
return ImageContent(type="image", data=data, mimeType=self._mime_type)
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
class Tool(BaseModel):
|
|
64
|
-
"""Internal tool registration info."""
|
|
65
|
-
|
|
66
|
-
func: Callable = Field(exclude=True)
|
|
67
|
-
name: str = Field(description="Name of the tool")
|
|
68
|
-
description: str = Field(description="Description of what the tool does")
|
|
69
|
-
parameters: dict = Field(description="JSON schema for tool parameters")
|
|
70
|
-
is_async: bool = Field(description="Whether the tool is async")
|
|
71
|
-
|
|
72
|
-
@classmethod
|
|
73
|
-
def from_function(
|
|
74
|
-
cls,
|
|
75
|
-
func: Callable,
|
|
76
|
-
name: Optional[str] = None,
|
|
77
|
-
description: Optional[str] = None,
|
|
78
|
-
) -> "Tool":
|
|
79
|
-
"""Create a Tool from a function."""
|
|
80
|
-
func_name = name or func.__name__
|
|
81
|
-
|
|
82
|
-
if func_name == "<lambda>":
|
|
83
|
-
raise ValueError("You must provide a name for lambda functions")
|
|
84
|
-
|
|
85
|
-
func_doc = description or func.__doc__ or ""
|
|
86
|
-
is_async = inspect.iscoroutinefunction(func)
|
|
87
|
-
|
|
88
|
-
# Get schema from TypeAdapter - will fail if function isn't properly typed
|
|
89
|
-
parameters = TypeAdapter(func).json_schema()
|
|
90
|
-
|
|
91
|
-
# ensure the arguments are properly cast
|
|
92
|
-
func = validate_call(func)
|
|
93
|
-
|
|
94
|
-
return cls(
|
|
95
|
-
func=func,
|
|
96
|
-
name=func_name,
|
|
97
|
-
description=func_doc,
|
|
98
|
-
parameters=parameters,
|
|
99
|
-
is_async=is_async,
|
|
100
|
-
)
|
|
101
|
-
|
|
102
|
-
async def run(self, arguments: dict) -> Any:
|
|
103
|
-
"""Run the tool with arguments."""
|
|
104
|
-
try:
|
|
105
|
-
# Call function with proper async handling
|
|
106
|
-
if self.is_async:
|
|
107
|
-
return await self.func(**arguments)
|
|
108
|
-
return self.func(**arguments)
|
|
109
|
-
except Exception as e:
|
|
110
|
-
raise ToolError(f"Error executing tool {self.name}: {e}") from e
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
class ToolManager:
|
|
114
|
-
"""Manages FastMCP tools."""
|
|
115
|
-
|
|
116
|
-
def __init__(self, warn_on_duplicate_tools: bool = True):
|
|
117
|
-
self._tools: Dict[str, Tool] = {}
|
|
118
|
-
self.warn_on_duplicate_tools = warn_on_duplicate_tools
|
|
119
|
-
|
|
120
|
-
def get_tool(self, name: str) -> Optional[Tool]:
|
|
121
|
-
"""Get tool by name."""
|
|
122
|
-
return self._tools.get(name)
|
|
123
|
-
|
|
124
|
-
def list_tools(self) -> list[Tool]:
|
|
125
|
-
"""List all registered tools."""
|
|
126
|
-
return list(self._tools.values())
|
|
127
|
-
|
|
128
|
-
def add_tool(
|
|
129
|
-
self,
|
|
130
|
-
func: Callable,
|
|
131
|
-
name: Optional[str] = None,
|
|
132
|
-
description: Optional[str] = None,
|
|
133
|
-
) -> Tool:
|
|
134
|
-
"""Add a tool to the server."""
|
|
135
|
-
tool = Tool.from_function(func, name=name, description=description)
|
|
136
|
-
existing = self._tools.get(tool.name)
|
|
137
|
-
if existing:
|
|
138
|
-
if self.warn_on_duplicate_tools:
|
|
139
|
-
logger.warning(f"Tool already exists: {tool.name}")
|
|
140
|
-
return existing
|
|
141
|
-
self._tools[tool.name] = tool
|
|
142
|
-
return tool
|
|
143
|
-
|
|
144
|
-
async def call_tool(self, name: str, arguments: dict) -> Any:
|
|
145
|
-
"""Call a tool by name with arguments."""
|
|
146
|
-
tool = self.get_tool(name)
|
|
147
|
-
if not tool:
|
|
148
|
-
raise ToolError(f"Unknown tool: {name}")
|
|
149
|
-
|
|
150
|
-
return await tool.run(arguments)
|