Skip to content

tools

Tool

Bases: BaseModel

Internal tool registration info.

Source code in src/mcp/server/mcpserver/tools/base.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class Tool(BaseModel):
    """Internal tool registration info."""

    fn: Callable[..., Any] = Field(exclude=True)
    name: str = Field(description="Name of the tool")
    title: str | None = Field(None, description="Human-readable title of the tool")
    description: str = Field(description="Description of what the tool does")
    parameters: dict[str, Any] = Field(description="JSON schema for tool parameters")
    fn_metadata: FuncMetadata = Field(
        description="Metadata about the function including a pydantic model for tool arguments"
    )
    is_async: bool = Field(description="Whether the tool is async")
    context_kwarg: str | None = Field(None, description="Name of the kwarg that should receive context")
    resolved_params: dict[str, Any] = Field(
        default_factory=lambda: {},
        exclude=True,
        description="Parameters filled by resolvers, mapped to (Resolve, wants_union)",
    )
    resolver_plans: dict[Hashable, Any] = Field(
        default_factory=lambda: {}, exclude=True, description="Static per-resolver parameter plans"
    )
    annotations: ToolAnnotations | None = Field(None, description="Optional annotations for the tool")
    icons: list[Icon] | None = Field(default=None, description="Optional list of icons for this tool")
    meta: dict[str, Any] | None = Field(default=None, description="Optional metadata for this tool")

    @cached_property
    def output_schema(self) -> dict[str, Any] | None:
        return self.fn_metadata.output_schema

    @classmethod
    def from_function(
        cls,
        fn: Callable[..., Any],
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        context_kwarg: str | None = None,
        annotations: ToolAnnotations | None = None,
        icons: list[Icon] | None = None,
        meta: dict[str, Any] | None = None,
        structured_output: bool | None = None,
    ) -> Tool:
        """Create a Tool from a function."""
        func_name = name or fn.__name__

        validate_and_warn_tool_name(func_name)

        if func_name == "<lambda>":
            raise ValueError("You must provide a name for lambda functions")

        func_doc = description or fn.__doc__ or ""
        is_async = is_async_callable(fn)

        if context_kwarg is None:  # pragma: no branch
            context_kwarg = find_context_parameter(fn)

        resolved_params = find_resolved_parameters(fn)
        if resolved_params and returns_input_required(fn):
            raise InvalidSignature(
                f"Tool {func_name!r} combines Resolve(...) parameters with an InputRequiredResult "
                "return; a call has one input_required channel, so the multi-round flow is driven "
                "either by resolvers or by the tool body, not both"
            )

        skip_names = [context_kwarg] if context_kwarg is not None else []
        skip_names.extend(resolved_params)

        func_arg_metadata = func_metadata(
            fn,
            skip_names=skip_names,
            structured_output=structured_output,
        )
        parameters = func_arg_metadata.arg_model.model_json_schema(by_alias=True)

        # Match `model_dump_one_level`'s kwarg keys (alias when present, else field name)
        # so a by-name resolver param resolves to a key that exists at call time.
        tool_arg_names = {field.alias or name for name, field in func_arg_metadata.arg_model.model_fields.items()}
        resolver_plans = build_resolver_plans(resolved_params, tool_arg_names)

        return cls(
            fn=fn,
            name=func_name,
            title=title,
            description=func_doc,
            parameters=parameters,
            fn_metadata=func_arg_metadata,
            is_async=is_async,
            context_kwarg=context_kwarg,
            resolved_params=dict(resolved_params),
            resolver_plans=resolver_plans,
            annotations=annotations,
            icons=icons,
            meta=meta,
        )

    async def run(
        self,
        arguments: dict[str, Any],
        context: Context[LifespanContextT, RequestT],
        convert_result: bool = False,
    ) -> Any:
        """Run the tool with arguments.

        Every failure other than `MCPError` is raised as a `ToolError` whose message
        starts `Error executing tool <name>` and whose `__cause__` is what was raised.
        An anticipated failure keeps its own text after the prefix. A crash does not,
        so nothing from an unexpected exception reaches the client.

        Raises:
            ToolError: If the arguments fail validation against the input schema, or
                the tool function (or a resolver) raises `ToolError` or `ResourceError`.
            UnexpectedToolError: If argument validation, the tool function, or a
                resolver raises anything else, or the return value fails output conversion.
        """
        try:
            validated = self.fn_metadata.validate_arguments(arguments)
        except ValidationError as exc:
            # The caller's arguments don't match the input schema: the model's mistake
            # to read and correct, so it is reported like a deliberate ToolError.
            raise ToolError(f"Error executing tool {self.name}: {exc}") from exc
        except MCPError:
            raise
        except Exception as exc:
            # A custom validator or default_factory that raises is a crash.
            raise UnexpectedToolError(f"Error executing tool {self.name}") from exc

        try:
            pass_directly: dict[str, Any] = {}
            if self.context_kwarg is not None:
                pass_directly[self.context_kwarg] = context

            # Resolvers see the same validated arguments the tool body receives, so a
            # `default_factory`/stateful validator can't hand a by-name resolver a
            # different value than the body.
            if self.resolved_params:
                resolved = await resolve_arguments(self.resolved_params, self.resolver_plans, validated, context)
                if isinstance(resolved, InputRequiredResult):
                    # A resolver still needs client input (>= 2026-07-28): surface the
                    # batched questions instead of running the tool body this round.
                    return self.fn_metadata.convert_result(resolved) if convert_result else resolved
                pass_directly |= resolved

            result = await self.fn_metadata.call_fn_with_arg_validation(
                self.fn,
                self.is_async,
                arguments,
                pass_directly or None,
                pre_validated=validated,
            )

            # Registration rejects the annotated form of this combination; this covers
            # a body that returns an InputRequiredResult without declaring it. It is
            # an authoring bug, so it is raised as a crash rather than a ToolError.
            if self.resolved_params and isinstance(result, InputRequiredResult):
                raise RuntimeError(
                    "the tool returned an InputRequiredResult but its parameters use Resolve(...); "
                    "a call has one input_required channel, so the multi-round flow is driven "
                    "either by resolvers or by the tool body, not both"
                )

            if convert_result:
                result = self.fn_metadata.convert_result(result)

            return result
        except MCPError:
            # `MCPError` (and subclasses such as `UrlElicitationRequiredError`)
            # carries a JSON-RPC `ErrorData(code, message, data)` and means
            # "respond with a protocol error" - re-raise so the kernel surfaces
            # it as a top-level JSON-RPC error rather than wrapping it as a
            # `CallToolResult(isError=True)` execution failure.
            raise
        # Everything else reaches the model as an is_error result under this tool's
        # name, and the wrapper's type tells the server whether to log a crash.
        except (UnexpectedToolError, UnexpectedResourceError) as exc:
            # A nested tool call or resource read crashed: still a crash here. Its
            # message is already the generic one, so it is safe to carry along.
            raise UnexpectedToolError(f"Error executing tool {self.name}: {exc}") from exc
        except (ToolError, ResourceError) as exc:
            # Raised deliberately by the tool, a resolver, or a resource it read.
            raise ToolError(f"Error executing tool {self.name}: {exc}") from exc
        except Exception as exc:
            # A crash: the exception's own text stays on the server.
            raise UnexpectedToolError(f"Error executing tool {self.name}") from exc

from_function classmethod

from_function(
    fn: Callable[..., Any],
    name: str | None = None,
    title: str | None = None,
    description: str | None = None,
    context_kwarg: str | None = None,
    annotations: ToolAnnotations | None = None,
    icons: list[Icon] | None = None,
    meta: dict[str, Any] | None = None,
    structured_output: bool | None = None,
) -> Tool

Create a Tool from a function.

Source code in src/mcp/server/mcpserver/tools/base.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@classmethod
def from_function(
    cls,
    fn: Callable[..., Any],
    name: str | None = None,
    title: str | None = None,
    description: str | None = None,
    context_kwarg: str | None = None,
    annotations: ToolAnnotations | None = None,
    icons: list[Icon] | None = None,
    meta: dict[str, Any] | None = None,
    structured_output: bool | None = None,
) -> Tool:
    """Create a Tool from a function."""
    func_name = name or fn.__name__

    validate_and_warn_tool_name(func_name)

    if func_name == "<lambda>":
        raise ValueError("You must provide a name for lambda functions")

    func_doc = description or fn.__doc__ or ""
    is_async = is_async_callable(fn)

    if context_kwarg is None:  # pragma: no branch
        context_kwarg = find_context_parameter(fn)

    resolved_params = find_resolved_parameters(fn)
    if resolved_params and returns_input_required(fn):
        raise InvalidSignature(
            f"Tool {func_name!r} combines Resolve(...) parameters with an InputRequiredResult "
            "return; a call has one input_required channel, so the multi-round flow is driven "
            "either by resolvers or by the tool body, not both"
        )

    skip_names = [context_kwarg] if context_kwarg is not None else []
    skip_names.extend(resolved_params)

    func_arg_metadata = func_metadata(
        fn,
        skip_names=skip_names,
        structured_output=structured_output,
    )
    parameters = func_arg_metadata.arg_model.model_json_schema(by_alias=True)

    # Match `model_dump_one_level`'s kwarg keys (alias when present, else field name)
    # so a by-name resolver param resolves to a key that exists at call time.
    tool_arg_names = {field.alias or name for name, field in func_arg_metadata.arg_model.model_fields.items()}
    resolver_plans = build_resolver_plans(resolved_params, tool_arg_names)

    return cls(
        fn=fn,
        name=func_name,
        title=title,
        description=func_doc,
        parameters=parameters,
        fn_metadata=func_arg_metadata,
        is_async=is_async,
        context_kwarg=context_kwarg,
        resolved_params=dict(resolved_params),
        resolver_plans=resolver_plans,
        annotations=annotations,
        icons=icons,
        meta=meta,
    )

run async

run(
    arguments: dict[str, Any],
    context: Context[LifespanContextT, RequestT],
    convert_result: bool = False,
) -> Any

Run the tool with arguments.

Every failure other than MCPError is raised as a ToolError whose message starts Error executing tool <name> and whose __cause__ is what was raised. An anticipated failure keeps its own text after the prefix. A crash does not, so nothing from an unexpected exception reaches the client.

Raises:

Type Description
ToolError

If the arguments fail validation against the input schema, or the tool function (or a resolver) raises ToolError or ResourceError.

UnexpectedToolError

If argument validation, the tool function, or a resolver raises anything else, or the return value fails output conversion.

Source code in src/mcp/server/mcpserver/tools/base.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
async def run(
    self,
    arguments: dict[str, Any],
    context: Context[LifespanContextT, RequestT],
    convert_result: bool = False,
) -> Any:
    """Run the tool with arguments.

    Every failure other than `MCPError` is raised as a `ToolError` whose message
    starts `Error executing tool <name>` and whose `__cause__` is what was raised.
    An anticipated failure keeps its own text after the prefix. A crash does not,
    so nothing from an unexpected exception reaches the client.

    Raises:
        ToolError: If the arguments fail validation against the input schema, or
            the tool function (or a resolver) raises `ToolError` or `ResourceError`.
        UnexpectedToolError: If argument validation, the tool function, or a
            resolver raises anything else, or the return value fails output conversion.
    """
    try:
        validated = self.fn_metadata.validate_arguments(arguments)
    except ValidationError as exc:
        # The caller's arguments don't match the input schema: the model's mistake
        # to read and correct, so it is reported like a deliberate ToolError.
        raise ToolError(f"Error executing tool {self.name}: {exc}") from exc
    except MCPError:
        raise
    except Exception as exc:
        # A custom validator or default_factory that raises is a crash.
        raise UnexpectedToolError(f"Error executing tool {self.name}") from exc

    try:
        pass_directly: dict[str, Any] = {}
        if self.context_kwarg is not None:
            pass_directly[self.context_kwarg] = context

        # Resolvers see the same validated arguments the tool body receives, so a
        # `default_factory`/stateful validator can't hand a by-name resolver a
        # different value than the body.
        if self.resolved_params:
            resolved = await resolve_arguments(self.resolved_params, self.resolver_plans, validated, context)
            if isinstance(resolved, InputRequiredResult):
                # A resolver still needs client input (>= 2026-07-28): surface the
                # batched questions instead of running the tool body this round.
                return self.fn_metadata.convert_result(resolved) if convert_result else resolved
            pass_directly |= resolved

        result = await self.fn_metadata.call_fn_with_arg_validation(
            self.fn,
            self.is_async,
            arguments,
            pass_directly or None,
            pre_validated=validated,
        )

        # Registration rejects the annotated form of this combination; this covers
        # a body that returns an InputRequiredResult without declaring it. It is
        # an authoring bug, so it is raised as a crash rather than a ToolError.
        if self.resolved_params and isinstance(result, InputRequiredResult):
            raise RuntimeError(
                "the tool returned an InputRequiredResult but its parameters use Resolve(...); "
                "a call has one input_required channel, so the multi-round flow is driven "
                "either by resolvers or by the tool body, not both"
            )

        if convert_result:
            result = self.fn_metadata.convert_result(result)

        return result
    except MCPError:
        # `MCPError` (and subclasses such as `UrlElicitationRequiredError`)
        # carries a JSON-RPC `ErrorData(code, message, data)` and means
        # "respond with a protocol error" - re-raise so the kernel surfaces
        # it as a top-level JSON-RPC error rather than wrapping it as a
        # `CallToolResult(isError=True)` execution failure.
        raise
    # Everything else reaches the model as an is_error result under this tool's
    # name, and the wrapper's type tells the server whether to log a crash.
    except (UnexpectedToolError, UnexpectedResourceError) as exc:
        # A nested tool call or resource read crashed: still a crash here. Its
        # message is already the generic one, so it is safe to carry along.
        raise UnexpectedToolError(f"Error executing tool {self.name}: {exc}") from exc
    except (ToolError, ResourceError) as exc:
        # Raised deliberately by the tool, a resolver, or a resource it read.
        raise ToolError(f"Error executing tool {self.name}: {exc}") from exc
    except Exception as exc:
        # A crash: the exception's own text stays on the server.
        raise UnexpectedToolError(f"Error executing tool {self.name}") from exc

ToolManager

Manages MCPServer tools.

Source code in src/mcp/server/mcpserver/tools/tool_manager.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class ToolManager:
    """Manages MCPServer tools."""

    def __init__(self, warn_on_duplicate_tools: bool = True, *, tools: list[Tool] | None = None):
        self._tools: dict[str, Tool] = {}
        for tool in tools or ():
            if warn_on_duplicate_tools and tool.name in self._tools:
                logger.warning(f"Tool already exists: {tool.name}")
            self._tools[tool.name] = tool

        self.warn_on_duplicate_tools = warn_on_duplicate_tools

    def get_tool(self, name: str) -> Tool | None:
        """Get tool by name."""
        return self._tools.get(name)

    def list_tools(self) -> list[Tool]:
        """List all registered tools."""
        return list(self._tools.values())

    def add_tool(
        self,
        fn: Callable[..., Any],
        name: str | None = None,
        title: str | None = None,
        description: str | None = None,
        annotations: ToolAnnotations | None = None,
        icons: list[Icon] | None = None,
        meta: dict[str, Any] | None = None,
        structured_output: bool | None = None,
    ) -> Tool:
        """Add a tool to the server."""
        tool = Tool.from_function(
            fn,
            name=name,
            title=title,
            description=description,
            annotations=annotations,
            icons=icons,
            meta=meta,
            structured_output=structured_output,
        )
        existing = self._tools.get(tool.name)
        if existing:
            if self.warn_on_duplicate_tools:
                logger.warning(f"Tool already exists: {tool.name}")
            return existing
        self._tools[tool.name] = tool
        return tool

    def remove_tool(self, name: str) -> None:
        """Remove a tool by name."""
        if name not in self._tools:
            raise ToolError(f"Unknown tool: {name}")
        del self._tools[name]

    async def call_tool(
        self,
        name: str,
        arguments: dict[str, Any],
        context: Context[LifespanContextT, RequestT],
        convert_result: bool = False,
    ) -> Any:
        """Call a tool by name with arguments."""
        tool = self.get_tool(name)
        if not tool:
            raise ToolError(f"Unknown tool: {name}")

        return await tool.run(arguments, context, convert_result=convert_result)

get_tool

get_tool(name: str) -> Tool | None

Get tool by name.

Source code in src/mcp/server/mcpserver/tools/tool_manager.py
31
32
33
def get_tool(self, name: str) -> Tool | None:
    """Get tool by name."""
    return self._tools.get(name)

list_tools

list_tools() -> list[Tool]

List all registered tools.

Source code in src/mcp/server/mcpserver/tools/tool_manager.py
35
36
37
def list_tools(self) -> list[Tool]:
    """List all registered tools."""
    return list(self._tools.values())

add_tool

add_tool(
    fn: Callable[..., Any],
    name: str | None = None,
    title: str | None = None,
    description: str | None = None,
    annotations: ToolAnnotations | None = None,
    icons: list[Icon] | None = None,
    meta: dict[str, Any] | None = None,
    structured_output: bool | None = None,
) -> Tool

Add a tool to the server.

Source code in src/mcp/server/mcpserver/tools/tool_manager.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def add_tool(
    self,
    fn: Callable[..., Any],
    name: str | None = None,
    title: str | None = None,
    description: str | None = None,
    annotations: ToolAnnotations | None = None,
    icons: list[Icon] | None = None,
    meta: dict[str, Any] | None = None,
    structured_output: bool | None = None,
) -> Tool:
    """Add a tool to the server."""
    tool = Tool.from_function(
        fn,
        name=name,
        title=title,
        description=description,
        annotations=annotations,
        icons=icons,
        meta=meta,
        structured_output=structured_output,
    )
    existing = self._tools.get(tool.name)
    if existing:
        if self.warn_on_duplicate_tools:
            logger.warning(f"Tool already exists: {tool.name}")
        return existing
    self._tools[tool.name] = tool
    return tool

remove_tool

remove_tool(name: str) -> None

Remove a tool by name.

Source code in src/mcp/server/mcpserver/tools/tool_manager.py
69
70
71
72
73
def remove_tool(self, name: str) -> None:
    """Remove a tool by name."""
    if name not in self._tools:
        raise ToolError(f"Unknown tool: {name}")
    del self._tools[name]

call_tool async

call_tool(
    name: str,
    arguments: dict[str, Any],
    context: Context[LifespanContextT, RequestT],
    convert_result: bool = False,
) -> Any

Call a tool by name with arguments.

Source code in src/mcp/server/mcpserver/tools/tool_manager.py
75
76
77
78
79
80
81
82
83
84
85
86
87
async def call_tool(
    self,
    name: str,
    arguments: dict[str, Any],
    context: Context[LifespanContextT, RequestT],
    convert_result: bool = False,
) -> Any:
    """Call a tool by name with arguments."""
    tool = self.get_tool(name)
    if not tool:
        raise ToolError(f"Unknown tool: {name}")

    return await tool.run(arguments, context, convert_result=convert_result)