Jeremiah Lowin commited on
Commit
4647681
·
unverified ·
2 Parent(s): 980ee4c0b08fee

Merge pull request #745 from jlowin/transform-tools-2

Browse files
docs/docs.json CHANGED
@@ -125,6 +125,7 @@
125
  {
126
  "group": "Patterns",
127
  "pages": [
 
128
  "patterns/decorating-methods",
129
  "patterns/http-requests",
130
  "patterns/testing",
 
125
  {
126
  "group": "Patterns",
127
  "pages": [
128
+ "patterns/tool-transformation",
129
  "patterns/decorating-methods",
130
  "patterns/http-requests",
131
  "patterns/testing",
docs/patterns/tool-transformation.mdx ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Tool Transformation
3
+ sidebarTitle: Tool Transformation
4
+ description: Create enhanced tool variants with modified schemas, argument mappings, and custom behavior.
5
+ icon: wand-magic-sparkles
6
+ ---
7
+
8
+ import { VersionBadge } from '/snippets/version-badge.mdx'
9
+
10
+ <VersionBadge version="2.8.0" />
11
+
12
+ Tool transformation allows you to create new, enhanced tools from existing ones. This powerful feature enables you to adapt tools for different contexts, simplify complex interfaces, or add custom logic without duplicating code.
13
+
14
+ ## Why Transform Tools?
15
+
16
+ Often, an existing tool is *almost* perfect for your use case, but it might have:
17
+ - A confusing description (or no description at all).
18
+ - Argument names or descriptions that are not intuitive for an LLM (e.g., `q` instead of `query`).
19
+ - Unnecessary parameters that you want to hide from the LLM.
20
+ - A need for input validation before the original tool is called.
21
+ - A need to modify or format the tool's output.
22
+
23
+ Instead of rewriting the tool from scratch, you can **transform** it to fit your needs.
24
+
25
+ ## Basic Transformation
26
+
27
+ The primary way to create a transformed tool is with the `Tool.from_tool()` class method. At its simplest, you can use it to change a tool's top-level metadata like its `name`, `description`, or `tags`.
28
+
29
+ In the following simple example, we take a generic `search` tool and adjust its name and description to help an LLM client better understand its purpose.
30
+
31
+ ```python {13-21}
32
+ from fastmcp import FastMCP
33
+ from fastmcp.tools import Tool
34
+
35
+ mcp = FastMCP()
36
+
37
+ # The original, generic tool
38
+ @mcp.tool
39
+ def search(query: str, category: str = "all") -> list[dict]:
40
+ """Searches for items in the database."""
41
+ return database.search(query, category)
42
+
43
+ # Create a more domain-specific version by changing its metadata
44
+ product_search_tool = Tool.from_tool(
45
+ search,
46
+ name="find_products",
47
+ description="""
48
+ Search for products in the e-commerce catalog.
49
+ Use this when customers ask about finding specific items,
50
+ checking availability, or browsing product categories.
51
+ """,
52
+ )
53
+
54
+ mcp.add_tool(product_search_tool)
55
+ ```
56
+ Now, clients see a tool named `find_products` with a clear, domain-specific purpose and relevant tags, even though it still uses the original generic `search` function's logic.
57
+
58
+ ### Parameters
59
+
60
+ The `Tool.from_tool()` class method is the primary way to create a transformed tool. It takes the following parameters:
61
+
62
+ - `tool`: The tool to transform. This is the only required argument.
63
+ - `name`: An optional name for the new tool.
64
+ - `description`: An optional description for the new tool.
65
+ - `transform_args`: A dictionary of `ArgTransform` objects, one for each argument you want to modify.
66
+ - `transform_fn`: An optional function that will be called instead of the parent tool's logic.
67
+ - `tags`: An optional set of tags for the new tool.
68
+ - `annotations`: An optional set of `ToolAnnotations` for the new tool.
69
+ - `serializer`: An optional function that will be called to serialize the result of the new tool.
70
+
71
+ The result is a new `TransformedTool` object that wraps the parent tool and applies the transformations you specify. You can add this tool to your MCP server using its `add_tool()` method.
72
+
73
+
74
+
75
+ ## Modifying Arguments
76
+
77
+ To modify a tool's parameters, provide a dictionary of `ArgTransform` objects to the `transform_args` parameter of `Tool.from_tool()`. Each key is the name of the *original* argument you want to modify.
78
+
79
+ <Tip>
80
+ You only need to provide a `transform_args` entry for arguments you want to modify. All other arguments will be passed through unchanged.
81
+ </Tip>
82
+
83
+ ### The ArgTransform Class
84
+
85
+ To modify an argument, you need to create an `ArgTransform` object. This object has the following parameters:
86
+
87
+ - `name`: The new name for the argument.
88
+ - `description`: The new description for the argument.
89
+ - `default`: The new default value for the argument.
90
+ - `default_factory`: A function that will be called to generate a default value for the argument. This is useful for arguments that need to be generated for each tool call, such as timestamps or unique IDs.
91
+ - `hide`: Whether to hide the argument from the LLM.
92
+ - `required`: Whether the argument is required, usually used to make an optional argument be required instead.
93
+ - `type`: The new type for the argument.
94
+
95
+ <Tip>
96
+ Certain combinations of parameters are not allowed. For example, you can only use `default_factory` with `hide=True`, because dynamic defaults cannot be represented in a JSON schema for the client. You can only set required=True for arguments that do not declare a default value.
97
+ </Tip>
98
+
99
+
100
+ ### Descriptions
101
+
102
+ By far the most common reason to transform a tool, after its own description, is to improve its argument descriptions. A good description is crucial for helping an LLM understand how to use a parameter correctly. This is especially important when wrapping tools from external APIs, whose argument descriptions may be missing or written for developers, not LLMs.
103
+
104
+ In this example, we add a helpful description to the `user_id` argument:
105
+
106
+ ```python {16-19}
107
+ from fastmcp import FastMCP
108
+ from fastmcp.tools import Tool
109
+ from fastmcp.tools.tool_transform import ArgTransform
110
+
111
+ mcp = FastMCP()
112
+
113
+ @mcp.tool
114
+ def find_user(user_id: str):
115
+ """Finds a user by their ID."""
116
+ ...
117
+
118
+ new_tool = Tool.from_tool(
119
+ find_user,
120
+ transform_args={
121
+ "user_id": ArgTransform(
122
+ description=(
123
+ "The unique identifier for the user, "
124
+ "usually in the format 'usr-xxxxxxxx'."
125
+ )
126
+ )
127
+ }
128
+ )
129
+ ```
130
+
131
+ ### Names
132
+
133
+ At times, you may want to rename an argument to make it more intuitive for an LLM.
134
+
135
+ For example, in the following example, we take a generic `q` argument and expand it to `search_query`:
136
+
137
+ ```python {15}
138
+ from fastmcp import FastMCP
139
+ from fastmcp.tools import Tool
140
+ from fastmcp.tools.tool_transform import ArgTransform
141
+
142
+ mcp = FastMCP()
143
+
144
+ @mcp.tool
145
+ def search(q: str):
146
+ """Searches for items in the database."""
147
+ return database.search(q)
148
+
149
+ new_tool = Tool.from_tool(
150
+ search,
151
+ transform_args={
152
+ "q": ArgTransform(name="search_query")
153
+ }
154
+ )
155
+ ```
156
+
157
+ ### Default Values
158
+
159
+ You can update the default value for any argument using the `default` parameter. Here, we change the default value of the `y` argument to 10:
160
+
161
+ ```python{15}
162
+ from fastmcp import FastMCP
163
+ from fastmcp.tools import Tool
164
+ from fastmcp.tools.tool_transform import ArgTransform
165
+
166
+ mcp = FastMCP()
167
+
168
+ @mcp.tool
169
+ def add(x: int, y: int) -> int:
170
+ """Adds two numbers."""
171
+ return x + y
172
+
173
+ new_tool = Tool.from_tool(
174
+ add,
175
+ transform_args={
176
+ "y": ArgTransform(default=10)
177
+ }
178
+ )
179
+ ```
180
+
181
+ Default values are especially useful in combination with hidden arguments.
182
+
183
+ ### Hiding Arguments
184
+
185
+ Sometimes a tool requires arguments that shouldn't be exposed to the LLM, such as API keys, configuration flags, or internal IDs. You can hide these parameters using `hide=True`. Note that you can only hide arguments that have a default value (or for which you provide a new default), because the LLM can't provide a value at call time.
186
+
187
+ <Tip>
188
+ To pass a constant value to the parent tool, combine `hide=True` with `default=<value>`.
189
+ </Tip>
190
+
191
+ ```python {19-20}
192
+ import os
193
+ from fastmcp import FastMCP
194
+ from fastmcp.tools import Tool
195
+ from fastmcp.tools.tool_transform import ArgTransform
196
+
197
+ mcp = FastMCP()
198
+
199
+ @mcp.tool
200
+ def send_email(to: str, subject: str, body: str, api_key: str):
201
+ """Sends an email."""
202
+ ...
203
+
204
+ # Create a simplified version that hides the API key
205
+ new_tool = Tool.from_tool(
206
+ send_email,
207
+ name="send_notification",
208
+ transform_args={
209
+ "api_key": ArgTransform(
210
+ hide=True,
211
+ default=os.environ.get("EMAIL_API_KEY"),
212
+ )
213
+ }
214
+ )
215
+ ```
216
+ The LLM now only sees the `to`, `subject`, and `body` parameters. The `api_key` is supplied automatically from an environment variable.
217
+
218
+ For values that must be generated for each tool call (like timestamps or unique IDs), use `default_factory`, which is called with no arguments every time the tool is called. For example,
219
+
220
+ ```python {3-4}
221
+ transform_args = {
222
+ 'timestamp': ArgTransform(
223
+ hide=True,
224
+ default_factory=lambda: datetime.now(),
225
+ )
226
+ }
227
+ ```
228
+
229
+ <Warning>
230
+ `default_factory` can only be used with `hide=True`. This is because visible parameters need static defaults that can be represented in a JSON schema for the client.
231
+ </Warning>
232
+
233
+ ### Required Values
234
+
235
+ In rare cases where you want to make an optional argument required, you can set `required=True`. This has no effect if the argument was already required.
236
+
237
+ ```python {3}
238
+ transform_args = {
239
+ 'user_id': ArgTransform(
240
+ required=True,
241
+ )
242
+ }
243
+ ```
244
+
245
+ ## Modifying Tool Behavior
246
+
247
+ <Warning>
248
+ With great power comes great responsibility. Modifying tool behavior is a very advanced feature.
249
+ </Warning>
250
+
251
+ In addition to changing a tool's schema, advanced users can also modify its behavior. This is useful for adding validation logic, or for post-processing the tool's output.
252
+
253
+ The `from_tool()` method takes a `transform_fn` parameter, which is an async function that replaces the parent tool's logic and gives you complete control over the tool's execution.
254
+
255
+ ### The Transform Function
256
+
257
+ The `transform_fn` is an async function that **completely replaces** the parent tool's logic.
258
+
259
+ Critically, the transform function's arguments are used to determine the new tool's final schema. Any arguments that are not already present in the parent tool schema OR the `transform_args` will be added to the new tool's schema. Note that when `transform_args` and your function have the same argument name, the `transform_args` metadata will take precedence, if provided.
260
+
261
+ ```python
262
+ async def my_custom_logic(user_input: str, max_length: int = 100) -> str:
263
+ # Your custom logic here - this completely replaces the parent tool
264
+ return f"Custom result for: {user_input[:max_length]}"
265
+
266
+ Tool.from_tool(transform_fn=my_custom_logic)
267
+ ```
268
+
269
+ <Tip>
270
+ The name / docstring of the `transform_fn` are ignored. Only its arguments are used to determine the final schema.
271
+ </Tip>
272
+
273
+ ### Calling the Parent Tool
274
+
275
+ Most of the time, you don't want to completely replace the parent tool's behavior. Instead, you want to add validation, modify inputs, or post-process outputs while still leveraging the parent tool's core functionality. For this, FastMCP provides the special `forward()` and `forward_raw()` functions.
276
+
277
+ Both `forward()` and `forward_raw()` are async functions that let you call the parent tool from within your `transform_fn`:
278
+
279
+ - **`forward()`** (recommended): Automatically handles argument mapping based on your `ArgTransform` configurations. Call it with the transformed argument names.
280
+ - **`forward_raw()`**: Bypasses all transformation and calls the parent tool directly with its original argument names. This is rarely needed unless you're doing complex argument manipulation, perhaps without `arg_transforms`.
281
+
282
+ The most common transformation pattern is to validate (potentially renamed) arguments before calling the parent tool. Here's an example that validates that `x` and `y` are positive before calling the parent tool:
283
+ <Tabs>
284
+ <Tab title="Using forward()">
285
+
286
+ In the simplest case, your parent tool and your transform function have the same arguments. You can call `forward()` with the same argument names as the parent tool:
287
+
288
+ ```python {15}
289
+ from fastmcp import FastMCP
290
+ from fastmcp.tools import Tool
291
+ from fastmcp.tools.tool_transform import forward
292
+
293
+ mcp = FastMCP()
294
+
295
+ @mcp.tool
296
+ def add(x: int, y: int) -> int:
297
+ """Adds two numbers."""
298
+ return x + y
299
+
300
+ async def ensure_positive(x: int, y: int) -> int:
301
+ if x <= 0 or y <= 0:
302
+ raise ValueError("x and y must be positive")
303
+ return await forward(x=x, y=y)
304
+
305
+ new_tool = Tool.from_tool(
306
+ add,
307
+ transform_fn=ensure_positive,
308
+ )
309
+
310
+ mcp.add_tool(new_tool)
311
+ ```
312
+ </Tab>
313
+ <Tab title="Using forward() with renamed args">
314
+
315
+ When your transformed tool has different argument names than the parent tool, you can call `forward()` with the renamed arguments and it will automatically map the arguments to the parent tool's arguments:
316
+
317
+ ```python {15, 20-23}
318
+ from fastmcp import FastMCP
319
+ from fastmcp.tools import Tool
320
+ from fastmcp.tools.tool_transform import forward
321
+
322
+ mcp = FastMCP()
323
+
324
+ @mcp.tool
325
+ def add(x: int, y: int) -> int:
326
+ """Adds two numbers."""
327
+ return x + y
328
+
329
+ async def ensure_positive(a: int, b: int) -> int:
330
+ if a <= 0 or b <= 0:
331
+ raise ValueError("a and b must be positive")
332
+ return await forward(a=a, b=b)
333
+
334
+ new_tool = Tool.from_tool(
335
+ add,
336
+ transform_fn=ensure_positive,
337
+ transform_args={
338
+ "x": ArgTransform(name="a"),
339
+ "y": ArgTransform(name="b"),
340
+ }
341
+ )
342
+
343
+ mcp.add_tool(new_tool)
344
+ ```
345
+ </Tab>
346
+ <Tab title="Using forward_raw()">
347
+ Finally, you can use `forward_raw()` to bypass all argument mapping and call the parent tool directly with its original argument names.
348
+
349
+ ```python {15, 20-23}
350
+ from fastmcp import FastMCP
351
+ from fastmcp.tools import Tool
352
+ from fastmcp.tools.tool_transform import forward
353
+
354
+ mcp = FastMCP()
355
+
356
+ @mcp.tool
357
+ def add(x: int, y: int) -> int:
358
+ """Adds two numbers."""
359
+ return x + y
360
+
361
+ async def ensure_positive(a: int, b: int) -> int:
362
+ if a <= 0 or b <= 0:
363
+ raise ValueError("a and b must be positive")
364
+ return await forward_raw(x=a, y=b)
365
+
366
+ new_tool = Tool.from_tool(
367
+ add,
368
+ transform_fn=ensure_positive,
369
+ transform_args={
370
+ "x": ArgTransform(name="a"),
371
+ "y": ArgTransform(name="b"),
372
+ }
373
+ )
374
+
375
+ mcp.add_tool(new_tool)
376
+ ```
377
+ </Tab>
378
+ </Tabs>
379
+
380
+ ### Passing Arguments with **kwargs
381
+
382
+ If your `transform_fn` includes `**kwargs` in its signature, it will receive **all arguments from the parent tool after `ArgTransform` configurations have been applied**. This is powerful for creating flexible validation functions that don't require you to add every argument to the function signature.
383
+
384
+ In the following example, we wrap a parent tool that accepts two arguments `x` and `y`. These are renamed to `a` and `b` in the transformed tool, and the transform only validates `a`, passing the other argument through as `**kwargs`.
385
+
386
+ ```python {12, 15}
387
+ from fastmcp import FastMCP
388
+ from fastmcp.tools import Tool
389
+ from fastmcp.tools.tool_transform import forward
390
+
391
+ mcp = FastMCP()
392
+
393
+ @mcp.tool
394
+ def add(x: int, y: int) -> int:
395
+ """Adds two numbers."""
396
+ return x + y
397
+
398
+ async def ensure_a_positive(a: int, **kwargs) -> int:
399
+ if a <= 0:
400
+ raise ValueError("a must be positive")
401
+ return await forward(a=a, **kwargs)
402
+
403
+ new_tool = Tool.from_tool(
404
+ add,
405
+ transform_fn=ensure_a_positive,
406
+ transform_args={
407
+ "x": ArgTransform(name="a"),
408
+ "y": ArgTransform(name="b"),
409
+ }
410
+ )
411
+
412
+ mcp.add_tool(new_tool)
413
+ ```
414
+
415
+ <Tip>
416
+ In the above example, `**kwargs` receives the renamed argument `b`, not the original argument `y`. It is therefore recommended to use with `forward()`, not `forward_raw()`.
417
+ </Tip>
418
+
419
+ ## Common Patterns
420
+
421
+ Tool transformation is a flexible feature that supports many powerful patterns. Here are a few common use cases to give you ideas.
422
+
423
+ ### Adapting Remote or Generated Tools
424
+ This is one of the most common reasons to use tool transformation. Tools from remote servers (via a [proxy](/servers/proxy)) or generated from an [OpenAPI spec](/servers/openapi) are often too generic for direct use by an LLM. You can use transformation to create a simpler, more intuitive version for your specific needs.
425
+
426
+ ### Chaining Transformations
427
+ You can chain transformations by using an already transformed tool as the parent for a new transformation. This lets you build up complex behaviors in layers, for example, first renaming arguments, and then adding validation logic to the renamed tool.
428
+
429
+ ### Context-Aware Tool Factories
430
+ You can write functions that act as "factories," generating specialized versions of a tool for different contexts. For example, you could create a `get_my_data` tool that is specific to the currently logged-in user by hiding the `user_id` parameter and providing it automatically.
src/fastmcp/server/auth/providers/bearer_env.py CHANGED
@@ -1,13 +1,10 @@
 
 
1
  from pydantic_settings import BaseSettings, SettingsConfigDict
2
 
3
  from fastmcp.server.auth.providers.bearer import BearerAuthProvider
4
 
5
 
6
- # Sentinel object to indicate that a setting is not set
7
- class _NotSet:
8
- pass
9
-
10
-
11
  class EnvBearerAuthProviderSettings(BaseSettings):
12
  """Settings for the BearerAuthProvider."""
13
 
@@ -33,11 +30,11 @@ class EnvBearerAuthProvider(BearerAuthProvider):
33
 
34
  def __init__(
35
  self,
36
- public_key: str | None | type[_NotSet] = _NotSet,
37
- jwks_uri: str | None | type[_NotSet] = _NotSet,
38
- issuer: str | None | type[_NotSet] = _NotSet,
39
- audience: str | None | type[_NotSet] = _NotSet,
40
- required_scopes: list[str] | None | type[_NotSet] = _NotSet,
41
  ):
42
  """
43
  Initialize the provider.
@@ -57,6 +54,6 @@ class EnvBearerAuthProvider(BearerAuthProvider):
57
  "required_scopes": required_scopes,
58
  }
59
  settings = EnvBearerAuthProviderSettings(
60
- **{k: v for k, v in kwargs.items() if v is not _NotSet}
61
  )
62
  super().__init__(**settings.model_dump())
 
1
+ from types import EllipsisType
2
+
3
  from pydantic_settings import BaseSettings, SettingsConfigDict
4
 
5
  from fastmcp.server.auth.providers.bearer import BearerAuthProvider
6
 
7
 
 
 
 
 
 
8
  class EnvBearerAuthProviderSettings(BaseSettings):
9
  """Settings for the BearerAuthProvider."""
10
 
 
30
 
31
  def __init__(
32
  self,
33
+ public_key: str | None | EllipsisType = ...,
34
+ jwks_uri: str | None | EllipsisType = ...,
35
+ issuer: str | None | EllipsisType = ...,
36
+ audience: str | None | EllipsisType = ...,
37
+ required_scopes: list[str] | None | EllipsisType = ...,
38
  ):
39
  """
40
  Initialize the provider.
 
54
  "required_scopes": required_scopes,
55
  }
56
  settings = EnvBearerAuthProviderSettings(
57
+ **{k: v for k, v in kwargs.items() if v is not ...}
58
  )
59
  super().__init__(**settings.model_dump())
src/fastmcp/server/openapi.py CHANGED
@@ -226,7 +226,6 @@ class OpenAPITool(Tool):
226
  tags: set[str] = set(),
227
  timeout: float | None = None,
228
  annotations: ToolAnnotations | None = None,
229
- exclude_args: list[str] | None = None,
230
  serializer: Callable[[Any], str] | None = None,
231
  ):
232
  super().__init__(
@@ -235,7 +234,6 @@ class OpenAPITool(Tool):
235
  parameters=parameters,
236
  tags=tags,
237
  annotations=annotations,
238
- exclude_args=exclude_args,
239
  serializer=serializer,
240
  )
241
  self._client = client
 
226
  tags: set[str] = set(),
227
  timeout: float | None = None,
228
  annotations: ToolAnnotations | None = None,
 
229
  serializer: Callable[[Any], str] | None = None,
230
  ):
231
  super().__init__(
 
234
  parameters=parameters,
235
  tags=tags,
236
  annotations=annotations,
 
237
  serializer=serializer,
238
  )
239
  self._client = client
src/fastmcp/server/server.py CHANGED
@@ -268,6 +268,12 @@ class FastMCP(Generic[LifespanResultT]):
268
  self._cache.set("tools", tools)
269
  return tools
270
 
 
 
 
 
 
 
271
  async def get_resources(self) -> dict[str, Resource]:
272
  """Get all registered resources, indexed by registered key."""
273
  if (resources := self._cache.get("resources")) is self._cache.NOT_FOUND:
 
268
  self._cache.set("tools", tools)
269
  return tools
270
 
271
+ async def get_tool(self, key: str) -> Tool:
272
+ tools = await self.get_tools()
273
+ if key not in tools:
274
+ raise NotFoundError(f"Unknown tool: {key}")
275
+ return tools[key]
276
+
277
  async def get_resources(self) -> dict[str, Resource]:
278
  """Get all registered resources, indexed by registered key."""
279
  if (resources := self._cache.get("resources")) is self._cache.NOT_FOUND:
src/fastmcp/tools/__init__.py CHANGED
@@ -1,4 +1,5 @@
1
  from .tool import Tool, FunctionTool
2
  from .tool_manager import ToolManager
 
3
 
4
- __all__ = ["Tool", "ToolManager", "FunctionTool"]
 
1
  from .tool import Tool, FunctionTool
2
  from .tool_manager import ToolManager
3
+ from .tool_transform import forward, forward_raw
4
 
5
+ __all__ = ["Tool", "ToolManager", "FunctionTool", "forward", "forward_raw"]
src/fastmcp/tools/tool.py CHANGED
@@ -4,6 +4,7 @@ import inspect
4
  import json
5
  from abc import ABC, abstractmethod
6
  from collections.abc import Callable
 
7
  from typing import TYPE_CHECKING, Annotated, Any
8
 
9
  import pydantic_core
@@ -24,7 +25,7 @@ from fastmcp.utilities.types import (
24
  )
25
 
26
  if TYPE_CHECKING:
27
- pass
28
 
29
  logger = get_logger(__name__)
30
 
@@ -47,10 +48,6 @@ class Tool(FastMCPBaseModel, ABC):
47
  annotations: ToolAnnotations | None = Field(
48
  default=None, description="Additional annotations about the tool"
49
  )
50
- exclude_args: list[str] | None = Field(
51
- default=None,
52
- description="Arguments to exclude from the tool schema, such as State, Memory, or Credential",
53
- )
54
  serializer: Callable[[Any], str] | None = Field(
55
  default=None, description="Optional custom serializer for tool results"
56
  )
@@ -98,6 +95,31 @@ class Tool(FastMCPBaseModel, ABC):
98
  """Run the tool with arguments."""
99
  raise NotImplementedError("Subclasses must implement run()")
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  class FunctionTool(Tool):
103
  fn: Callable[..., Any]
@@ -114,62 +136,19 @@ class FunctionTool(Tool):
114
  serializer: Callable[[Any], str] | None = None,
115
  ) -> FunctionTool:
116
  """Create a Tool from a function."""
117
- from fastmcp.server.context import Context
118
-
119
- # Reject functions with *args or **kwargs
120
- sig = inspect.signature(fn)
121
- for param in sig.parameters.values():
122
- if param.kind == inspect.Parameter.VAR_POSITIONAL:
123
- raise ValueError("Functions with *args are not supported as tools")
124
- if param.kind == inspect.Parameter.VAR_KEYWORD:
125
- raise ValueError("Functions with **kwargs are not supported as tools")
126
-
127
- if exclude_args:
128
- for arg_name in exclude_args:
129
- if arg_name not in sig.parameters:
130
- raise ValueError(
131
- f"Parameter '{arg_name}' in exclude_args does not exist in function."
132
- )
133
- param = sig.parameters[arg_name]
134
- if param.default == inspect.Parameter.empty:
135
- raise ValueError(
136
- f"Parameter '{arg_name}' in exclude_args must have a default value."
137
- )
138
 
139
- func_name = name or getattr(fn, "__name__", None) or fn.__class__.__name__
140
 
141
- if func_name == "<lambda>":
142
  raise ValueError("You must provide a name for lambda functions")
143
 
144
- func_doc = description or fn.__doc__
145
-
146
- # if the fn is a callable class, we need to get the __call__ method from here out
147
- if not inspect.isroutine(fn):
148
- fn = fn.__call__
149
- # if the fn is a staticmethod, we need to work with the underlying function
150
- if isinstance(fn, staticmethod):
151
- fn = fn.__func__
152
-
153
- type_adapter = get_cached_typeadapter(fn)
154
- schema = type_adapter.json_schema()
155
-
156
- prune_params: list[str] = []
157
- context_kwarg = find_kwarg_by_type(fn, kwarg_type=Context)
158
- if context_kwarg:
159
- prune_params.append(context_kwarg)
160
- if exclude_args:
161
- prune_params.extend(exclude_args)
162
-
163
- schema = compress_schema(schema, prune_params=prune_params)
164
-
165
  return cls(
166
- fn=fn,
167
- name=func_name,
168
- description=func_doc,
169
- parameters=schema,
170
  tags=tags or set(),
171
  annotations=annotations,
172
- exclude_args=exclude_args,
173
  serializer=serializer,
174
  )
175
 
@@ -222,6 +201,76 @@ class FunctionTool(Tool):
222
  return _convert_to_content(result, serializer=self.serializer)
223
 
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  def _convert_to_content(
226
  result: Any,
227
  serializer: Callable[[Any], str] | None = None,
 
4
  import json
5
  from abc import ABC, abstractmethod
6
  from collections.abc import Callable
7
+ from dataclasses import dataclass
8
  from typing import TYPE_CHECKING, Annotated, Any
9
 
10
  import pydantic_core
 
25
  )
26
 
27
  if TYPE_CHECKING:
28
+ from fastmcp.tools.tool_transform import ArgTransform, TransformedTool
29
 
30
  logger = get_logger(__name__)
31
 
 
48
  annotations: ToolAnnotations | None = Field(
49
  default=None, description="Additional annotations about the tool"
50
  )
 
 
 
 
51
  serializer: Callable[[Any], str] | None = Field(
52
  default=None, description="Optional custom serializer for tool results"
53
  )
 
95
  """Run the tool with arguments."""
96
  raise NotImplementedError("Subclasses must implement run()")
97
 
98
+ @classmethod
99
+ def from_tool(
100
+ cls,
101
+ tool: Tool,
102
+ transform_fn: Callable[..., Any] | None = None,
103
+ name: str | None = None,
104
+ transform_args: dict[str, ArgTransform] | None = None,
105
+ description: str | None = None,
106
+ tags: set[str] | None = None,
107
+ annotations: ToolAnnotations | None = None,
108
+ serializer: Callable[[Any], str] | None = None,
109
+ ) -> TransformedTool:
110
+ from fastmcp.tools.tool_transform import TransformedTool
111
+
112
+ return TransformedTool.from_tool(
113
+ tool=tool,
114
+ transform_fn=transform_fn,
115
+ name=name,
116
+ transform_args=transform_args,
117
+ description=description,
118
+ tags=tags,
119
+ annotations=annotations,
120
+ serializer=serializer,
121
+ )
122
+
123
 
124
  class FunctionTool(Tool):
125
  fn: Callable[..., Any]
 
136
  serializer: Callable[[Any], str] | None = None,
137
  ) -> FunctionTool:
138
  """Create a Tool from a function."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
+ parsed_fn = ParsedFunction.from_function(fn, exclude_args=exclude_args)
141
 
142
+ if name is None and parsed_fn.name == "<lambda>":
143
  raise ValueError("You must provide a name for lambda functions")
144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  return cls(
146
+ fn=parsed_fn.fn,
147
+ name=name or parsed_fn.name,
148
+ description=description or parsed_fn.description,
149
+ parameters=parsed_fn.parameters,
150
  tags=tags or set(),
151
  annotations=annotations,
 
152
  serializer=serializer,
153
  )
154
 
 
201
  return _convert_to_content(result, serializer=self.serializer)
202
 
203
 
204
+ @dataclass
205
+ class ParsedFunction:
206
+ fn: Callable[..., Any]
207
+ name: str
208
+ description: str | None
209
+ parameters: dict[str, Any]
210
+
211
+ @classmethod
212
+ def from_function(
213
+ cls,
214
+ fn: Callable[..., Any],
215
+ exclude_args: list[str] | None = None,
216
+ validate: bool = True,
217
+ ) -> ParsedFunction:
218
+ from fastmcp.server.context import Context
219
+
220
+ if validate:
221
+ sig = inspect.signature(fn)
222
+ # Reject functions with *args or **kwargs
223
+ for param in sig.parameters.values():
224
+ if param.kind == inspect.Parameter.VAR_POSITIONAL:
225
+ raise ValueError("Functions with *args are not supported as tools")
226
+ if param.kind == inspect.Parameter.VAR_KEYWORD:
227
+ raise ValueError(
228
+ "Functions with **kwargs are not supported as tools"
229
+ )
230
+
231
+ # Reject exclude_args that don't exist in the function or don't have a default value
232
+ if exclude_args:
233
+ for arg_name in exclude_args:
234
+ if arg_name not in sig.parameters:
235
+ raise ValueError(
236
+ f"Parameter '{arg_name}' in exclude_args does not exist in function."
237
+ )
238
+ param = sig.parameters[arg_name]
239
+ if param.default == inspect.Parameter.empty:
240
+ raise ValueError(
241
+ f"Parameter '{arg_name}' in exclude_args must have a default value."
242
+ )
243
+
244
+ # collect name and doc before we potentially modify the function
245
+ fn_name = getattr(fn, "__name__", None) or fn.__class__.__name__
246
+ fn_doc = fn.__doc__
247
+
248
+ # if the fn is a callable class, we need to get the __call__ method from here out
249
+ if not inspect.isroutine(fn):
250
+ fn = fn.__call__
251
+ # if the fn is a staticmethod, we need to work with the underlying function
252
+ if isinstance(fn, staticmethod):
253
+ fn = fn.__func__
254
+
255
+ type_adapter = get_cached_typeadapter(fn)
256
+ schema = type_adapter.json_schema()
257
+
258
+ prune_params: list[str] = []
259
+ context_kwarg = find_kwarg_by_type(fn, kwarg_type=Context)
260
+ if context_kwarg:
261
+ prune_params.append(context_kwarg)
262
+ if exclude_args:
263
+ prune_params.extend(exclude_args)
264
+
265
+ schema = compress_schema(schema, prune_params=prune_params)
266
+ return cls(
267
+ fn=fn,
268
+ name=fn_name,
269
+ description=fn_doc,
270
+ parameters=schema,
271
+ )
272
+
273
+
274
  def _convert_to_content(
275
  result: Any,
276
  serializer: Callable[[Any], str] | None = None,
src/fastmcp/tools/tool_transform.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import Callable
5
+ from contextvars import ContextVar
6
+ from dataclasses import dataclass
7
+ from types import EllipsisType
8
+ from typing import Any, Literal
9
+
10
+ from mcp.types import EmbeddedResource, ImageContent, TextContent, ToolAnnotations
11
+ from pydantic import ConfigDict
12
+
13
+ from fastmcp.tools.tool import ParsedFunction, Tool
14
+ from fastmcp.utilities.logging import get_logger
15
+ from fastmcp.utilities.types import get_cached_typeadapter
16
+
17
+ logger = get_logger(__name__)
18
+
19
+ NotSet = ...
20
+
21
+
22
+ # Context variable to store current transformed tool
23
+ _current_tool: ContextVar[TransformedTool | None] = ContextVar(
24
+ "_current_tool", default=None
25
+ )
26
+
27
+
28
+ async def forward(**kwargs) -> Any:
29
+ """Forward to parent tool with argument transformation applied.
30
+
31
+ This function can only be called from within a transformed tool's custom
32
+ function. It applies argument transformation (renaming, validation) before
33
+ calling the parent tool.
34
+
35
+ For example, if the parent tool has args `x` and `y`, but the transformed
36
+ tool has args `a` and `b`, and an `transform_args` was provided that maps `x` to
37
+ `a` and `y` to `b`, then `forward(a=1, b=2)` will call the parent tool with
38
+ `x=1` and `y=2`.
39
+
40
+ Args:
41
+ **kwargs: Arguments to forward to the parent tool (using transformed names).
42
+
43
+ Returns:
44
+ The result from the parent tool execution.
45
+
46
+ Raises:
47
+ RuntimeError: If called outside a transformed tool context.
48
+ TypeError: If provided arguments don't match the transformed schema.
49
+ """
50
+ tool = _current_tool.get()
51
+ if tool is None:
52
+ raise RuntimeError("forward() can only be called within a transformed tool")
53
+
54
+ # Use the forwarding function that handles mapping
55
+ return await tool.forwarding_fn(**kwargs)
56
+
57
+
58
+ async def forward_raw(**kwargs) -> Any:
59
+ """Forward directly to parent tool without transformation.
60
+
61
+ This function bypasses all argument transformation and validation, calling the parent
62
+ tool directly with the provided arguments. Use this when you need to call the parent
63
+ with its original parameter names and structure.
64
+
65
+ For example, if the parent tool has args `x` and `y`, then `forward_raw(x=1,
66
+ y=2)` will call the parent tool with `x=1` and `y=2`.
67
+
68
+ Args:
69
+ **kwargs: Arguments to pass directly to the parent tool (using original names).
70
+
71
+ Returns:
72
+ The result from the parent tool execution.
73
+
74
+ Raises:
75
+ RuntimeError: If called outside a transformed tool context.
76
+ """
77
+ tool = _current_tool.get()
78
+ if tool is None:
79
+ raise RuntimeError("forward_raw() can only be called within a transformed tool")
80
+
81
+ return await tool.parent_tool.run(kwargs)
82
+
83
+
84
+ @dataclass(kw_only=True)
85
+ class ArgTransform:
86
+ """Configuration for transforming a parent tool's argument.
87
+
88
+ This class allows fine-grained control over how individual arguments are transformed
89
+ when creating a new tool from an existing one. You can rename arguments, change their
90
+ descriptions, add default values, or hide them from clients while passing constants.
91
+
92
+ Attributes:
93
+ name: New name for the argument. Use None to keep original name, or ... for no change.
94
+ description: New description for the argument. Use None to remove description, or ... for no change.
95
+ default: New default value for the argument. Use ... for no change.
96
+ default_factory: Callable that returns a default value. Cannot be used with default.
97
+ type: New type for the argument. Use ... for no change.
98
+ hide: If True, hide this argument from clients but pass a constant value to parent.
99
+ required: If True, make argument required (remove default). Use ... for no change.
100
+
101
+ Examples:
102
+ # Rename argument 'old_name' to 'new_name'
103
+ ArgTransform(name="new_name")
104
+
105
+ # Change description only
106
+ ArgTransform(description="Updated description")
107
+
108
+ # Add a default value (makes argument optional)
109
+ ArgTransform(default=42)
110
+
111
+ # Add a default factory (makes argument optional)
112
+ ArgTransform(default_factory=lambda: time.time())
113
+
114
+ # Change the type
115
+ ArgTransform(type=str)
116
+
117
+ # Hide the argument entirely from clients
118
+ ArgTransform(hide=True)
119
+
120
+ # Hide argument but pass a constant value to parent
121
+ ArgTransform(hide=True, default="constant_value")
122
+
123
+ # Hide argument but pass a factory-generated value to parent
124
+ ArgTransform(hide=True, default_factory=lambda: uuid.uuid4().hex)
125
+
126
+ # Make an optional parameter required (removes any default)
127
+ ArgTransform(required=True)
128
+
129
+ # Combine multiple transformations
130
+ ArgTransform(name="new_name", description="New desc", default=None, type=int)
131
+ """
132
+
133
+ name: str | EllipsisType = NotSet
134
+ description: str | EllipsisType = NotSet
135
+ default: Any | EllipsisType = NotSet
136
+ default_factory: Callable[[], Any] | EllipsisType = NotSet
137
+ type: Any | EllipsisType = NotSet
138
+ hide: bool = False
139
+ required: Literal[True] | EllipsisType = NotSet
140
+
141
+ def __post_init__(self):
142
+ """Validate that only one of default or default_factory is provided."""
143
+ has_default = self.default is not NotSet
144
+ has_factory = self.default_factory is not NotSet
145
+
146
+ if has_default and has_factory:
147
+ raise ValueError(
148
+ "Cannot specify both 'default' and 'default_factory' in ArgTransform. "
149
+ "Use either 'default' for a static value or 'default_factory' for a callable."
150
+ )
151
+
152
+ if has_factory and not self.hide:
153
+ raise ValueError(
154
+ "default_factory can only be used with hide=True. "
155
+ "Visible parameters must use static 'default' values since JSON schema "
156
+ "cannot represent dynamic factories."
157
+ )
158
+
159
+ if self.required is True and (has_default or has_factory):
160
+ raise ValueError(
161
+ "Cannot specify 'required=True' with 'default' or 'default_factory'. "
162
+ "Required parameters cannot have defaults."
163
+ )
164
+
165
+ if self.hide and self.required is True:
166
+ raise ValueError(
167
+ "Cannot specify both 'hide=True' and 'required=True'. "
168
+ "Hidden parameters cannot be required since clients cannot provide them."
169
+ )
170
+
171
+ if self.required is False:
172
+ raise ValueError(
173
+ "Cannot specify 'required=False'. Set a default value instead."
174
+ )
175
+
176
+
177
+ class TransformedTool(Tool):
178
+ """A tool that is transformed from another tool.
179
+
180
+ This class represents a tool that has been created by transforming another tool.
181
+ It supports argument renaming, schema modification, custom function injection,
182
+ and provides context for the forward() and forward_raw() functions.
183
+
184
+ The transformation can be purely schema-based (argument renaming, dropping, etc.)
185
+ or can include a custom function that uses forward() to call the parent tool
186
+ with transformed arguments.
187
+
188
+ Attributes:
189
+ parent_tool: The original tool that this tool was transformed from.
190
+ fn: The function to execute when this tool is called (either the forwarding
191
+ function for pure transformations or a custom user function).
192
+ forwarding_fn: Internal function that handles argument transformation and
193
+ validation when forward() is called from custom functions.
194
+ """
195
+
196
+ model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
197
+
198
+ parent_tool: Tool
199
+ fn: Callable[..., Any]
200
+ forwarding_fn: Callable[..., Any] # Always present, handles arg transformation
201
+ transform_args: dict[str, ArgTransform]
202
+
203
+ async def run(
204
+ self, arguments: dict[str, Any]
205
+ ) -> list[TextContent | ImageContent | EmbeddedResource]:
206
+ """Run the tool with context set for forward() functions.
207
+
208
+ This method executes the tool's function while setting up the context
209
+ that allows forward() and forward_raw() to work correctly within custom
210
+ functions.
211
+
212
+ Args:
213
+ arguments: Dictionary of arguments to pass to the tool's function.
214
+
215
+ Returns:
216
+ List of content objects (text, image, or embedded resources) representing
217
+ the tool's output.
218
+ """
219
+ from fastmcp.tools.tool import _convert_to_content
220
+
221
+ # Fill in missing arguments with schema defaults to ensure
222
+ # ArgTransform defaults take precedence over function defaults
223
+ arguments = arguments.copy()
224
+ properties = self.parameters.get("properties", {})
225
+
226
+ for param_name, param_schema in properties.items():
227
+ if param_name not in arguments and "default" in param_schema:
228
+ # Check if this parameter has a default_factory from transform_args
229
+ # We need to call the factory for each run, not use the cached schema value
230
+ has_factory_default = False
231
+ if self.transform_args:
232
+ # Find the original parameter name that maps to this param_name
233
+ for orig_name, transform in self.transform_args.items():
234
+ transform_name = (
235
+ transform.name
236
+ if transform.name is not NotSet
237
+ else orig_name
238
+ )
239
+ if (
240
+ transform_name == param_name
241
+ and transform.default_factory is not NotSet
242
+ ):
243
+ # Type check to ensure default_factory is callable
244
+ if callable(transform.default_factory):
245
+ arguments[param_name] = transform.default_factory()
246
+ has_factory_default = True
247
+ break
248
+
249
+ if not has_factory_default:
250
+ arguments[param_name] = param_schema["default"]
251
+
252
+ token = _current_tool.set(self)
253
+ try:
254
+ result = await self.fn(**arguments)
255
+ return _convert_to_content(result, serializer=self.serializer)
256
+ finally:
257
+ _current_tool.reset(token)
258
+
259
+ @classmethod
260
+ def from_tool(
261
+ cls,
262
+ tool: Tool,
263
+ name: str | None = None,
264
+ description: str | None = None,
265
+ tags: set[str] | None = None,
266
+ transform_fn: Callable[..., Any] | None = None,
267
+ transform_args: dict[str, ArgTransform] | None = None,
268
+ annotations: ToolAnnotations | None = None,
269
+ serializer: Callable[[Any], str] | None = None,
270
+ ) -> TransformedTool:
271
+ """Create a transformed tool from a parent tool.
272
+
273
+ Args:
274
+ tool: The parent tool to transform.
275
+ transform_fn: Optional custom function. Can use forward() and forward_raw()
276
+ to call the parent tool. Functions with **kwargs receive transformed
277
+ argument names.
278
+ name: New name for the tool. Defaults to parent tool's name.
279
+ transform_args: Optional transformations for parent tool arguments.
280
+ Only specified arguments are transformed, others pass through unchanged:
281
+ - str: Simple rename
282
+ - ArgTransform: Complex transformation (rename/description/default/drop)
283
+ - None: Drop the argument
284
+ description: New description. Defaults to parent's description.
285
+ tags: New tags. Defaults to parent's tags.
286
+ annotations: New annotations. Defaults to parent's annotations.
287
+ serializer: New serializer. Defaults to parent's serializer.
288
+
289
+ Returns:
290
+ TransformedTool with the specified transformations.
291
+
292
+ Examples:
293
+ # Transform specific arguments only
294
+ Tool.from_tool(parent, transform_args={"old": "new"}) # Others unchanged
295
+
296
+ # Custom function with partial transforms
297
+ async def custom(x: int, y: int) -> str:
298
+ result = await forward(x=x, y=y)
299
+ return f"Custom: {result}"
300
+
301
+ Tool.from_tool(parent, transform_fn=custom, transform_args={"a": "x", "b": "y"})
302
+
303
+ # Using **kwargs (gets all args, transformed and untransformed)
304
+ async def flexible(**kwargs) -> str:
305
+ result = await forward(**kwargs)
306
+ return f"Got: {kwargs}"
307
+
308
+ Tool.from_tool(parent, transform_fn=flexible, transform_args={"a": "x"})
309
+ """
310
+ transform_args = transform_args or {}
311
+
312
+ # Validate transform_args
313
+ parent_params = set(tool.parameters.get("properties", {}).keys())
314
+ unknown_args = set(transform_args.keys()) - parent_params
315
+ if unknown_args:
316
+ raise ValueError(
317
+ f"Unknown arguments in transform_args: {', '.join(sorted(unknown_args))}. "
318
+ f"Parent tool has: {', '.join(sorted(parent_params))}"
319
+ )
320
+
321
+ # Always create the forwarding transform
322
+ schema, forwarding_fn = cls._create_forwarding_transform(tool, transform_args)
323
+
324
+ if transform_fn is None:
325
+ # User wants pure transformation - use forwarding_fn as the main function
326
+ final_fn = forwarding_fn
327
+ final_schema = schema
328
+ else:
329
+ # User provided custom function - merge schemas
330
+ parsed_fn = ParsedFunction.from_function(transform_fn, validate=False)
331
+ final_fn = transform_fn
332
+
333
+ has_kwargs = cls._function_has_kwargs(transform_fn)
334
+
335
+ # Validate function parameters against transformed schema
336
+ fn_params = set(parsed_fn.parameters.get("properties", {}).keys())
337
+ transformed_params = set(schema.get("properties", {}).keys())
338
+
339
+ if not has_kwargs:
340
+ # Without **kwargs, function must declare all transformed params
341
+ # Check if function is missing any parameters required after transformation
342
+ missing_params = transformed_params - fn_params
343
+ if missing_params:
344
+ raise ValueError(
345
+ f"Function missing parameters required after transformation: "
346
+ f"{', '.join(sorted(missing_params))}. "
347
+ f"Function declares: {', '.join(sorted(fn_params))}"
348
+ )
349
+
350
+ # ArgTransform takes precedence over function signature
351
+ # Start with function schema as base, then override with transformed schema
352
+ final_schema = cls._merge_schema_with_precedence(
353
+ parsed_fn.parameters, schema
354
+ )
355
+ else:
356
+ # With **kwargs, function can access all transformed params
357
+ # ArgTransform takes precedence over function signature
358
+ # No validation needed - kwargs makes everything accessible
359
+
360
+ # Start with function schema as base, then override with transformed schema
361
+ final_schema = cls._merge_schema_with_precedence(
362
+ parsed_fn.parameters, schema
363
+ )
364
+
365
+ # Additional validation: check for naming conflicts after transformation
366
+ if transform_args:
367
+ new_names = []
368
+ for old_name, transform in transform_args.items():
369
+ if not transform.hide:
370
+ if transform.name is not NotSet:
371
+ new_names.append(transform.name)
372
+ else:
373
+ new_names.append(old_name)
374
+
375
+ # Check for duplicate names after transformation
376
+ name_counts = {}
377
+ for arg_name in new_names:
378
+ name_counts[arg_name] = name_counts.get(arg_name, 0) + 1
379
+
380
+ duplicates = [
381
+ arg_name for arg_name, count in name_counts.items() if count > 1
382
+ ]
383
+ if duplicates:
384
+ raise ValueError(
385
+ f"Multiple arguments would be mapped to the same names: "
386
+ f"{', '.join(sorted(duplicates))}"
387
+ )
388
+
389
+ final_description = description if description is not None else tool.description
390
+
391
+ transformed_tool = cls(
392
+ fn=final_fn,
393
+ forwarding_fn=forwarding_fn,
394
+ parent_tool=tool,
395
+ name=name or tool.name,
396
+ description=final_description,
397
+ parameters=final_schema,
398
+ tags=tags or tool.tags,
399
+ annotations=annotations or tool.annotations,
400
+ serializer=serializer or tool.serializer,
401
+ transform_args=transform_args,
402
+ )
403
+
404
+ return transformed_tool
405
+
406
+ @classmethod
407
+ def _create_forwarding_transform(
408
+ cls,
409
+ parent_tool: Tool,
410
+ transform_args: dict[str, ArgTransform] | None,
411
+ ) -> tuple[dict[str, Any], Callable[..., Any]]:
412
+ """Create schema and forwarding function that encapsulates all transformation logic.
413
+
414
+ This method builds a new JSON schema for the transformed tool and creates a
415
+ forwarding function that validates arguments against the new schema and maps
416
+ them back to the parent tool's expected arguments.
417
+
418
+ Args:
419
+ parent_tool: The original tool to transform.
420
+ transform_args: Dictionary defining how to transform each argument.
421
+
422
+ Returns:
423
+ A tuple containing:
424
+ - dict: The new JSON schema for the transformed tool
425
+ - Callable: Async function that validates and forwards calls to the parent tool
426
+ """
427
+
428
+ # Build transformed schema and mapping
429
+ parent_props = parent_tool.parameters.get("properties", {}).copy()
430
+ parent_required = set(parent_tool.parameters.get("required", []))
431
+
432
+ new_props = {}
433
+ new_required = set()
434
+ new_to_old = {}
435
+ hidden_defaults = {} # Track hidden parameters with constant values
436
+
437
+ for old_name, old_schema in parent_props.items():
438
+ # Check if parameter is in transform_args
439
+ if transform_args and old_name in transform_args:
440
+ transform = transform_args[old_name]
441
+ else:
442
+ # Default behavior - pass through (no transformation)
443
+ transform = ArgTransform() # Default ArgTransform with no changes
444
+
445
+ # Handle hidden parameters with defaults
446
+ if transform.hide:
447
+ # Validate that hidden parameters without user defaults have parent defaults
448
+ has_user_default = (
449
+ transform.default is not NotSet
450
+ or transform.default_factory is not NotSet
451
+ )
452
+ if not has_user_default and old_name in parent_required:
453
+ raise ValueError(
454
+ f"Hidden parameter '{old_name}' has no default value in parent tool "
455
+ f"and no default or default_factory provided in ArgTransform. Either provide a default "
456
+ f"or default_factory in ArgTransform or don't hide required parameters."
457
+ )
458
+ if has_user_default:
459
+ # Store info for later factory calling or direct value
460
+ hidden_defaults[old_name] = transform
461
+ # Skip adding to schema (not exposed to clients)
462
+ continue
463
+
464
+ transform_result = cls._apply_single_transform(
465
+ old_name,
466
+ old_schema,
467
+ transform,
468
+ old_name in parent_required,
469
+ )
470
+
471
+ if transform_result:
472
+ new_name, new_schema, is_required = transform_result
473
+ new_props[new_name] = new_schema
474
+ new_to_old[new_name] = old_name
475
+ if is_required:
476
+ new_required.add(new_name)
477
+
478
+ schema = {
479
+ "type": "object",
480
+ "properties": new_props,
481
+ "required": list(new_required),
482
+ }
483
+
484
+ # Create forwarding function that closes over everything it needs
485
+ async def _forward(**kwargs):
486
+ # Validate arguments
487
+ valid_args = set(new_props.keys())
488
+ provided_args = set(kwargs.keys())
489
+ unknown_args = provided_args - valid_args
490
+
491
+ if unknown_args:
492
+ raise TypeError(
493
+ f"Got unexpected keyword argument(s): {', '.join(sorted(unknown_args))}"
494
+ )
495
+
496
+ # Check required arguments
497
+ missing_args = new_required - provided_args
498
+ if missing_args:
499
+ raise TypeError(
500
+ f"Missing required argument(s): {', '.join(sorted(missing_args))}"
501
+ )
502
+
503
+ # Map arguments to parent names
504
+ parent_args = {}
505
+ for new_name, value in kwargs.items():
506
+ old_name = new_to_old.get(new_name, new_name)
507
+ parent_args[old_name] = value
508
+
509
+ # Add hidden defaults (constant values for hidden parameters)
510
+ for old_name, transform in hidden_defaults.items():
511
+ if transform.default is not NotSet:
512
+ parent_args[old_name] = transform.default
513
+ elif transform.default_factory is not NotSet:
514
+ # Type check to ensure default_factory is callable
515
+ if callable(transform.default_factory):
516
+ parent_args[old_name] = transform.default_factory()
517
+
518
+ return await parent_tool.run(parent_args)
519
+
520
+ return schema, _forward
521
+
522
+ @staticmethod
523
+ def _apply_single_transform(
524
+ old_name: str,
525
+ old_schema: dict[str, Any],
526
+ transform: ArgTransform,
527
+ is_required: bool,
528
+ ) -> tuple[str, dict[str, Any], bool] | None:
529
+ """Apply transformation to a single parameter.
530
+
531
+ This method handles the transformation of a single argument according to
532
+ the specified transformation rules.
533
+
534
+ Args:
535
+ old_name: Original name of the parameter.
536
+ old_schema: Original JSON schema for the parameter.
537
+ transform: ArgTransform object specifying how to transform the parameter.
538
+ is_required: Whether the original parameter was required.
539
+
540
+ Returns:
541
+ Tuple of (new_name, new_schema, new_is_required) if parameter should be kept,
542
+ None if parameter should be dropped.
543
+ """
544
+ if transform.hide:
545
+ return None
546
+
547
+ # Handle name transformation - ensure we always have a string
548
+ if transform.name is not NotSet:
549
+ new_name = transform.name if transform.name is not None else old_name
550
+ else:
551
+ new_name = old_name
552
+
553
+ # Ensure new_name is always a string
554
+ if not isinstance(new_name, str):
555
+ new_name = old_name
556
+
557
+ new_schema = old_schema.copy()
558
+
559
+ # Handle description transformation
560
+ if transform.description is not NotSet:
561
+ if transform.description is None:
562
+ new_schema.pop("description", None) # Remove description
563
+ else:
564
+ new_schema["description"] = transform.description
565
+
566
+ # Handle required transformation first
567
+ if transform.required is not NotSet:
568
+ is_required = bool(transform.required)
569
+ if transform.required is True:
570
+ # Remove any existing default when making required
571
+ new_schema.pop("default", None)
572
+
573
+ # Handle default value transformation (only if not making required)
574
+ if transform.default is not NotSet and transform.required is not True:
575
+ new_schema["default"] = transform.default
576
+ is_required = False
577
+
578
+ # Handle type transformation
579
+ if transform.type is not NotSet:
580
+ # Use TypeAdapter to get proper JSON schema for the type
581
+ type_schema = get_cached_typeadapter(transform.type).json_schema()
582
+ # Update the schema with the type information from TypeAdapter
583
+ new_schema.update(type_schema)
584
+
585
+ return new_name, new_schema, is_required
586
+
587
+ @staticmethod
588
+ def _merge_schema_with_precedence(
589
+ base_schema: dict[str, Any], override_schema: dict[str, Any]
590
+ ) -> dict[str, Any]:
591
+ """Merge two schemas, with the override schema taking precedence.
592
+
593
+ Args:
594
+ base_schema: Base schema to start with
595
+ override_schema: Schema that takes precedence for overlapping properties
596
+
597
+ Returns:
598
+ Merged schema with override taking precedence
599
+ """
600
+ merged_props = base_schema.get("properties", {}).copy()
601
+ merged_required = set(base_schema.get("required", []))
602
+
603
+ override_props = override_schema.get("properties", {})
604
+ override_required = set(override_schema.get("required", []))
605
+
606
+ # Override properties
607
+ for param_name, param_schema in override_props.items():
608
+ if param_name in merged_props:
609
+ # Merge the schemas, with override taking precedence
610
+ base_param = merged_props[param_name].copy()
611
+ base_param.update(param_schema)
612
+ merged_props[param_name] = base_param
613
+ else:
614
+ merged_props[param_name] = param_schema.copy()
615
+
616
+ # Handle required parameters - override takes complete precedence
617
+ # Start with override's required set
618
+ final_required = override_required.copy()
619
+
620
+ # For parameters not in override, inherit base requirement status
621
+ # but only if they don't have a default in the final merged properties
622
+ for param_name in merged_required:
623
+ if param_name not in override_props:
624
+ # Parameter not mentioned in override, keep base requirement status
625
+ final_required.add(param_name)
626
+ elif (
627
+ param_name in override_props
628
+ and "default" not in merged_props[param_name]
629
+ ):
630
+ # Parameter in override but no default, keep required if it was required in base
631
+ if param_name not in override_required:
632
+ # Override doesn't specify it as required, and it has no default,
633
+ # so inherit from base
634
+ final_required.add(param_name)
635
+
636
+ # Remove any parameters that have defaults (they become optional)
637
+ for param_name, param_schema in merged_props.items():
638
+ if "default" in param_schema:
639
+ final_required.discard(param_name)
640
+
641
+ return {
642
+ "type": "object",
643
+ "properties": merged_props,
644
+ "required": list(final_required),
645
+ }
646
+
647
+ @staticmethod
648
+ def _function_has_kwargs(fn: Callable[..., Any]) -> bool:
649
+ """Check if function accepts **kwargs.
650
+
651
+ This determines whether a custom function can accept arbitrary keyword arguments,
652
+ which affects how schemas are merged during tool transformation.
653
+
654
+ Args:
655
+ fn: Function to inspect.
656
+
657
+ Returns:
658
+ True if the function has a **kwargs parameter, False otherwise.
659
+ """
660
+ sig = inspect.signature(fn)
661
+ return any(
662
+ p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()
663
+ )
tests/server/test_tool_exclude_args.py CHANGED
@@ -21,9 +21,7 @@ async def test_tool_exclude_args_in_tool_manager():
21
 
22
  tools = mcp._tool_manager.list_tools()
23
  assert len(tools) == 1
24
- assert tools[0].exclude_args is not None
25
- for args in tools[0].exclude_args:
26
- assert args not in tools[0].parameters
27
 
28
 
29
  async def test_tool_exclude_args_without_default_value_raises_error():
@@ -64,10 +62,7 @@ async def test_add_tool_method_exclude_args():
64
  # Check internal tool objects directly
65
  tools = mcp._tool_manager.list_tools()
66
  assert len(tools) == 1
67
- assert tools[0].exclude_args is not None
68
- assert tools[0].exclude_args == ["state"]
69
- for args in tools[0].exclude_args:
70
- assert args not in tools[0].parameters
71
 
72
 
73
  async def test_tool_functionality_with_exclude_args():
 
21
 
22
  tools = mcp._tool_manager.list_tools()
23
  assert len(tools) == 1
24
+ assert "state" not in echo.parameters["properties"]
 
 
25
 
26
 
27
  async def test_tool_exclude_args_without_default_value_raises_error():
 
62
  # Check internal tool objects directly
63
  tools = mcp._tool_manager.list_tools()
64
  assert len(tools) == 1
65
+ assert "state" not in tools[0].parameters["properties"]
 
 
 
66
 
67
 
68
  async def test_tool_functionality_with_exclude_args():
tests/tools/test_tool_transform.py ADDED
@@ -0,0 +1,944 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from dataclasses import dataclass
3
+ from typing import Annotated, Any
4
+
5
+ import pytest
6
+ from dirty_equals import IsList
7
+ from pydantic import BaseModel, Field
8
+ from typing_extensions import TypedDict
9
+
10
+ from fastmcp import FastMCP
11
+ from fastmcp.client.client import Client
12
+ from fastmcp.tools import Tool, forward, forward_raw
13
+ from fastmcp.tools.tool import FunctionTool
14
+ from fastmcp.tools.tool_transform import ArgTransform, TransformedTool
15
+
16
+
17
+ def get_property(tool: Tool, name: str) -> dict[str, Any]:
18
+ return tool.parameters["properties"][name]
19
+
20
+
21
+ @pytest.fixture
22
+ def add_tool() -> FunctionTool:
23
+ def add(
24
+ old_x: Annotated[int, Field(description="old_x description")], old_y: int = 10
25
+ ) -> int:
26
+ print("running!")
27
+ return old_x + old_y
28
+
29
+ return Tool.from_function(add)
30
+
31
+
32
+ def test_tool_from_tool_no_change(add_tool):
33
+ new_tool = Tool.from_tool(add_tool)
34
+ assert isinstance(new_tool, TransformedTool)
35
+ assert new_tool.parameters == add_tool.parameters
36
+ assert new_tool.name == add_tool.name
37
+ assert new_tool.description == add_tool.description
38
+
39
+
40
+ async def test_renamed_arg_description_is_maintained(add_tool):
41
+ new_tool = Tool.from_tool(
42
+ add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
43
+ )
44
+ assert (
45
+ new_tool.parameters["properties"]["new_x"]["description"] == "old_x description"
46
+ )
47
+
48
+
49
+ async def test_tool_defaults_are_maintained_on_unmapped_args(add_tool):
50
+ new_tool = Tool.from_tool(
51
+ add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
52
+ )
53
+ result = await new_tool.run(arguments={"new_x": 1})
54
+ assert result[0].text == "11" # type: ignore
55
+
56
+
57
+ async def test_tool_defaults_are_maintained_on_mapped_args(add_tool):
58
+ new_tool = Tool.from_tool(
59
+ add_tool, transform_args={"old_y": ArgTransform(name="new_y")}
60
+ )
61
+ result = await new_tool.run(arguments={"old_x": 1})
62
+ assert result[0].text == "11" # type: ignore
63
+
64
+
65
+ def test_tool_change_arg_name(add_tool):
66
+ new_tool = Tool.from_tool(
67
+ add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
68
+ )
69
+
70
+ assert sorted(new_tool.parameters["properties"]) == ["new_x", "old_y"]
71
+ assert get_property(new_tool, "new_x") == get_property(add_tool, "old_x")
72
+ assert get_property(new_tool, "old_y") == get_property(add_tool, "old_y")
73
+ assert new_tool.parameters["required"] == ["new_x"]
74
+
75
+
76
+ def test_tool_change_arg_description(add_tool):
77
+ new_tool = Tool.from_tool(
78
+ add_tool, transform_args={"old_x": ArgTransform(description="new description")}
79
+ )
80
+ assert get_property(new_tool, "old_x")["description"] == "new description"
81
+
82
+
83
+ async def test_tool_drop_arg(add_tool):
84
+ new_tool = Tool.from_tool(
85
+ add_tool, transform_args={"old_y": ArgTransform(hide=True)}
86
+ )
87
+ assert sorted(new_tool.parameters["properties"]) == ["old_x"]
88
+ result = await new_tool.run(arguments={"old_x": 1})
89
+ assert result[0].text == "11" # type: ignore
90
+
91
+
92
+ async def test_dropped_args_error_if_provided(add_tool):
93
+ new_tool = Tool.from_tool(
94
+ add_tool, transform_args={"old_y": ArgTransform(hide=True)}
95
+ )
96
+ with pytest.raises(
97
+ TypeError, match="Got unexpected keyword argument\\(s\\): old_y"
98
+ ):
99
+ await new_tool.run(arguments={"old_x": 1, "old_y": 2})
100
+
101
+
102
+ async def test_hidden_arg_with_constant_default(add_tool):
103
+ """Test that hidden argument with default value passes constant to parent."""
104
+ new_tool = Tool.from_tool(
105
+ add_tool, transform_args={"old_y": ArgTransform(hide=True, default=20)}
106
+ )
107
+ # Only old_x should be exposed
108
+ assert sorted(new_tool.parameters["properties"]) == ["old_x"]
109
+ # Should pass old_x=5 and old_y=20 to parent
110
+ result = await new_tool.run(arguments={"old_x": 5})
111
+ assert result[0].text == "25" # type: ignore
112
+
113
+
114
+ async def test_hidden_arg_without_default_uses_parent_default(add_tool):
115
+ """Test that hidden argument without default uses parent's default."""
116
+ new_tool = Tool.from_tool(
117
+ add_tool, transform_args={"old_y": ArgTransform(hide=True)}
118
+ )
119
+ # Only old_x should be exposed
120
+ assert sorted(new_tool.parameters["properties"]) == ["old_x"]
121
+ # Should pass old_x=3 and let parent use its default old_y=10
122
+ result = await new_tool.run(arguments={"old_x": 3})
123
+ assert result[0].text == "13" # type: ignore
124
+
125
+
126
+ async def test_mixed_hidden_args_with_custom_function(add_tool):
127
+ """Test custom function with both hidden constant and hidden default parameters."""
128
+
129
+ async def custom_fn(visible_x: int) -> int:
130
+ # This custom function should receive the transformed visible parameter
131
+ # and the hidden parameters should be automatically handled
132
+ result = await forward(visible_x=visible_x)
133
+ return result
134
+
135
+ new_tool = Tool.from_tool(
136
+ add_tool,
137
+ transform_fn=custom_fn,
138
+ transform_args={
139
+ "old_x": ArgTransform(name="visible_x"), # Rename and expose
140
+ "old_y": ArgTransform(hide=True, default=25), # Hidden with constant
141
+ },
142
+ )
143
+
144
+ # Only visible_x should be exposed
145
+ assert sorted(new_tool.parameters["properties"]) == ["visible_x"]
146
+ # Should pass visible_x=7 as old_x=7 and old_y=25 to parent
147
+ result = await new_tool.run(arguments={"visible_x": 7})
148
+ assert result[0].text == "32" # type: ignore
149
+
150
+
151
+ async def test_hide_required_param_without_default_raises_error():
152
+ """Test that hiding a required parameter without providing default raises error."""
153
+
154
+ @Tool.from_function
155
+ def tool_with_required_param(required_param: int, optional_param: int = 10) -> int:
156
+ return required_param + optional_param
157
+
158
+ # This should raise an error because required_param has no default and we're not providing one
159
+ with pytest.raises(
160
+ ValueError,
161
+ match=r"Hidden parameter 'required_param' has no default value in parent tool",
162
+ ):
163
+ Tool.from_tool(
164
+ tool_with_required_param,
165
+ transform_args={"required_param": ArgTransform(hide=True)},
166
+ )
167
+
168
+
169
+ async def test_hide_required_param_with_user_default_works():
170
+ """Test that hiding a required parameter works when user provides a default."""
171
+
172
+ @Tool.from_function
173
+ def tool_with_required_param(required_param: int, optional_param: int = 10) -> int:
174
+ return required_param + optional_param
175
+
176
+ # This should work because we're providing a default for the hidden required param
177
+ new_tool = Tool.from_tool(
178
+ tool_with_required_param,
179
+ transform_args={"required_param": ArgTransform(hide=True, default=5)},
180
+ )
181
+
182
+ # Only optional_param should be exposed
183
+ assert sorted(new_tool.parameters["properties"]) == ["optional_param"]
184
+ # Should pass required_param=5 and optional_param=20 to parent
185
+ result = await new_tool.run(arguments={"optional_param": 20})
186
+ assert result[0].text == "25" # type: ignore
187
+
188
+
189
+ async def test_forward_with_argument_mapping(add_tool):
190
+ """Test that forward() applies argument mapping correctly."""
191
+
192
+ async def custom_fn(new_x: int, new_y: int = 5) -> int:
193
+ return await forward(new_x=new_x, new_y=new_y)
194
+
195
+ new_tool = Tool.from_tool(
196
+ add_tool,
197
+ transform_fn=custom_fn,
198
+ transform_args={
199
+ "old_x": ArgTransform(name="new_x"),
200
+ "old_y": ArgTransform(name="new_y"),
201
+ },
202
+ )
203
+
204
+ result = await new_tool.run(arguments={"new_x": 2, "new_y": 3})
205
+ assert result[0].text == "5" # type: ignore
206
+
207
+
208
+ async def test_forward_with_incorrect_args_raises_error(add_tool):
209
+ async def custom_fn(new_x: int, new_y: int = 5) -> int:
210
+ # the forward should use the new args, not the old ones
211
+ return await forward(old_x=new_x, old_y=new_y)
212
+
213
+ new_tool = Tool.from_tool(
214
+ add_tool,
215
+ transform_fn=custom_fn,
216
+ transform_args={
217
+ "old_x": ArgTransform(name="new_x"),
218
+ "old_y": ArgTransform(name="new_y"),
219
+ },
220
+ )
221
+ with pytest.raises(
222
+ TypeError, match=re.escape("Got unexpected keyword argument(s): old_x, old_y")
223
+ ):
224
+ await new_tool.run(arguments={"new_x": 2, "new_y": 3})
225
+
226
+
227
+ async def test_forward_raw_without_argument_mapping(add_tool):
228
+ """Test that forward_raw() calls parent directly without mapping."""
229
+
230
+ async def custom_fn(new_x: int, new_y: int = 5) -> int:
231
+ # Call parent directly with original argument names
232
+ result = await forward_raw(old_x=new_x, old_y=new_y)
233
+ return result
234
+
235
+ new_tool = Tool.from_tool(
236
+ add_tool,
237
+ transform_fn=custom_fn,
238
+ transform_args={
239
+ "old_x": ArgTransform(name="new_x"),
240
+ "old_y": ArgTransform(name="new_y"),
241
+ },
242
+ )
243
+
244
+ result = await new_tool.run(arguments={"new_x": 2, "new_y": 3})
245
+ assert result[0].text == "5" # type: ignore
246
+
247
+
248
+ async def test_custom_fn_with_kwargs_and_no_transform_args(add_tool):
249
+ async def custom_fn(extra: int, **kwargs) -> int:
250
+ sum = await forward(**kwargs)
251
+ return int(sum[0].text) + extra # type: ignore[attr-defined]
252
+
253
+ new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)
254
+ result = await new_tool.run(arguments={"extra": 1, "old_x": 2, "old_y": 3})
255
+ assert result[0].text == "6" # type: ignore
256
+ assert new_tool.parameters["required"] == IsList(
257
+ "extra", "old_x", check_order=False
258
+ )
259
+ assert list(new_tool.parameters["properties"]) == IsList(
260
+ "extra", "old_x", "old_y", check_order=False
261
+ )
262
+
263
+
264
+ async def test_fn_with_kwargs_passes_through_original_args(add_tool):
265
+ async def custom_fn(new_y: int = 5, **kwargs) -> int:
266
+ assert kwargs == {"old_y": 3}
267
+ result = await forward(old_x=new_y, **kwargs)
268
+ return result
269
+
270
+ new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)
271
+ result = await new_tool.run(arguments={"new_y": 2, "old_y": 3})
272
+ assert result[0].text == "5" # type: ignore
273
+
274
+
275
+ async def test_fn_with_kwargs_receives_transformed_arg_names(add_tool):
276
+ """Test that **kwargs receives arguments with their transformed names from transform_args."""
277
+
278
+ async def custom_fn(new_x: int, **kwargs) -> int:
279
+ # kwargs should contain 'old_y': 3 (transformed name), not 'old_y': 3 (original name)
280
+ assert kwargs == {"old_y": 3}
281
+ result = await forward(new_x=new_x, **kwargs)
282
+ return result
283
+
284
+ new_tool = Tool.from_tool(
285
+ add_tool,
286
+ transform_fn=custom_fn,
287
+ transform_args={"old_x": ArgTransform(name="new_x")},
288
+ )
289
+ result = await new_tool.run(arguments={"new_x": 2, "old_y": 3})
290
+ assert result[0].text == "5" # type: ignore
291
+
292
+
293
+ async def test_fn_with_kwargs_handles_partial_explicit_args(add_tool):
294
+ """Test that function can explicitly handle some transformed args while others pass through kwargs."""
295
+
296
+ async def custom_fn(new_x: int, some_other_param: str = "default", **kwargs) -> int:
297
+ # x is explicitly handled, y should come through kwargs with transformed name
298
+ assert kwargs == {"old_y": 7}
299
+ result = await forward(new_x=new_x, **kwargs)
300
+ return result
301
+
302
+ new_tool = Tool.from_tool(
303
+ add_tool,
304
+ transform_fn=custom_fn,
305
+ transform_args={"old_x": ArgTransform(name="new_x")},
306
+ )
307
+ result = await new_tool.run(
308
+ arguments={"new_x": 3, "old_y": 7, "some_other_param": "test"}
309
+ )
310
+ assert result[0].text == "10" # type: ignore
311
+
312
+
313
+ async def test_fn_with_kwargs_mixed_mapped_and_unmapped_args(add_tool):
314
+ """Test **kwargs behavior with mix of mapped and unmapped arguments."""
315
+
316
+ async def custom_fn(new_x: int, **kwargs) -> int:
317
+ # new_x is explicitly handled, old_y should pass through kwargs with original name (unmapped)
318
+ assert kwargs == {"old_y": 5}
319
+ result = await forward(new_x=new_x, **kwargs)
320
+ return result
321
+
322
+ new_tool = Tool.from_tool(
323
+ add_tool,
324
+ transform_fn=custom_fn,
325
+ transform_args={"old_x": ArgTransform(name="new_x")},
326
+ ) # only map 'a'
327
+ result = await new_tool.run(arguments={"new_x": 1, "old_y": 5})
328
+ assert result[0].text == "6" # type: ignore
329
+
330
+
331
+ async def test_fn_with_kwargs_dropped_args_not_in_kwargs(add_tool):
332
+ """Test that dropped arguments don't appear in **kwargs."""
333
+
334
+ async def custom_fn(new_x: int, **kwargs) -> int:
335
+ # 'b' was dropped, so kwargs should be empty
336
+ assert kwargs == {}
337
+ # Can't use 'old_y' since it was dropped, so just use 'old_x' mapped to 'new_x'
338
+ result = await forward(new_x=new_x)
339
+ return result
340
+
341
+ new_tool = Tool.from_tool(
342
+ add_tool,
343
+ transform_fn=custom_fn,
344
+ transform_args={
345
+ "old_x": ArgTransform(name="new_x"),
346
+ "old_y": ArgTransform(hide=True),
347
+ },
348
+ ) # drop 'old_y'
349
+ result = await new_tool.run(arguments={"new_x": 8})
350
+ # 8 + 10 (default value of b in parent)
351
+ assert result[0].text == "18" # type: ignore[attr-defined]
352
+
353
+
354
+ async def test_forward_outside_context_raises_error():
355
+ """Test that forward() raises RuntimeError when called outside a transformed tool."""
356
+ with pytest.raises(
357
+ RuntimeError,
358
+ match=re.escape("forward() can only be called within a transformed tool"),
359
+ ):
360
+ await forward(new_x=1, old_y=2)
361
+
362
+
363
+ async def test_forward_raw_outside_context_raises_error():
364
+ """Test that forward_raw() raises RuntimeError when called outside a transformed tool."""
365
+ with pytest.raises(
366
+ RuntimeError,
367
+ match=re.escape("forward_raw() can only be called within a transformed tool"),
368
+ ):
369
+ await forward_raw(new_x=1, old_y=2)
370
+
371
+
372
+ def test_transform_args_validation_unknown_arg(add_tool):
373
+ """Test that transform_args with unknown arguments raises ValueError."""
374
+ with pytest.raises(
375
+ ValueError, match="Unknown arguments in transform_args: unknown_param"
376
+ ):
377
+ Tool.from_tool(
378
+ add_tool, transform_args={"unknown_param": ArgTransform(name="new_name")}
379
+ )
380
+
381
+
382
+ def test_transform_args_creates_duplicate_names(add_tool):
383
+ """Test that transform_args creating duplicate parameter names raises ValueError."""
384
+ with pytest.raises(
385
+ ValueError,
386
+ match="Multiple arguments would be mapped to the same names: same_name",
387
+ ):
388
+ Tool.from_tool(
389
+ add_tool,
390
+ transform_args={
391
+ "old_x": ArgTransform(name="same_name"),
392
+ "old_y": ArgTransform(name="same_name"),
393
+ },
394
+ )
395
+
396
+
397
+ def test_function_without_kwargs_missing_params(add_tool):
398
+ """Test that function missing required transformed parameters raises ValueError."""
399
+
400
+ def invalid_fn(new_x: int, non_existent: str) -> str:
401
+ return f"{new_x}_{non_existent}"
402
+
403
+ with pytest.raises(
404
+ ValueError,
405
+ match="Function missing parameters required after transformation: new_y",
406
+ ):
407
+ Tool.from_tool(
408
+ add_tool,
409
+ transform_fn=invalid_fn,
410
+ transform_args={
411
+ "old_x": ArgTransform(name="new_x"),
412
+ "old_y": ArgTransform(name="new_y"),
413
+ },
414
+ )
415
+
416
+
417
+ def test_function_without_kwargs_can_have_extra_params(add_tool):
418
+ """Test that function can have extra parameters not in parent tool."""
419
+
420
+ def valid_fn(new_x: int, new_y: int, extra_param: str = "default") -> str:
421
+ return f"{new_x}_{new_y}_{extra_param}"
422
+
423
+ # Should work - extra_param is fine as long as it has a default
424
+ new_tool = Tool.from_tool(
425
+ add_tool,
426
+ transform_fn=valid_fn,
427
+ transform_args={
428
+ "old_x": ArgTransform(name="new_x"),
429
+ "old_y": ArgTransform(name="new_y"),
430
+ },
431
+ )
432
+
433
+ # The final schema should include all function parameters
434
+ assert "new_x" in new_tool.parameters["properties"]
435
+ assert "new_y" in new_tool.parameters["properties"]
436
+ assert "extra_param" in new_tool.parameters["properties"]
437
+
438
+
439
+ def test_function_with_kwargs_can_add_params(add_tool):
440
+ """Test that function with **kwargs can add new parameters."""
441
+
442
+ async def valid_fn(extra_param: str, **kwargs) -> str:
443
+ result = await forward(**kwargs)
444
+ return f"{extra_param}: {result}"
445
+
446
+ # This should work fine - kwargs allows access to all transformed params
447
+ tool = Tool.from_tool(
448
+ add_tool,
449
+ transform_fn=valid_fn,
450
+ transform_args={
451
+ "old_x": ArgTransform(name="new_x"),
452
+ "old_y": ArgTransform(name="new_y"),
453
+ },
454
+ )
455
+
456
+ # extra_param is added, new_x and new_y are available
457
+ assert "extra_param" in tool.parameters["properties"]
458
+ assert "new_x" in tool.parameters["properties"]
459
+ assert "new_y" in tool.parameters["properties"]
460
+
461
+
462
+ async def test_tool_transform_chaining(add_tool):
463
+ """Test that transformed tools can be transformed again."""
464
+ # First transformation: a -> x
465
+ tool1 = Tool.from_tool(add_tool, transform_args={"old_x": ArgTransform(name="x")})
466
+
467
+ # Second transformation: x -> final_x, using tool1
468
+ tool2 = Tool.from_tool(tool1, transform_args={"x": ArgTransform(name="final_x")})
469
+
470
+ result = await tool2.run(arguments={"final_x": 5})
471
+ assert result[0].text == "15" # type: ignore
472
+
473
+ # Transform tool1 with custom function that handles all parameters
474
+ async def custom(final_x: int, **kwargs) -> str:
475
+ result = await forward(final_x=final_x, **kwargs)
476
+ return f"custom {result[0].text}" # Extract text from content
477
+
478
+ tool3 = Tool.from_tool(
479
+ tool1, transform_fn=custom, transform_args={"x": ArgTransform(name="final_x")}
480
+ )
481
+ result = await tool3.run(arguments={"final_x": 3, "old_y": 5})
482
+ assert result[0].text == "custom 8" # type: ignore
483
+
484
+
485
+ class MyModel(BaseModel):
486
+ x: int
487
+ y: str
488
+
489
+
490
+ @dataclass
491
+ class MyDataclass:
492
+ x: int
493
+ y: str
494
+
495
+
496
+ class MyTypedDict(TypedDict):
497
+ x: int
498
+ y: str
499
+
500
+
501
+ @pytest.mark.parametrize(
502
+ "py_type, json_type",
503
+ [
504
+ (int, "integer"),
505
+ (float, "number"),
506
+ (str, "string"),
507
+ (bool, "boolean"),
508
+ (list, "array"),
509
+ (list[int], "array"),
510
+ (dict, "object"),
511
+ (dict[str, int], "object"),
512
+ (MyModel, "object"),
513
+ (MyDataclass, "object"),
514
+ (MyTypedDict, "object"),
515
+ ],
516
+ )
517
+ def test_arg_transform_type_handling(add_tool, py_type, json_type):
518
+ """Test that ArgTransform type attribute gets applied to schema."""
519
+ new_tool = Tool.from_tool(
520
+ add_tool, transform_args={"old_x": ArgTransform(type=py_type)}
521
+ )
522
+
523
+ # Check that the type was changed in the schema
524
+ x_prop = get_property(new_tool, "old_x")
525
+ assert x_prop["type"] == json_type
526
+
527
+
528
+ def test_arg_transform_annotated_types(add_tool):
529
+ """Test that ArgTransform works with annotated types and complex types."""
530
+ from typing import Annotated
531
+
532
+ from pydantic import Field
533
+
534
+ # Test with Annotated types
535
+ tool = Tool.from_tool(
536
+ add_tool,
537
+ transform_args={
538
+ "old_x": ArgTransform(
539
+ type=Annotated[int, Field(description="An annotated integer")]
540
+ )
541
+ },
542
+ )
543
+
544
+ x_prop = get_property(tool, "old_x")
545
+ assert x_prop["type"] == "integer"
546
+ # The ArgTransform description should override the annotation description
547
+ # (since we didn't set a description in ArgTransform, it should use the original)
548
+
549
+ # Test with Annotated string that has constraints
550
+ tool2 = Tool.from_tool(
551
+ add_tool,
552
+ transform_args={
553
+ "old_x": ArgTransform(
554
+ type=Annotated[str, Field(min_length=1, max_length=10)]
555
+ )
556
+ },
557
+ )
558
+
559
+ x_prop2 = get_property(tool2, "old_x")
560
+ assert x_prop2["type"] == "string"
561
+ assert x_prop2["minLength"] == 1
562
+ assert x_prop2["maxLength"] == 10
563
+
564
+
565
+ def test_arg_transform_precedence_over_function_without_kwargs():
566
+ """Test that ArgTransform attributes take precedence over function signature (no **kwargs)."""
567
+
568
+ @Tool.from_function
569
+ def base(x: int, y: str = "default") -> str:
570
+ return f"{x}: {y}"
571
+
572
+ # Function signature says x: int with no default, y: str = "function_default"
573
+ # ArgTransform should override these
574
+ def custom_fn(x: str = "transform_default", y: int = 99) -> str:
575
+ return f"custom: {x}, {y}"
576
+
577
+ tool = Tool.from_tool(
578
+ base,
579
+ transform_fn=custom_fn,
580
+ transform_args={
581
+ "x": ArgTransform(type=str, default="transform_default"),
582
+ "y": ArgTransform(type=int, default=99),
583
+ },
584
+ )
585
+
586
+ # ArgTransform should take precedence
587
+ x_prop = get_property(tool, "x")
588
+ y_prop = get_property(tool, "y")
589
+
590
+ assert x_prop["type"] == "string" # ArgTransform type wins
591
+ assert x_prop["default"] == "transform_default" # ArgTransform default wins
592
+ assert y_prop["type"] == "integer" # ArgTransform type wins
593
+ assert y_prop["default"] == 99 # ArgTransform default wins
594
+
595
+ # Neither parameter should be required due to ArgTransform defaults
596
+ assert "x" not in tool.parameters["required"]
597
+ assert "y" not in tool.parameters["required"]
598
+
599
+
600
+ async def test_arg_transform_precedence_over_function_with_kwargs():
601
+ """Test that ArgTransform attributes take precedence over function signature (with **kwargs)."""
602
+
603
+ @Tool.from_function
604
+ def base(x: int, y: str = "base_default") -> str:
605
+ return f"{x}: {y}"
606
+
607
+ # Function signature has different types/defaults than ArgTransform
608
+ async def custom_fn(x: str = "function_default", **kwargs) -> str:
609
+ result = await forward(x=x, **kwargs)
610
+ return f"custom: {result}"
611
+
612
+ tool = Tool.from_tool(
613
+ base,
614
+ transform_fn=custom_fn,
615
+ transform_args={
616
+ "x": ArgTransform(type=int, default=42), # Different type and default
617
+ "y": ArgTransform(description="ArgTransform description"),
618
+ },
619
+ )
620
+
621
+ # ArgTransform should take precedence
622
+ x_prop = get_property(tool, "x")
623
+ y_prop = get_property(tool, "y")
624
+
625
+ assert x_prop["type"] == "integer" # ArgTransform type wins over function's str
626
+ assert x_prop["default"] == 42 # ArgTransform default wins over function's default
627
+ assert (
628
+ y_prop["description"] == "ArgTransform description"
629
+ ) # ArgTransform description
630
+
631
+ # x should not be required due to ArgTransform default
632
+ assert "x" not in tool.parameters["required"]
633
+
634
+ # Test it works at runtime
635
+ result = await tool.run(arguments={"y": "test"})
636
+ # Should use ArgTransform default of 42
637
+ assert "42: test" in result[0].text # type: ignore
638
+
639
+
640
+ def test_arg_transform_combined_attributes():
641
+ """Test that multiple ArgTransform attributes work together."""
642
+
643
+ @Tool.from_function
644
+ def base(param: int) -> str:
645
+ return str(param)
646
+
647
+ tool = Tool.from_tool(
648
+ base,
649
+ transform_args={
650
+ "param": ArgTransform(
651
+ name="renamed_param",
652
+ type=str,
653
+ description="New description",
654
+ default="default_value",
655
+ )
656
+ },
657
+ )
658
+
659
+ # Check all attributes were applied
660
+ assert "renamed_param" in tool.parameters["properties"]
661
+ assert "param" not in tool.parameters["properties"]
662
+
663
+ prop = get_property(tool, "renamed_param")
664
+ assert prop["type"] == "string"
665
+ assert prop["description"] == "New description"
666
+ assert prop["default"] == "default_value"
667
+ assert "renamed_param" not in tool.parameters["required"] # Has default
668
+
669
+
670
+ async def test_arg_transform_type_precedence_runtime():
671
+ """Test that ArgTransform type changes work correctly at runtime."""
672
+
673
+ @Tool.from_function
674
+ def base(x: int, y: int = 10) -> int:
675
+ return x + y
676
+
677
+ # Transform x to string type but keep same logic
678
+ async def custom_fn(x: str, y: int = 10) -> str:
679
+ # Convert string back to int for the original function
680
+ result = await forward_raw(x=int(x), y=y)
681
+ # Extract the text from the result
682
+ result_text = result[0].text
683
+ return f"String input '{x}' converted to result: {result_text}"
684
+
685
+ tool = Tool.from_tool(
686
+ base, transform_fn=custom_fn, transform_args={"x": ArgTransform(type=str)}
687
+ )
688
+
689
+ # Verify schema shows string type
690
+ assert get_property(tool, "x")["type"] == "string"
691
+
692
+ # Test it works with string input
693
+ result = await tool.run(arguments={"x": "5", "y": 3})
694
+ assert "String input '5'" in result[0].text # type: ignore
695
+ assert "result: 8" in result[0].text # type: ignore
696
+
697
+
698
+ class TestProxy:
699
+ @pytest.fixture
700
+ def mcp_server(self) -> FastMCP:
701
+ mcp = FastMCP()
702
+
703
+ @mcp.tool
704
+ def add(old_x: int, old_y: int = 10) -> int:
705
+ return old_x + old_y
706
+
707
+ return mcp
708
+
709
+ @pytest.fixture
710
+ def proxy_server(self, mcp_server: FastMCP) -> FastMCP:
711
+ from fastmcp.client.transports import FastMCPTransport
712
+
713
+ proxy = FastMCP.as_proxy(Client(transport=FastMCPTransport(mcp_server)))
714
+ return proxy
715
+
716
+ async def test_transform_proxy(self, proxy_server: FastMCP):
717
+ # when adding transformed tools to proxy servers. Needs separate investigation.
718
+
719
+ add_tool = await proxy_server.get_tool("add")
720
+ new_add_tool = Tool.from_tool(
721
+ add_tool,
722
+ name="add_transformed",
723
+ transform_args={"old_x": ArgTransform(name="new_x")},
724
+ )
725
+ proxy_server.add_tool(new_add_tool)
726
+
727
+ async with Client(proxy_server) as client:
728
+ # The tool should be registered with its transformed name
729
+ result = await client.call_tool("add_transformed", {"new_x": 1, "old_y": 2})
730
+ assert result[0].text == "3" # type: ignore
731
+
732
+
733
+ async def test_arg_transform_default_factory():
734
+ """Test ArgTransform with default_factory for hidden parameters."""
735
+
736
+ @Tool.from_function
737
+ def base_tool(x: int, timestamp: float) -> str:
738
+ return f"{x}_{timestamp}"
739
+
740
+ # Create a tool with default_factory for hidden timestamp
741
+ new_tool = Tool.from_tool(
742
+ base_tool,
743
+ transform_args={
744
+ "timestamp": ArgTransform(hide=True, default_factory=lambda: 12345.0)
745
+ },
746
+ )
747
+
748
+ # Only x should be visible since timestamp is hidden
749
+ assert sorted(new_tool.parameters["properties"]) == ["x"]
750
+
751
+ # Should work without providing timestamp (gets value from factory)
752
+ result = await new_tool.run(arguments={"x": 42})
753
+ assert result[0].text == "42_12345.0" # type: ignore
754
+
755
+
756
+ async def test_arg_transform_default_factory_called_each_time():
757
+ """Test that default_factory is called for each execution."""
758
+ call_count = 0
759
+
760
+ def counter_factory():
761
+ nonlocal call_count
762
+ call_count += 1
763
+ return call_count
764
+
765
+ @Tool.from_function
766
+ def base_tool(x: int, counter: int = 0) -> str:
767
+ return f"{x}_{counter}"
768
+
769
+ new_tool = Tool.from_tool(
770
+ base_tool,
771
+ transform_args={
772
+ "counter": ArgTransform(hide=True, default_factory=counter_factory)
773
+ },
774
+ )
775
+
776
+ # Only x should be visible since counter is hidden
777
+ assert sorted(new_tool.parameters["properties"]) == ["x"]
778
+
779
+ # First call
780
+ result1 = await new_tool.run(arguments={"x": 1})
781
+ assert result1[0].text == "1_1" # type: ignore
782
+
783
+ # Second call should get a different value
784
+ result2 = await new_tool.run(arguments={"x": 2})
785
+ assert result2[0].text == "2_2" # type: ignore
786
+
787
+
788
+ async def test_arg_transform_hidden_with_default_factory():
789
+ """Test hidden parameter with default_factory."""
790
+
791
+ @Tool.from_function
792
+ def base_tool(x: int, request_id: str) -> str:
793
+ return f"{x}_{request_id}"
794
+
795
+ def make_request_id():
796
+ return "req_123"
797
+
798
+ new_tool = Tool.from_tool(
799
+ base_tool,
800
+ transform_args={
801
+ "request_id": ArgTransform(hide=True, default_factory=make_request_id)
802
+ },
803
+ )
804
+
805
+ # Only x should be visible
806
+ assert sorted(new_tool.parameters["properties"]) == ["x"]
807
+
808
+ # Should pass hidden request_id with factory value
809
+ result = await new_tool.run(arguments={"x": 42})
810
+ assert result[0].text == "42_req_123" # type: ignore
811
+
812
+
813
+ async def test_arg_transform_default_and_factory_raises_error():
814
+ """Test that providing both default and default_factory raises an error."""
815
+ with pytest.raises(
816
+ ValueError, match="Cannot specify both 'default' and 'default_factory'"
817
+ ):
818
+ ArgTransform(default=42, default_factory=lambda: 24)
819
+
820
+
821
+ async def test_arg_transform_default_factory_requires_hide():
822
+ """Test that default_factory requires hide=True."""
823
+ with pytest.raises(
824
+ ValueError, match="default_factory can only be used with hide=True"
825
+ ):
826
+ ArgTransform(default_factory=lambda: 42) # hide=False by default
827
+
828
+
829
+ async def test_arg_transform_required_true():
830
+ """Test that required=True makes an optional parameter required."""
831
+
832
+ @Tool.from_function
833
+ def base_tool(optional_param: int = 42) -> str:
834
+ return f"value: {optional_param}"
835
+
836
+ # Make the optional parameter required
837
+ new_tool = Tool.from_tool(
838
+ base_tool, transform_args={"optional_param": ArgTransform(required=True)}
839
+ )
840
+
841
+ # Parameter should now be required (no default in schema)
842
+ assert "optional_param" in new_tool.parameters["required"]
843
+ assert "default" not in new_tool.parameters["properties"]["optional_param"]
844
+
845
+ # Should work when parameter is provided
846
+ result = await new_tool.run(arguments={"optional_param": 100})
847
+ assert result[0].text == "value: 100" # type: ignore
848
+
849
+ # Should fail when parameter is not provided
850
+ with pytest.raises(TypeError, match="Missing required argument"):
851
+ await new_tool.run(arguments={})
852
+
853
+
854
+ async def test_arg_transform_required_false():
855
+ """Test that required=False makes a required parameter optional with default."""
856
+
857
+ @Tool.from_function
858
+ def base_tool(required_param: int) -> str:
859
+ return f"value: {required_param}"
860
+
861
+ with pytest.raises(
862
+ ValueError,
863
+ match="Cannot specify 'required=False'. Set a default value instead.",
864
+ ):
865
+ Tool.from_tool(
866
+ base_tool,
867
+ transform_args={"required_param": ArgTransform(required=False, default=99)}, # type: ignore
868
+ )
869
+
870
+
871
+ async def test_arg_transform_required_with_rename():
872
+ """Test that required works correctly with argument renaming."""
873
+
874
+ @Tool.from_function
875
+ def base_tool(optional_param: int = 42) -> str:
876
+ return f"value: {optional_param}"
877
+
878
+ # Rename and make required
879
+ new_tool = Tool.from_tool(
880
+ base_tool,
881
+ transform_args={
882
+ "optional_param": ArgTransform(name="new_param", required=True)
883
+ },
884
+ )
885
+
886
+ # New parameter name should be required
887
+ assert "new_param" in new_tool.parameters["required"]
888
+ assert "optional_param" not in new_tool.parameters["properties"]
889
+ assert "new_param" in new_tool.parameters["properties"]
890
+ assert "default" not in new_tool.parameters["properties"]["new_param"]
891
+
892
+ # Should work with new name
893
+ result = await new_tool.run(arguments={"new_param": 200})
894
+ assert result[0].text == "value: 200" # type: ignore
895
+
896
+
897
+ async def test_arg_transform_required_true_with_default_raises_error():
898
+ """Test that required=True with default raises an error."""
899
+ with pytest.raises(
900
+ ValueError, match="Cannot specify 'required=True' with 'default'"
901
+ ):
902
+ ArgTransform(required=True, default=42)
903
+
904
+
905
+ async def test_arg_transform_required_true_with_factory_raises_error():
906
+ """Test that required=True with default_factory raises an error."""
907
+ with pytest.raises(
908
+ ValueError, match="default_factory can only be used with hide=True"
909
+ ):
910
+ ArgTransform(required=True, default_factory=lambda: 42)
911
+
912
+
913
+ async def test_arg_transform_required_no_change():
914
+ """Test that required=... (NotSet) leaves requirement status unchanged."""
915
+
916
+ @Tool.from_function
917
+ def base_tool(required_param: int, optional_param: int = 42) -> str:
918
+ return f"values: {required_param}, {optional_param}"
919
+
920
+ # Transform without changing required status
921
+ new_tool = Tool.from_tool(
922
+ base_tool,
923
+ transform_args={
924
+ "required_param": ArgTransform(name="req"),
925
+ "optional_param": ArgTransform(name="opt"),
926
+ },
927
+ )
928
+
929
+ # Required status should be unchanged
930
+ assert "req" in new_tool.parameters["required"]
931
+ assert "opt" not in new_tool.parameters["required"]
932
+ assert new_tool.parameters["properties"]["opt"]["default"] == 42
933
+
934
+ # Should work as expected
935
+ result = await new_tool.run(arguments={"req": 1})
936
+ assert result[0].text == "values: 1, 42" # type: ignore
937
+
938
+
939
+ async def test_arg_transform_hide_and_required_raises_error():
940
+ """Test that hide=True and required=True together raises an error."""
941
+ with pytest.raises(
942
+ ValueError, match="Cannot specify both 'hide=True' and 'required=True'"
943
+ ):
944
+ ArgTransform(hide=True, required=True)
tests/utilities/test_types.py CHANGED
@@ -1,4 +1,5 @@
1
  import base64
 
2
  from typing import Annotated, Any
3
 
4
  import pytest
@@ -308,6 +309,14 @@ class TestFindKwargByType:
308
 
309
  assert find_kwarg_by_type(func, SENTINEL) is None # type: ignore
310
 
 
 
 
 
 
 
 
 
311
  def test_missing_type_annotation(self):
312
  """Test finding parameter with a missing type annotation."""
313
 
 
1
  import base64
2
+ from types import EllipsisType
3
  from typing import Annotated, Any
4
 
5
  import pytest
 
309
 
310
  assert find_kwarg_by_type(func, SENTINEL) is None # type: ignore
311
 
312
+ def test_ellipsis_annotation(self):
313
+ """Test finding parameter with an ellipsis annotation."""
314
+
315
+ def func(a: int, b: EllipsisType, c: str): # type: ignore # noqa: F821
316
+ pass
317
+
318
+ assert find_kwarg_by_type(func, EllipsisType) == "b" # type: ignore
319
+
320
  def test_missing_type_annotation(self):
321
  """Test finding parameter with a missing type annotation."""
322