Jeremiah Lowin commited on
Commit
fbacb68
·
1 Parent(s): c135727

Add documentation

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,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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`. You can only hide arguments that already have a default value, or that you provide a new `default` or `default_factory` for.
186
+
187
+ ```python {19-20}
188
+ import os
189
+ from fastmcp import FastMCP
190
+ from fastmcp.tools import Tool
191
+ from fastmcp.tools.tool_transform import ArgTransform
192
+
193
+ mcp = FastMCP()
194
+
195
+ @mcp.tool
196
+ def send_email(to: str, subject: str, body: str, api_key: str):
197
+ """Sends an email."""
198
+ ...
199
+
200
+ # Create a simplified version that hides the API key
201
+ new_tool = Tool.from_tool(
202
+ send_email,
203
+ name="send_notification",
204
+ transform_args={
205
+ "api_key": ArgTransform(
206
+ hide=True,
207
+ default=os.environ.get("EMAIL_API_KEY"),
208
+ )
209
+ }
210
+ )
211
+ ```
212
+ The LLM now only sees the `to`, `subject`, and `body` parameters. The `api_key` is supplied automatically from an environment variable.
213
+
214
+ 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,
215
+
216
+ ```python {3-4}
217
+ transform_args = {
218
+ 'timestamp': ArgTransform(
219
+ hide=True,
220
+ default_factory=lambda: datetime.now(),
221
+ )
222
+ }
223
+ ```
224
+
225
+ <Warning>
226
+ `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.
227
+ </Warning>
228
+
229
+ ### Required Values
230
+
231
+ 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.
232
+
233
+ ```python {3}
234
+ transform_args = {
235
+ 'user_id': ArgTransform(
236
+ required=True,
237
+ )
238
+ }
239
+ ```
240
+
241
+ ## Modifying Tool Behavior
242
+
243
+ <Warning>
244
+ With great power comes great responsibility. Modifying tool behavior is a very advanced feature.
245
+ </Warning>
246
+
247
+ 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.
248
+
249
+ 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.
250
+
251
+ ### The Transform Function
252
+
253
+ The `transform_fn` is an async function that **completely replaces** the parent tool's logic.
254
+
255
+ 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.
256
+
257
+ ```python
258
+ async def my_custom_logic(user_input: str, max_length: int = 100) -> str:
259
+ # Your custom logic here - this completely replaces the parent tool
260
+ return f"Custom result for: {user_input[:max_length]}"
261
+
262
+ Tool.from_tool(transform_fn=my_custom_logic)
263
+ ```
264
+
265
+ <Tip>
266
+ The name / docstring of the `transform_fn` are ignored. Only its arguments are used to determine the final schema.
267
+ </Tip>
268
+
269
+ ### Calling the Parent Tool
270
+
271
+ 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.
272
+
273
+ Both `forward()` and `forward_raw()` are async functions that let you call the parent tool from within your `transform_fn`:
274
+
275
+ - **`forward()`** (recommended): Automatically handles argument mapping based on your `ArgTransform` configurations. Call it with the transformed argument names.
276
+ - **`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`.
277
+
278
+ 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:
279
+ <Tabs>
280
+ <Tab title="Using forward()">
281
+
282
+ 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:
283
+
284
+ ```python {15}
285
+ from fastmcp import FastMCP
286
+ from fastmcp.tools import Tool
287
+ from fastmcp.tools.tool_transform import forward
288
+
289
+ mcp = FastMCP()
290
+
291
+ @mcp.tool
292
+ def add(x: int, y: int) -> int:
293
+ """Adds two numbers."""
294
+ return x + y
295
+
296
+ async def ensure_positive(x: int, y: int) -> int:
297
+ if x <= 0 or y <= 0:
298
+ raise ValueError("x and y must be positive")
299
+ return await forward(x=x, y=y)
300
+
301
+ new_tool = Tool.from_tool(
302
+ add,
303
+ transform_fn=ensure_positive,
304
+ )
305
+
306
+ mcp.add_tool(new_tool)
307
+ ```
308
+ </Tab>
309
+ <Tab title="Using forward() with renamed args">
310
+
311
+ 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:
312
+
313
+ ```python {15, 20-23}
314
+ from fastmcp import FastMCP
315
+ from fastmcp.tools import Tool
316
+ from fastmcp.tools.tool_transform import forward
317
+
318
+ mcp = FastMCP()
319
+
320
+ @mcp.tool
321
+ def add(x: int, y: int) -> int:
322
+ """Adds two numbers."""
323
+ return x + y
324
+
325
+ async def ensure_positive(a: int, b: int) -> int:
326
+ if a <= 0 or b <= 0:
327
+ raise ValueError("a and b must be positive")
328
+ return await forward(a=a, b=b)
329
+
330
+ new_tool = Tool.from_tool(
331
+ add,
332
+ transform_fn=ensure_positive,
333
+ transform_args={
334
+ "x": ArgTransform(name="a"),
335
+ "y": ArgTransform(name="b"),
336
+ }
337
+ )
338
+
339
+ mcp.add_tool(new_tool)
340
+ ```
341
+ </Tab>
342
+ <Tab title="Using forward_raw()">
343
+ Finally, you can use `forward_raw()` to bypass all argument mapping and call the parent tool directly with its original argument names.
344
+
345
+ ```python {15, 20-23}
346
+ from fastmcp import FastMCP
347
+ from fastmcp.tools import Tool
348
+ from fastmcp.tools.tool_transform import forward
349
+
350
+ mcp = FastMCP()
351
+
352
+ @mcp.tool
353
+ def add(x: int, y: int) -> int:
354
+ """Adds two numbers."""
355
+ return x + y
356
+
357
+ async def ensure_positive(a: int, b: int) -> int:
358
+ if a <= 0 or b <= 0:
359
+ raise ValueError("a and b must be positive")
360
+ return await forward_raw(x=a, y=b)
361
+
362
+ new_tool = Tool.from_tool(
363
+ add,
364
+ transform_fn=ensure_positive,
365
+ transform_args={
366
+ "x": ArgTransform(name="a"),
367
+ "y": ArgTransform(name="b"),
368
+ }
369
+ )
370
+
371
+ mcp.add_tool(new_tool)
372
+ ```
373
+ </Tab>
374
+ </Tabs>
375
+
376
+ ### Passing Arguments with **kwargs
377
+
378
+ 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.
379
+
380
+ 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`.
381
+
382
+ ```python {12, 15}
383
+ from fastmcp import FastMCP
384
+ from fastmcp.tools import Tool
385
+ from fastmcp.tools.tool_transform import forward
386
+
387
+ mcp = FastMCP()
388
+
389
+ @mcp.tool
390
+ def add(x: int, y: int) -> int:
391
+ """Adds two numbers."""
392
+ return x + y
393
+
394
+ async def ensure_a_positive(a: int, **kwargs) -> int:
395
+ if a <= 0:
396
+ raise ValueError("a must be positive")
397
+ return await forward(a=a, **kwargs)
398
+
399
+ new_tool = Tool.from_tool(
400
+ add,
401
+ transform_fn=ensure_positive,
402
+ transform_args={
403
+ "x": ArgTransform(name="a"),
404
+ "y": ArgTransform(name="b"),
405
+ }
406
+ )
407
+
408
+ mcp.add_tool(new_tool)
409
+ ```
410
+
411
+ <Tip>
412
+ 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()`.
413
+ </Tip>
414
+
415
+ ## Common Patterns
416
+
417
+ Tool transformation is a flexible feature that supports many powerful patterns. Here are a few common use cases to give you ideas.
418
+
419
+ ### Adapting Remote or Generated Tools
420
+ 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.
421
+
422
+ ### Chaining Transformations
423
+ 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.
424
+
425
+ ### Context-Aware Tool Factories
426
+ 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/tools/tool_transform.py CHANGED
@@ -1,107 +1,3 @@
1
- """# Tool Transformation
2
-
3
- Transform existing tools with modified schemas, argument mappings, and custom behavior.
4
- Use this for creating tool variants, adapting tools for different contexts, or adding
5
- custom logic while preserving the original tool's functionality.
6
-
7
- ## Quick Reference
8
-
9
- ### Basic Argument Renaming
10
- ```python
11
- # Transform specific parent arguments (others pass through unchanged)
12
- new_tool = Tool.from_tool(
13
- original_tool,
14
- transform_args={"old_param": "new_param"} # Only transforms this one arg
15
- )
16
- ```
17
-
18
- ### Complex Transformations
19
- ```python
20
- from fastmcp.tools.tool_transform import ArgTransform
21
-
22
- new_tool = Tool.from_tool(
23
- original_tool,
24
- transform_args={
25
- "old_name": ArgTransform(name="new_name", description="Updated desc"),
26
- "hidden_param": ArgTransform(hide=True, default="constant_value"),
27
- "simple": "renamed"
28
- }
29
- )
30
- ```
31
-
32
- ### Custom Transform Functions
33
- ```python
34
- async def my_transform(new_x: int, new_y: int) -> str:
35
- # Use forward() with transformed argument names
36
- result = await forward(new_x=new_x, new_y=new_y)
37
- return f"Custom: {result}"
38
-
39
- new_tool = Tool.from_tool(
40
- original_tool,
41
- transform_fn=my_transform,
42
- transform_args={"x": "new_x", "y": "new_y"}
43
- )
44
- ```
45
-
46
- ### Using **kwargs for Flexibility
47
- ```python
48
- async def flexible_transform(**kwargs) -> str:
49
- # kwargs contains all transformed arguments
50
- result = await forward(**kwargs)
51
- return f"Got: {kwargs}"
52
-
53
- new_tool = Tool.from_tool(
54
- original_tool,
55
- transform_fn=flexible_transform,
56
- transform_args={"x": "input_x", "y": "input_y"}
57
- )
58
- ```
59
-
60
- ## Key Functions
61
-
62
- - `forward(**kwargs)`: Call parent tool with transformed argument names
63
- - `forward_raw(**kwargs)`: Call parent tool with original argument names
64
-
65
- ## Important Notes
66
-
67
- - `transform_args` is optional - if empty/None, all parent arguments pass through unchanged
68
- - Only arguments listed in `transform_args` are transformed, others remain as-is
69
- - Functions with `**kwargs` receive both transformed and untransformed arguments
70
-
71
- ## ArgTransform Options
72
-
73
- - `name`: Rename the argument
74
- - `description`: Change the description
75
- - `default`: Add/change default value
76
- - `hide=True`: Hide the argument from clients (pass constant value to parent)
77
-
78
- ## Common Patterns
79
-
80
- ```python
81
- # Chain transformations (partial transforms at each step)
82
- tool1 = Tool.from_tool(original, transform_args={"a": "x"}) # Only transforms 'a'
83
- tool2 = Tool.from_tool(tool1, transform_args={"x": "final"}) # Only transforms 'x'
84
-
85
- # Pure passthrough (no transform_args needed)
86
- enhanced = Tool.from_tool(
87
- original,
88
- name="enhanced_version",
89
- description="Better tool",
90
- tags={"v2", "enhanced"}
91
- # No transform_args = all parent args pass through unchanged
92
- )
93
-
94
- # Hide specific arguments with constant values
95
- simplified = Tool.from_tool(
96
- complex_tool,
97
- transform_args={
98
- "api_key": ArgTransform(hide=True, default="secret_key"), # Hidden constant
99
- "debug": ArgTransform(hide=True) # Hidden, uses parent's default
100
- }
101
- )
102
- ```
103
- """
104
-
105
  from __future__ import annotations
106
 
107
  import inspect
@@ -109,19 +5,19 @@ from collections.abc import Callable
109
  from contextvars import ContextVar
110
  from dataclasses import dataclass
111
  from types import EllipsisType
112
- from typing import TYPE_CHECKING, Any
113
 
114
  from mcp.types import EmbeddedResource, ImageContent, TextContent, ToolAnnotations
 
115
 
116
  from fastmcp.tools.tool import ParsedFunction, Tool
117
  from fastmcp.utilities.logging import get_logger
118
  from fastmcp.utilities.types import get_cached_typeadapter
119
 
120
- if TYPE_CHECKING:
121
- pass
122
-
123
  logger = get_logger(__name__)
124
 
 
 
125
 
126
  # Context variable to store current transformed tool
127
  _current_tool: ContextVar[TransformedTool | None] = ContextVar(
@@ -197,8 +93,10 @@ class ArgTransform:
197
  name: New name for the argument. Use None to keep original name, or ... for no change.
198
  description: New description for the argument. Use None to remove description, or ... for no change.
199
  default: New default value for the argument. Use ... for no change.
 
200
  type: New type for the argument. Use ... for no change.
201
  hide: If True, hide this argument from clients but pass a constant value to parent.
 
202
 
203
  Examples:
204
  # Rename argument 'old_name' to 'new_name'
@@ -210,6 +108,9 @@ class ArgTransform:
210
  # Add a default value (makes argument optional)
211
  ArgTransform(default=42)
212
 
 
 
 
213
  # Change the type
214
  ArgTransform(type=str)
215
 
@@ -219,15 +120,53 @@ class ArgTransform:
219
  # Hide argument but pass a constant value to parent
220
  ArgTransform(hide=True, default="constant_value")
221
 
 
 
 
 
 
 
222
  # Combine multiple transformations
223
  ArgTransform(name="new_name", description="New desc", default=None, type=int)
224
  """
225
 
226
- name: str | None | EllipsisType = ...
227
- description: str | None | EllipsisType = ...
228
- default: Any | EllipsisType = ...
229
- type: Any | EllipsisType = ...
 
230
  hide: bool = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
 
233
  class TransformedTool(Tool):
@@ -249,9 +188,12 @@ class TransformedTool(Tool):
249
  validation when forward() is called from custom functions.
250
  """
251
 
 
 
252
  parent_tool: Tool
253
  fn: Callable[..., Any]
254
  forwarding_fn: Callable[..., Any] # Always present, handles arg transformation
 
255
 
256
  async def run(
257
  self, arguments: dict[str, Any]
@@ -278,7 +220,29 @@ class TransformedTool(Tool):
278
 
279
  for param_name, param_schema in properties.items():
280
  if param_name not in arguments and "default" in param_schema:
281
- arguments[param_name] = param_schema["default"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
  token = _current_tool.set(self)
284
  try:
@@ -291,11 +255,11 @@ class TransformedTool(Tool):
291
  def from_tool(
292
  cls,
293
  tool: Tool,
294
- transform_fn: Callable[..., Any] | None = None,
295
  name: str | None = None,
296
- transform_args: dict[str, str | ArgTransform | None] | None = None,
297
  description: str | None = None,
298
  tags: set[str] | None = None,
 
 
299
  annotations: ToolAnnotations | None = None,
300
  serializer: Callable[[Any], str] | None = None,
301
  ) -> TransformedTool:
@@ -338,16 +302,16 @@ class TransformedTool(Tool):
338
 
339
  Tool.from_tool(parent, transform_fn=flexible, transform_args={"a": "x"})
340
  """
341
-
342
- # Validate transform_args early
343
- if transform_args:
344
- parent_params = set(tool.parameters.get("properties", {}).keys())
345
- unknown_args = set(transform_args.keys()) - parent_params
346
- if unknown_args:
347
- raise ValueError(
348
- f"Unknown arguments in transform_args: {', '.join(sorted(unknown_args))}. "
349
- f"Parent tool has: {', '.join(sorted(parent_params))}"
350
- )
351
 
352
  # Always create the forwarding transform
353
  schema, forwarding_fn = cls._create_forwarding_transform(tool, transform_args)
@@ -397,10 +361,8 @@ class TransformedTool(Tool):
397
  if transform_args:
398
  new_names = []
399
  for old_name, transform in transform_args.items():
400
- if isinstance(transform, str):
401
- new_names.append(transform)
402
- elif isinstance(transform, ArgTransform) and not transform.hide:
403
- if transform.name is not ... and transform.name is not None:
404
  new_names.append(transform.name)
405
  else:
406
  new_names.append(old_name)
@@ -421,7 +383,7 @@ class TransformedTool(Tool):
421
 
422
  final_description = description if description is not None else tool.description
423
 
424
- return cls(
425
  fn=final_fn,
426
  forwarding_fn=forwarding_fn,
427
  parent_tool=tool,
@@ -431,13 +393,16 @@ class TransformedTool(Tool):
431
  tags=tags or tool.tags,
432
  annotations=annotations or tool.annotations,
433
  serializer=serializer or tool.serializer,
 
434
  )
435
 
 
 
436
  @classmethod
437
  def _create_forwarding_transform(
438
  cls,
439
  parent_tool: Tool,
440
- transform_args: dict[str, str | ArgTransform | None] | None,
441
  ) -> tuple[dict[str, Any], Callable[..., Any]]:
442
  """Create schema and forwarding function that encapsulates all transformation logic.
443
 
@@ -469,20 +434,25 @@ class TransformedTool(Tool):
469
  if transform_args and old_name in transform_args:
470
  transform = transform_args[old_name]
471
  else:
472
- transform = ... # Default behavior - pass through
 
473
 
474
  # Handle hidden parameters with defaults
475
- if isinstance(transform, ArgTransform) and transform.hide:
476
  # Validate that hidden parameters without user defaults have parent defaults
477
- if transform.default is ... and old_name in parent_required:
 
 
 
 
478
  raise ValueError(
479
  f"Hidden parameter '{old_name}' has no default value in parent tool "
480
- f"and no default provided in ArgTransform. Either provide a default "
481
- f"in ArgTransform or don't hide required parameters."
482
  )
483
- if transform.default is not ...:
484
- # Hidden parameter with a constant value
485
- hidden_defaults[old_name] = transform.default
486
  # Skip adding to schema (not exposed to clients)
487
  continue
488
 
@@ -532,7 +502,13 @@ class TransformedTool(Tool):
532
  parent_args[old_name] = value
533
 
534
  # Add hidden defaults (constant values for hidden parameters)
535
- parent_args.update(hidden_defaults)
 
 
 
 
 
 
536
 
537
  return await parent_tool.run(parent_args)
538
 
@@ -542,7 +518,7 @@ class TransformedTool(Tool):
542
  def _apply_single_transform(
543
  old_name: str,
544
  old_schema: dict[str, Any],
545
- transform: str | ArgTransform | None | EllipsisType,
546
  is_required: bool,
547
  ) -> tuple[str, dict[str, Any], bool] | None:
548
  """Apply transformation to a single parameter.
@@ -553,49 +529,55 @@ class TransformedTool(Tool):
553
  Args:
554
  old_name: Original name of the parameter.
555
  old_schema: Original JSON schema for the parameter.
556
- transform: Transformation to apply (string for rename, ArgTransform for complex,
557
- None to drop, ... to pass through unchanged).
558
  is_required: Whether the original parameter was required.
559
 
560
  Returns:
561
  Tuple of (new_name, new_schema, new_is_required) if parameter should be kept,
562
  None if parameter should be dropped.
563
  """
564
- if transform is ...:
565
- # Not in transform_args - pass through
566
- return old_name, old_schema.copy(), is_required
567
- elif transform is None:
568
- # Explicitly set to None in transform_args - drop the parameter
569
  return None
570
 
571
- if isinstance(transform, str):
572
- # Simple rename
573
- return transform, old_schema.copy(), is_required
 
 
574
 
575
- if isinstance(transform, ArgTransform):
576
- if transform.hide:
577
- return None
578
 
579
- if transform.name is not ...:
580
- new_name = transform.name or old_name # Handle None case
581
- else:
582
- new_name = old_name
583
- new_schema = old_schema.copy()
584
 
585
- if transform.description is not ...:
 
 
 
 
586
  new_schema["description"] = transform.description
587
- if transform.default is not ...:
588
- new_schema["default"] = transform.default
589
- is_required = False
590
- if transform.type is not ...:
591
- # Use TypeAdapter to get proper JSON schema for the type
592
- type_schema = get_cached_typeadapter(transform.type).json_schema()
593
- # Update the schema with the type information from TypeAdapter
594
- new_schema.update(type_schema)
595
-
596
- return new_name, new_schema, is_required # type: ignore[return-value]
597
-
598
- raise ValueError(f"Invalid transform: {transform}")
 
 
 
 
 
 
 
 
 
599
 
600
  @staticmethod
601
  def _merge_schema_with_precedence(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
  import inspect
 
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(
 
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'
 
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
 
 
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
 
172
  class TransformedTool(Tool):
 
188
  validation when forward() is called from custom functions.
189
  """
190
 
191
+ model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
192
+
193
  parent_tool: Tool
194
  fn: Callable[..., Any]
195
  forwarding_fn: Callable[..., Any] # Always present, handles arg transformation
196
+ transform_args: dict[str, ArgTransform]
197
 
198
  async def run(
199
  self, arguments: dict[str, Any]
 
220
 
221
  for param_name, param_schema in properties.items():
222
  if param_name not in arguments and "default" in param_schema:
223
+ # Check if this parameter has a default_factory from transform_args
224
+ # We need to call the factory for each run, not use the cached schema value
225
+ has_factory_default = False
226
+ if self.transform_args:
227
+ # Find the original parameter name that maps to this param_name
228
+ for orig_name, transform in self.transform_args.items():
229
+ transform_name = (
230
+ transform.name
231
+ if transform.name is not NotSet
232
+ else orig_name
233
+ )
234
+ if (
235
+ transform_name == param_name
236
+ and transform.default_factory is not NotSet
237
+ ):
238
+ # Type check to ensure default_factory is callable
239
+ if callable(transform.default_factory):
240
+ arguments[param_name] = transform.default_factory()
241
+ has_factory_default = True
242
+ break
243
+
244
+ if not has_factory_default:
245
+ arguments[param_name] = param_schema["default"]
246
 
247
  token = _current_tool.set(self)
248
  try:
 
255
  def from_tool(
256
  cls,
257
  tool: Tool,
 
258
  name: str | None = None,
 
259
  description: str | None = None,
260
  tags: set[str] | None = None,
261
+ transform_fn: Callable[..., Any] | None = None,
262
+ transform_args: dict[str, ArgTransform] | None = None,
263
  annotations: ToolAnnotations | None = None,
264
  serializer: Callable[[Any], str] | None = None,
265
  ) -> TransformedTool:
 
302
 
303
  Tool.from_tool(parent, transform_fn=flexible, transform_args={"a": "x"})
304
  """
305
+ transform_args = transform_args or {}
306
+
307
+ # Validate transform_args
308
+ parent_params = set(tool.parameters.get("properties", {}).keys())
309
+ unknown_args = set(transform_args.keys()) - parent_params
310
+ if unknown_args:
311
+ raise ValueError(
312
+ f"Unknown arguments in transform_args: {', '.join(sorted(unknown_args))}. "
313
+ f"Parent tool has: {', '.join(sorted(parent_params))}"
314
+ )
315
 
316
  # Always create the forwarding transform
317
  schema, forwarding_fn = cls._create_forwarding_transform(tool, transform_args)
 
361
  if transform_args:
362
  new_names = []
363
  for old_name, transform in transform_args.items():
364
+ if not transform.hide:
365
+ if transform.name is not NotSet:
 
 
366
  new_names.append(transform.name)
367
  else:
368
  new_names.append(old_name)
 
383
 
384
  final_description = description if description is not None else tool.description
385
 
386
+ transformed_tool = cls(
387
  fn=final_fn,
388
  forwarding_fn=forwarding_fn,
389
  parent_tool=tool,
 
393
  tags=tags or tool.tags,
394
  annotations=annotations or tool.annotations,
395
  serializer=serializer or tool.serializer,
396
+ transform_args=transform_args,
397
  )
398
 
399
+ return transformed_tool
400
+
401
  @classmethod
402
  def _create_forwarding_transform(
403
  cls,
404
  parent_tool: Tool,
405
+ transform_args: dict[str, ArgTransform] | None,
406
  ) -> tuple[dict[str, Any], Callable[..., Any]]:
407
  """Create schema and forwarding function that encapsulates all transformation logic.
408
 
 
434
  if transform_args and old_name in transform_args:
435
  transform = transform_args[old_name]
436
  else:
437
+ # Default behavior - pass through (no transformation)
438
+ transform = ArgTransform() # Default ArgTransform with no changes
439
 
440
  # Handle hidden parameters with defaults
441
+ if transform.hide:
442
  # Validate that hidden parameters without user defaults have parent defaults
443
+ has_user_default = (
444
+ transform.default is not NotSet
445
+ or transform.default_factory is not NotSet
446
+ )
447
+ if not has_user_default and old_name in parent_required:
448
  raise ValueError(
449
  f"Hidden parameter '{old_name}' has no default value in parent tool "
450
+ f"and no default or default_factory provided in ArgTransform. Either provide a default "
451
+ f"or default_factory in ArgTransform or don't hide required parameters."
452
  )
453
+ if has_user_default:
454
+ # Store info for later factory calling or direct value
455
+ hidden_defaults[old_name] = transform
456
  # Skip adding to schema (not exposed to clients)
457
  continue
458
 
 
502
  parent_args[old_name] = value
503
 
504
  # Add hidden defaults (constant values for hidden parameters)
505
+ for old_name, transform in hidden_defaults.items():
506
+ if transform.default is not NotSet:
507
+ parent_args[old_name] = transform.default
508
+ elif transform.default_factory is not NotSet:
509
+ # Type check to ensure default_factory is callable
510
+ if callable(transform.default_factory):
511
+ parent_args[old_name] = transform.default_factory()
512
 
513
  return await parent_tool.run(parent_args)
514
 
 
518
  def _apply_single_transform(
519
  old_name: str,
520
  old_schema: dict[str, Any],
521
+ transform: ArgTransform,
522
  is_required: bool,
523
  ) -> tuple[str, dict[str, Any], bool] | None:
524
  """Apply transformation to a single parameter.
 
529
  Args:
530
  old_name: Original name of the parameter.
531
  old_schema: Original JSON schema for the parameter.
532
+ transform: ArgTransform object specifying how to transform the parameter.
 
533
  is_required: Whether the original parameter was required.
534
 
535
  Returns:
536
  Tuple of (new_name, new_schema, new_is_required) if parameter should be kept,
537
  None if parameter should be dropped.
538
  """
539
+ if transform.hide:
 
 
 
 
540
  return None
541
 
542
+ # Handle name transformation - ensure we always have a string
543
+ if transform.name is not NotSet:
544
+ new_name = transform.name if transform.name is not None else old_name
545
+ else:
546
+ new_name = old_name
547
 
548
+ # Ensure new_name is always a string
549
+ if not isinstance(new_name, str):
550
+ new_name = old_name
551
 
552
+ new_schema = old_schema.copy()
 
 
 
 
553
 
554
+ # Handle description transformation
555
+ if transform.description is not NotSet:
556
+ if transform.description is None:
557
+ new_schema.pop("description", None) # Remove description
558
+ else:
559
  new_schema["description"] = transform.description
560
+
561
+ # Handle required transformation first
562
+ if transform.required is not NotSet:
563
+ is_required = bool(transform.required)
564
+ if transform.required is True:
565
+ # Remove any existing default when making required
566
+ new_schema.pop("default", None)
567
+
568
+ # Handle default value transformation (only if not making required)
569
+ if transform.default is not NotSet and transform.required is not True:
570
+ new_schema["default"] = transform.default
571
+ is_required = False
572
+
573
+ # Handle type transformation
574
+ if transform.type is not NotSet:
575
+ # Use TypeAdapter to get proper JSON schema for the type
576
+ type_schema = get_cached_typeadapter(transform.type).json_schema()
577
+ # Update the schema with the type information from TypeAdapter
578
+ new_schema.update(type_schema)
579
+
580
+ return new_name, new_schema, is_required
581
 
582
  @staticmethod
583
  def _merge_schema_with_precedence(
tests/tools/test_tool_transform.py CHANGED
@@ -37,35 +37,32 @@ def test_tool_from_tool_no_change(add_tool):
37
  assert new_tool.description == add_tool.description
38
 
39
 
40
- async def test_tool_change_arg_name_with_string(add_tool):
41
- new_tool = Tool.from_tool(add_tool, transform_args={"old_x": "new_x"})
42
-
43
- assert sorted(new_tool.parameters["properties"]) == ["new_x", "old_y"]
44
- assert get_property(new_tool, "new_x") == get_property(add_tool, "old_x")
45
- assert get_property(new_tool, "old_y") == get_property(add_tool, "old_y")
46
- assert new_tool.parameters["required"] == ["new_x"]
47
- result = await new_tool.run(arguments={"new_x": 1, "old_y": 2})
48
- assert result[0].text == "3" # type: ignore
49
-
50
-
51
  async def test_renamed_arg_description_is_maintained(add_tool):
52
- new_tool = Tool.from_tool(add_tool, transform_args={"old_x": "new_x"})
53
- assert get_property(new_tool, "new_x")["description"] == "old_x description"
 
 
 
 
54
 
55
 
56
  async def test_tool_defaults_are_maintained_on_unmapped_args(add_tool):
57
- new_tool = Tool.from_tool(add_tool, transform_args={"old_x": "new_x"})
 
 
58
  result = await new_tool.run(arguments={"new_x": 1})
59
  assert result[0].text == "11" # type: ignore
60
 
61
 
62
  async def test_tool_defaults_are_maintained_on_mapped_args(add_tool):
63
- new_tool = Tool.from_tool(add_tool, transform_args={"old_y": "new_y"})
 
 
64
  result = await new_tool.run(arguments={"old_x": 1})
65
  assert result[0].text == "11" # type: ignore
66
 
67
 
68
- def test_tool_change_arg_name_with_arg_transform(add_tool):
69
  new_tool = Tool.from_tool(
70
  add_tool, transform_args={"old_x": ArgTransform(name="new_x")}
71
  )
@@ -83,15 +80,7 @@ def test_tool_change_arg_description(add_tool):
83
  assert get_property(new_tool, "old_x")["description"] == "new description"
84
 
85
 
86
- async def test_tool_drop_arg_with_none(add_tool):
87
- # drop the arg with a default value
88
- new_tool = Tool.from_tool(add_tool, transform_args={"old_y": None})
89
- assert sorted(new_tool.parameters["properties"]) == ["old_x"]
90
- result = await new_tool.run(arguments={"old_x": 1})
91
- assert result[0].text == "11" # type: ignore
92
-
93
-
94
- async def test_tool_drop_arg_with_arg_transform(add_tool):
95
  new_tool = Tool.from_tool(
96
  add_tool, transform_args={"old_y": ArgTransform(hide=True)}
97
  )
@@ -147,7 +136,7 @@ async def test_mixed_hidden_args_with_custom_function(add_tool):
147
  add_tool,
148
  transform_fn=custom_fn,
149
  transform_args={
150
- "old_x": "visible_x", # Rename and expose
151
  "old_y": ArgTransform(hide=True, default=25), # Hidden with constant
152
  },
153
  )
@@ -206,7 +195,10 @@ async def test_forward_with_argument_mapping(add_tool):
206
  new_tool = Tool.from_tool(
207
  add_tool,
208
  transform_fn=custom_fn,
209
- transform_args={"old_x": "new_x", "old_y": "new_y"},
 
 
 
210
  )
211
 
212
  result = await new_tool.run(arguments={"new_x": 2, "new_y": 3})
@@ -221,7 +213,10 @@ async def test_forward_with_incorrect_args_raises_error(add_tool):
221
  new_tool = Tool.from_tool(
222
  add_tool,
223
  transform_fn=custom_fn,
224
- transform_args={"old_x": "new_x", "old_y": "new_y"},
 
 
 
225
  )
226
  with pytest.raises(
227
  TypeError, match=re.escape("Got unexpected keyword argument(s): old_x, old_y")
@@ -240,7 +235,10 @@ async def test_forward_raw_without_argument_mapping(add_tool):
240
  new_tool = Tool.from_tool(
241
  add_tool,
242
  transform_fn=custom_fn,
243
- transform_args={"old_x": "new_x", "old_y": "new_y"},
 
 
 
244
  )
245
 
246
  result = await new_tool.run(arguments={"new_x": 2, "new_y": 3})
@@ -284,7 +282,9 @@ async def test_fn_with_kwargs_receives_transformed_arg_names(add_tool):
284
  return result
285
 
286
  new_tool = Tool.from_tool(
287
- add_tool, transform_fn=custom_fn, transform_args={"old_x": "new_x"}
 
 
288
  )
289
  result = await new_tool.run(arguments={"new_x": 2, "old_y": 3})
290
  assert result[0].text == "5" # type: ignore
@@ -300,7 +300,9 @@ async def test_fn_with_kwargs_handles_partial_explicit_args(add_tool):
300
  return result
301
 
302
  new_tool = Tool.from_tool(
303
- add_tool, transform_fn=custom_fn, transform_args={"old_x": "new_x"}
 
 
304
  )
305
  result = await new_tool.run(
306
  arguments={"new_x": 3, "old_y": 7, "some_other_param": "test"}
@@ -318,7 +320,9 @@ async def test_fn_with_kwargs_mixed_mapped_and_unmapped_args(add_tool):
318
  return result
319
 
320
  new_tool = Tool.from_tool(
321
- add_tool, transform_fn=custom_fn, transform_args={"old_x": "new_x"}
 
 
322
  ) # only map 'a'
323
  result = await new_tool.run(arguments={"new_x": 1, "old_y": 5})
324
  assert result[0].text == "6" # type: ignore
@@ -337,7 +341,10 @@ async def test_fn_with_kwargs_dropped_args_not_in_kwargs(add_tool):
337
  new_tool = Tool.from_tool(
338
  add_tool,
339
  transform_fn=custom_fn,
340
- transform_args={"old_x": "new_x", "old_y": None},
 
 
 
341
  ) # drop 'old_y'
342
  result = await new_tool.run(arguments={"new_x": 8})
343
  # 8 + 10 (default value of b in parent)
@@ -366,22 +373,13 @@ def test_transform_args_validation_unknown_arg(add_tool):
366
  """Test that transform_args with unknown arguments raises ValueError."""
367
  with pytest.raises(
368
  ValueError, match="Unknown arguments in transform_args: unknown_param"
369
- ):
370
- Tool.from_tool(add_tool, transform_args={"unknown_param": "new_name"})
371
-
372
-
373
- def test_transform_args_creates_duplicate_names(add_tool):
374
- """Test that transform_args creating duplicate parameter names raises ValueError."""
375
- with pytest.raises(
376
- ValueError,
377
- match="Multiple arguments would be mapped to the same names: same_name",
378
  ):
379
  Tool.from_tool(
380
- add_tool, transform_args={"old_x": "same_name", "old_y": "same_name"}
381
  )
382
 
383
 
384
- def test_transform_args_creates_duplicate_names_with_arg_transform(add_tool):
385
  """Test that transform_args creating duplicate parameter names raises ValueError."""
386
  with pytest.raises(
387
  ValueError,
@@ -391,16 +389,16 @@ def test_transform_args_creates_duplicate_names_with_arg_transform(add_tool):
391
  add_tool,
392
  transform_args={
393
  "old_x": ArgTransform(name="same_name"),
394
- "old_y": "same_name",
395
  },
396
  )
397
 
398
 
399
  def test_function_without_kwargs_missing_params(add_tool):
400
- """Test that function without **kwargs must declare all transformed params."""
401
 
402
  def invalid_fn(new_x: int, non_existent: str) -> str:
403
- return "test"
404
 
405
  with pytest.raises(
406
  ValueError,
@@ -409,27 +407,33 @@ def test_function_without_kwargs_missing_params(add_tool):
409
  Tool.from_tool(
410
  add_tool,
411
  transform_fn=invalid_fn,
412
- transform_args={"old_x": "new_x", "old_y": "new_y"},
 
 
 
413
  )
414
 
415
 
416
  def test_function_without_kwargs_can_have_extra_params(add_tool):
417
- """Test that function without **kwargs can declare extra params beyond transformed ones."""
418
 
419
  def valid_fn(new_x: int, new_y: int, extra_param: str = "default") -> str:
420
- return f"{new_x + new_y}: {extra_param}"
421
 
422
- # This should work fine - function declares all required params plus an extra one
423
- tool = Tool.from_tool(
424
  add_tool,
425
  transform_fn=valid_fn,
426
- transform_args={"old_x": "new_x", "old_y": "new_y"},
 
 
 
427
  )
428
 
429
  # The final schema should include all function parameters
430
- assert "new_x" in tool.parameters["properties"]
431
- assert "new_y" in tool.parameters["properties"]
432
- assert "extra_param" in tool.parameters["properties"]
433
 
434
 
435
  def test_function_with_kwargs_can_add_params(add_tool):
@@ -443,7 +447,10 @@ def test_function_with_kwargs_can_add_params(add_tool):
443
  tool = Tool.from_tool(
444
  add_tool,
445
  transform_fn=valid_fn,
446
- transform_args={"old_x": "new_x", "old_y": "new_y"},
 
 
 
447
  )
448
 
449
  # extra_param is added, new_x and new_y are available
@@ -452,28 +459,27 @@ def test_function_with_kwargs_can_add_params(add_tool):
452
  assert "new_y" in tool.parameters["properties"]
453
 
454
 
455
- async def test_chaining_transformations(add_tool):
456
  """Test that transformed tools can be transformed again."""
457
- # First transformation
458
- tool1 = Tool.from_tool(add_tool, transform_args={"old_x": "x"})
459
-
460
- # Second transformation on the already-transformed tool
461
- tool2 = Tool.from_tool(tool1, transform_args={"x": "final_x"})
462
 
463
- # Should work with the final names
464
- result = await tool2.run(arguments={"final_x": 5, "old_y": 3})
465
- assert result[0].text == "8" # type: ignore
466
 
467
- # And forward() in a custom function should work
468
- async def custom(final_x: int, old_y: int) -> str:
469
- # forward() goes to tool1, which has 'final_x' and 'old_y' after transformation
470
- result = await forward(final_x=final_x, old_y=old_y)
471
- return f"Chained: {result}"
472
 
473
- tool3 = Tool.from_tool(tool1, transform_fn=custom, transform_args={"x": "final_x"})
 
 
 
474
 
475
- result = await tool3.run(arguments={"final_x": 5, "old_y": 3})
476
- assert "Chained:" in result[0].text # type: ignore
 
 
 
477
 
478
 
479
  class MyModel(BaseModel):
@@ -712,7 +718,9 @@ class TestProxy:
712
 
713
  add_tool = await proxy_server.get_tool("add")
714
  new_add_tool = Tool.from_tool(
715
- add_tool, name="add_transformed", transform_args={"old_x": "new_x"}
 
 
716
  )
717
  proxy_server.add_tool(new_add_tool)
718
 
@@ -720,3 +728,226 @@ class TestProxy:
720
  # The tool should be registered with its transformed name
721
  result = await client.call_tool("add_transformed", {"new_x": 1, "old_y": 2})
722
  assert result[0].text == "3" # type: ignore
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
  )
 
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
  )
 
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
  )
 
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})
 
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")
 
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})
 
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
 
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"}
 
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
 
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)
 
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,
 
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,
 
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):
 
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
 
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):
 
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
 
 
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
+ # Make the required parameter optional with a default
862
+ new_tool = Tool.from_tool(
863
+ base_tool,
864
+ transform_args={"required_param": ArgTransform(required=False, default=99)},
865
+ )
866
+
867
+ # Parameter should now be optional (not in required list, has default)
868
+ assert "required_param" not in new_tool.parameters["required"]
869
+ assert new_tool.parameters["properties"]["required_param"]["default"] == 99
870
+
871
+ # Should work when parameter is not provided (uses default)
872
+ result = await new_tool.run(arguments={})
873
+ assert result[0].text == "value: 99" # type: ignore
874
+
875
+ # Should work when parameter is provided
876
+ result = await new_tool.run(arguments={"required_param": 123})
877
+ assert result[0].text == "value: 123" # type: ignore
878
+
879
+
880
+ async def test_arg_transform_required_with_rename():
881
+ """Test that required works correctly with argument renaming."""
882
+
883
+ @Tool.from_function
884
+ def base_tool(optional_param: int = 42) -> str:
885
+ return f"value: {optional_param}"
886
+
887
+ # Rename and make required
888
+ new_tool = Tool.from_tool(
889
+ base_tool,
890
+ transform_args={
891
+ "optional_param": ArgTransform(name="new_param", required=True)
892
+ },
893
+ )
894
+
895
+ # New parameter name should be required
896
+ assert "new_param" in new_tool.parameters["required"]
897
+ assert "optional_param" not in new_tool.parameters["properties"]
898
+ assert "new_param" in new_tool.parameters["properties"]
899
+ assert "default" not in new_tool.parameters["properties"]["new_param"]
900
+
901
+ # Should work with new name
902
+ result = await new_tool.run(arguments={"new_param": 200})
903
+ assert result[0].text == "value: 200" # type: ignore
904
+
905
+
906
+ async def test_arg_transform_required_true_with_default_raises_error():
907
+ """Test that required=True with default raises an error."""
908
+ with pytest.raises(
909
+ ValueError, match="Cannot specify 'required=True' with 'default'"
910
+ ):
911
+ ArgTransform(required=True, default=42)
912
+
913
+
914
+ async def test_arg_transform_required_true_with_factory_raises_error():
915
+ """Test that required=True with default_factory raises an error."""
916
+ with pytest.raises(
917
+ ValueError, match="default_factory can only be used with hide=True"
918
+ ):
919
+ ArgTransform(required=True, default_factory=lambda: 42)
920
+
921
+
922
+ async def test_arg_transform_required_no_change():
923
+ """Test that required=... (NotSet) leaves requirement status unchanged."""
924
+
925
+ @Tool.from_function
926
+ def base_tool(required_param: int, optional_param: int = 42) -> str:
927
+ return f"values: {required_param}, {optional_param}"
928
+
929
+ # Transform without changing required status
930
+ new_tool = Tool.from_tool(
931
+ base_tool,
932
+ transform_args={
933
+ "required_param": ArgTransform(name="req"),
934
+ "optional_param": ArgTransform(name="opt"),
935
+ },
936
+ )
937
+
938
+ # Required status should be unchanged
939
+ assert "req" in new_tool.parameters["required"]
940
+ assert "opt" not in new_tool.parameters["required"]
941
+ assert new_tool.parameters["properties"]["opt"]["default"] == 42
942
+
943
+ # Should work as expected
944
+ result = await new_tool.run(arguments={"req": 1})
945
+ assert result[0].text == "values: 1, 42" # type: ignore
946
+
947
+
948
+ async def test_arg_transform_hide_and_required_raises_error():
949
+ """Test that hide=True and required=True together raises an error."""
950
+ with pytest.raises(
951
+ ValueError, match="Cannot specify both 'hide=True' and 'required=True'"
952
+ ):
953
+ ArgTransform(hide=True, required=True)