nvidia-nat-mcp 1.3.0a20250910__py3-none-any.whl → 1.5.0a20260117__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nat/meta/pypi.md +3 -3
- nat/plugins/mcp/__init__.py +1 -1
- nat/plugins/mcp/auth/__init__.py +14 -0
- nat/plugins/mcp/auth/auth_flow_handler.py +208 -0
- nat/plugins/mcp/auth/auth_provider.py +431 -0
- nat/plugins/mcp/auth/auth_provider_config.py +87 -0
- nat/plugins/mcp/auth/register.py +33 -0
- nat/plugins/mcp/auth/service_account/__init__.py +14 -0
- nat/plugins/mcp/auth/service_account/provider.py +136 -0
- nat/plugins/mcp/auth/service_account/provider_config.py +137 -0
- nat/plugins/mcp/auth/service_account/token_client.py +156 -0
- nat/plugins/mcp/auth/token_storage.py +265 -0
- nat/plugins/mcp/cli/__init__.py +15 -0
- nat/plugins/mcp/cli/commands.py +1094 -0
- nat/plugins/mcp/client/__init__.py +15 -0
- nat/plugins/mcp/client/client_base.py +665 -0
- nat/plugins/mcp/client/client_config.py +146 -0
- nat/plugins/mcp/client/client_impl.py +782 -0
- nat/plugins/mcp/exception_handler.py +2 -2
- nat/plugins/mcp/exceptions.py +1 -1
- nat/plugins/mcp/register.py +5 -4
- nat/plugins/mcp/server/__init__.py +15 -0
- nat/plugins/mcp/server/front_end_config.py +109 -0
- nat/plugins/mcp/server/front_end_plugin.py +155 -0
- nat/plugins/mcp/server/front_end_plugin_worker.py +415 -0
- nat/plugins/mcp/server/introspection_token_verifier.py +72 -0
- nat/plugins/mcp/server/memory_profiler.py +320 -0
- nat/plugins/mcp/server/register_frontend.py +27 -0
- nat/plugins/mcp/server/tool_converter.py +290 -0
- nat/plugins/mcp/utils.py +228 -0
- {nvidia_nat_mcp-1.3.0a20250910.dist-info → nvidia_nat_mcp-1.5.0a20260117.dist-info}/METADATA +15 -6
- nvidia_nat_mcp-1.5.0a20260117.dist-info/RECORD +37 -0
- nvidia_nat_mcp-1.5.0a20260117.dist-info/entry_points.txt +9 -0
- nvidia_nat_mcp-1.5.0a20260117.dist-info/licenses/LICENSE-3rd-party.txt +5478 -0
- nvidia_nat_mcp-1.5.0a20260117.dist-info/licenses/LICENSE.md +201 -0
- nat/plugins/mcp/client_base.py +0 -406
- nat/plugins/mcp/client_impl.py +0 -229
- nat/plugins/mcp/tool.py +0 -133
- nvidia_nat_mcp-1.3.0a20250910.dist-info/RECORD +0 -13
- nvidia_nat_mcp-1.3.0a20250910.dist-info/entry_points.txt +0 -2
- {nvidia_nat_mcp-1.3.0a20250910.dist-info → nvidia_nat_mcp-1.5.0a20260117.dist-info}/WHEEL +0 -0
- {nvidia_nat_mcp-1.3.0a20250910.dist-info → nvidia_nat_mcp-1.5.0a20260117.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
nat/plugins/mcp/client_base.py
DELETED
|
@@ -1,406 +0,0 @@
|
|
|
1
|
-
# SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
2
|
-
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
-
#
|
|
4
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
# you may not use this file except in compliance with the License.
|
|
6
|
-
# You may obtain a copy of the License at
|
|
7
|
-
#
|
|
8
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
#
|
|
10
|
-
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
# See the License for the specific language governing permissions and
|
|
14
|
-
# limitations under the License.
|
|
15
|
-
|
|
16
|
-
from __future__ import annotations
|
|
17
|
-
|
|
18
|
-
import logging
|
|
19
|
-
from abc import ABC
|
|
20
|
-
from abc import abstractmethod
|
|
21
|
-
from contextlib import AsyncExitStack
|
|
22
|
-
from contextlib import asynccontextmanager
|
|
23
|
-
from enum import Enum
|
|
24
|
-
from typing import Any
|
|
25
|
-
|
|
26
|
-
from pydantic import BaseModel
|
|
27
|
-
from pydantic import Field
|
|
28
|
-
from pydantic import create_model
|
|
29
|
-
|
|
30
|
-
from mcp import ClientSession
|
|
31
|
-
from mcp.client.sse import sse_client
|
|
32
|
-
from mcp.client.stdio import StdioServerParameters
|
|
33
|
-
from mcp.client.stdio import stdio_client
|
|
34
|
-
from mcp.client.streamable_http import streamablehttp_client
|
|
35
|
-
from mcp.types import TextContent
|
|
36
|
-
from nat.plugins.mcp.exception_handler import mcp_exception_handler
|
|
37
|
-
from nat.plugins.mcp.exceptions import MCPToolNotFoundError
|
|
38
|
-
from nat.utils.type_utils import override
|
|
39
|
-
|
|
40
|
-
logger = logging.getLogger(__name__)
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
def model_from_mcp_schema(name: str, mcp_input_schema: dict) -> type[BaseModel]:
|
|
44
|
-
"""
|
|
45
|
-
Create a pydantic model from the input schema of the MCP tool
|
|
46
|
-
"""
|
|
47
|
-
_type_map = {
|
|
48
|
-
"string": str,
|
|
49
|
-
"number": float,
|
|
50
|
-
"integer": int,
|
|
51
|
-
"boolean": bool,
|
|
52
|
-
"array": list,
|
|
53
|
-
"null": None,
|
|
54
|
-
"object": dict,
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
properties = mcp_input_schema.get("properties", {})
|
|
58
|
-
required_fields = set(mcp_input_schema.get("required", []))
|
|
59
|
-
schema_dict = {}
|
|
60
|
-
|
|
61
|
-
def _generate_valid_classname(class_name: str):
|
|
62
|
-
return class_name.replace('_', ' ').replace('-', ' ').title().replace(' ', '')
|
|
63
|
-
|
|
64
|
-
def _generate_field(field_name: str, field_properties: dict[str, Any]) -> tuple:
|
|
65
|
-
json_type = field_properties.get("type", "string")
|
|
66
|
-
enum_vals = field_properties.get("enum")
|
|
67
|
-
|
|
68
|
-
if enum_vals:
|
|
69
|
-
enum_name = f"{field_name.capitalize()}Enum"
|
|
70
|
-
field_type = Enum(enum_name, {item: item for item in enum_vals})
|
|
71
|
-
|
|
72
|
-
elif json_type == "object" and "properties" in field_properties:
|
|
73
|
-
field_type = model_from_mcp_schema(name=field_name, mcp_input_schema=field_properties)
|
|
74
|
-
elif json_type == "array" and "items" in field_properties:
|
|
75
|
-
item_properties = field_properties.get("items", {})
|
|
76
|
-
if item_properties.get("type") == "object":
|
|
77
|
-
item_type = model_from_mcp_schema(name=field_name, mcp_input_schema=item_properties)
|
|
78
|
-
else:
|
|
79
|
-
item_type = _type_map.get(item_properties.get("type", "string"), Any)
|
|
80
|
-
field_type = list[item_type]
|
|
81
|
-
elif isinstance(json_type, list):
|
|
82
|
-
field_type = None
|
|
83
|
-
for t in json_type:
|
|
84
|
-
mapped = _type_map.get(t, Any)
|
|
85
|
-
field_type = mapped if field_type is None else field_type | mapped
|
|
86
|
-
|
|
87
|
-
return field_type, Field(
|
|
88
|
-
default=field_properties.get("default", None if "null" in json_type else ...),
|
|
89
|
-
description=field_properties.get("description", "")
|
|
90
|
-
)
|
|
91
|
-
else:
|
|
92
|
-
field_type = _type_map.get(json_type, Any)
|
|
93
|
-
|
|
94
|
-
# Determine the default value based on whether the field is required
|
|
95
|
-
if field_name in required_fields:
|
|
96
|
-
# Field is required - use explicit default if provided, otherwise make it required
|
|
97
|
-
default_value = field_properties.get("default", ...)
|
|
98
|
-
else:
|
|
99
|
-
# Field is optional - use explicit default if provided, otherwise None
|
|
100
|
-
default_value = field_properties.get("default", None)
|
|
101
|
-
# Make the type optional if no default was provided
|
|
102
|
-
if "default" not in field_properties:
|
|
103
|
-
field_type = field_type | None
|
|
104
|
-
|
|
105
|
-
nullable = field_properties.get("nullable", False)
|
|
106
|
-
description = field_properties.get("description", "")
|
|
107
|
-
|
|
108
|
-
field_type = field_type | None if nullable else field_type
|
|
109
|
-
|
|
110
|
-
return field_type, Field(default=default_value, description=description)
|
|
111
|
-
|
|
112
|
-
for field_name, field_props in properties.items():
|
|
113
|
-
schema_dict[field_name] = _generate_field(field_name=field_name, field_properties=field_props)
|
|
114
|
-
return create_model(f"{_generate_valid_classname(name)}InputSchema", **schema_dict)
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
class MCPBaseClient(ABC):
|
|
118
|
-
"""
|
|
119
|
-
Base client for creating a session and connecting to an MCP server
|
|
120
|
-
|
|
121
|
-
Args:
|
|
122
|
-
transport (str): The type of client to use ('sse', 'stdio', or 'streamable-http')
|
|
123
|
-
"""
|
|
124
|
-
|
|
125
|
-
def __init__(self, transport: str = 'streamable-http'):
|
|
126
|
-
self._tools = None
|
|
127
|
-
self._transport = transport.lower()
|
|
128
|
-
if self._transport not in ['sse', 'stdio', 'streamable-http']:
|
|
129
|
-
raise ValueError("transport must be either 'sse', 'stdio' or 'streamable-http'")
|
|
130
|
-
|
|
131
|
-
self._exit_stack: AsyncExitStack | None = None
|
|
132
|
-
|
|
133
|
-
self._session: ClientSession | None = None
|
|
134
|
-
|
|
135
|
-
@property
|
|
136
|
-
def transport(self) -> str:
|
|
137
|
-
return self._transport
|
|
138
|
-
|
|
139
|
-
async def __aenter__(self):
|
|
140
|
-
if self._exit_stack:
|
|
141
|
-
raise RuntimeError("MCPBaseClient already initialized. Use async with to initialize.")
|
|
142
|
-
|
|
143
|
-
self._exit_stack = AsyncExitStack()
|
|
144
|
-
|
|
145
|
-
self._session = await self._exit_stack.enter_async_context(self.connect_to_server())
|
|
146
|
-
|
|
147
|
-
return self
|
|
148
|
-
|
|
149
|
-
async def __aexit__(self, exc_type, exc_value, traceback):
|
|
150
|
-
|
|
151
|
-
if not self._exit_stack:
|
|
152
|
-
raise RuntimeError("MCPBaseClient not initialized. Use async with to initialize.")
|
|
153
|
-
|
|
154
|
-
await self._exit_stack.aclose()
|
|
155
|
-
self._session = None
|
|
156
|
-
self._exit_stack = None
|
|
157
|
-
|
|
158
|
-
@property
|
|
159
|
-
def server_name(self):
|
|
160
|
-
"""
|
|
161
|
-
Provide server name for logging
|
|
162
|
-
"""
|
|
163
|
-
return self._transport
|
|
164
|
-
|
|
165
|
-
@abstractmethod
|
|
166
|
-
@asynccontextmanager
|
|
167
|
-
async def connect_to_server(self):
|
|
168
|
-
"""
|
|
169
|
-
Establish a session with an MCP server within an async context
|
|
170
|
-
"""
|
|
171
|
-
pass
|
|
172
|
-
|
|
173
|
-
async def get_tools(self):
|
|
174
|
-
"""
|
|
175
|
-
Retrieve a dictionary of all tools served by the MCP server.
|
|
176
|
-
"""
|
|
177
|
-
|
|
178
|
-
if not self._session:
|
|
179
|
-
raise RuntimeError("MCPBaseClient not initialized. Use async with to initialize.")
|
|
180
|
-
|
|
181
|
-
response = await self._session.list_tools()
|
|
182
|
-
|
|
183
|
-
return {
|
|
184
|
-
tool.name:
|
|
185
|
-
MCPToolClient(session=self._session,
|
|
186
|
-
tool_name=tool.name,
|
|
187
|
-
tool_description=tool.description,
|
|
188
|
-
tool_input_schema=tool.inputSchema)
|
|
189
|
-
for tool in response.tools
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
@mcp_exception_handler
|
|
193
|
-
async def get_tool(self, tool_name: str) -> MCPToolClient:
|
|
194
|
-
"""
|
|
195
|
-
Get an MCP Tool by name.
|
|
196
|
-
|
|
197
|
-
Args:
|
|
198
|
-
tool_name (str): Name of the tool to load.
|
|
199
|
-
|
|
200
|
-
Returns:
|
|
201
|
-
MCPToolClient for the configured tool.
|
|
202
|
-
|
|
203
|
-
Raises:
|
|
204
|
-
MCPToolNotFoundError: If no tool is available with that name.
|
|
205
|
-
"""
|
|
206
|
-
if not self._exit_stack:
|
|
207
|
-
raise RuntimeError("MCPBaseClient not initialized. Use async with to initialize.")
|
|
208
|
-
|
|
209
|
-
if not self._tools:
|
|
210
|
-
self._tools = await self.get_tools()
|
|
211
|
-
|
|
212
|
-
tool = self._tools.get(tool_name)
|
|
213
|
-
if not tool:
|
|
214
|
-
raise MCPToolNotFoundError(tool_name, self.server_name)
|
|
215
|
-
return tool
|
|
216
|
-
|
|
217
|
-
@mcp_exception_handler
|
|
218
|
-
async def call_tool(self, tool_name: str, tool_args: dict | None):
|
|
219
|
-
if not self._session:
|
|
220
|
-
raise RuntimeError("MCPBaseClient not initialized. Use async with to initialize.")
|
|
221
|
-
|
|
222
|
-
result = await self._session.call_tool(tool_name, tool_args)
|
|
223
|
-
return result
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
class MCPSSEClient(MCPBaseClient):
|
|
227
|
-
"""
|
|
228
|
-
Client for creating a session and connecting to an MCP server using SSE
|
|
229
|
-
|
|
230
|
-
Args:
|
|
231
|
-
url (str): The url of the MCP server
|
|
232
|
-
"""
|
|
233
|
-
|
|
234
|
-
def __init__(self, url: str):
|
|
235
|
-
super().__init__("sse")
|
|
236
|
-
self._url = url
|
|
237
|
-
|
|
238
|
-
@property
|
|
239
|
-
def url(self) -> str:
|
|
240
|
-
return self._url
|
|
241
|
-
|
|
242
|
-
@property
|
|
243
|
-
def server_name(self):
|
|
244
|
-
return f"sse:{self._url}"
|
|
245
|
-
|
|
246
|
-
@asynccontextmanager
|
|
247
|
-
@override
|
|
248
|
-
async def connect_to_server(self):
|
|
249
|
-
"""
|
|
250
|
-
Establish a session with an MCP SSE server within an async context
|
|
251
|
-
"""
|
|
252
|
-
async with sse_client(url=self._url) as (read, write):
|
|
253
|
-
async with ClientSession(read, write) as session:
|
|
254
|
-
await session.initialize()
|
|
255
|
-
yield session
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
class MCPStdioClient(MCPBaseClient):
|
|
259
|
-
"""
|
|
260
|
-
Client for creating a session and connecting to an MCP server using stdio
|
|
261
|
-
|
|
262
|
-
Args:
|
|
263
|
-
command (str): The command to run
|
|
264
|
-
args (list[str] | None): Additional arguments for the command
|
|
265
|
-
env (dict[str, str] | None): Environment variables to set for the process
|
|
266
|
-
"""
|
|
267
|
-
|
|
268
|
-
def __init__(self, command: str, args: list[str] | None = None, env: dict[str, str] | None = None):
|
|
269
|
-
super().__init__("stdio")
|
|
270
|
-
self._command = command
|
|
271
|
-
self._args = args
|
|
272
|
-
self._env = env
|
|
273
|
-
|
|
274
|
-
@property
|
|
275
|
-
def command(self) -> str:
|
|
276
|
-
return self._command
|
|
277
|
-
|
|
278
|
-
@property
|
|
279
|
-
def server_name(self):
|
|
280
|
-
return f"stdio:{self._command}"
|
|
281
|
-
|
|
282
|
-
@property
|
|
283
|
-
def args(self) -> list[str] | None:
|
|
284
|
-
return self._args
|
|
285
|
-
|
|
286
|
-
@property
|
|
287
|
-
def env(self) -> dict[str, str] | None:
|
|
288
|
-
return self._env
|
|
289
|
-
|
|
290
|
-
@asynccontextmanager
|
|
291
|
-
@override
|
|
292
|
-
async def connect_to_server(self):
|
|
293
|
-
"""
|
|
294
|
-
Establish a session with an MCP server via stdio within an async context
|
|
295
|
-
"""
|
|
296
|
-
|
|
297
|
-
server_params = StdioServerParameters(command=self._command, args=self._args or [], env=self._env)
|
|
298
|
-
async with stdio_client(server_params) as (read, write):
|
|
299
|
-
async with ClientSession(read, write) as session:
|
|
300
|
-
await session.initialize()
|
|
301
|
-
yield session
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
class MCPStreamableHTTPClient(MCPBaseClient):
|
|
305
|
-
"""
|
|
306
|
-
Client for creating a session and connecting to an MCP server using streamable-http
|
|
307
|
-
|
|
308
|
-
Args:
|
|
309
|
-
url (str): The url of the MCP server
|
|
310
|
-
"""
|
|
311
|
-
|
|
312
|
-
def __init__(self, url: str):
|
|
313
|
-
super().__init__("streamable-http")
|
|
314
|
-
|
|
315
|
-
self._url = url
|
|
316
|
-
|
|
317
|
-
@property
|
|
318
|
-
def url(self) -> str:
|
|
319
|
-
return self._url
|
|
320
|
-
|
|
321
|
-
@property
|
|
322
|
-
def server_name(self):
|
|
323
|
-
return f"streamable-http:{self._url}"
|
|
324
|
-
|
|
325
|
-
@asynccontextmanager
|
|
326
|
-
async def connect_to_server(self):
|
|
327
|
-
"""
|
|
328
|
-
Establish a session with an MCP server via streamable-http within an async context
|
|
329
|
-
"""
|
|
330
|
-
async with streamablehttp_client(url=self._url) as (read, write, get_session_id):
|
|
331
|
-
async with ClientSession(read, write) as session:
|
|
332
|
-
await session.initialize()
|
|
333
|
-
yield session
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
class MCPToolClient:
|
|
337
|
-
"""
|
|
338
|
-
Client wrapper used to call an MCP tool.
|
|
339
|
-
|
|
340
|
-
Args:
|
|
341
|
-
connect_fn (callable): Function that returns an async context manager for connecting to the server
|
|
342
|
-
tool_name (str): The name of the tool to wrap
|
|
343
|
-
tool_description (str): The description of the tool provided by the MCP server.
|
|
344
|
-
tool_input_schema (dict): The input schema for the tool.
|
|
345
|
-
"""
|
|
346
|
-
|
|
347
|
-
def __init__(self,
|
|
348
|
-
session: ClientSession,
|
|
349
|
-
tool_name: str,
|
|
350
|
-
tool_description: str | None,
|
|
351
|
-
tool_input_schema: dict | None = None):
|
|
352
|
-
self._session = session
|
|
353
|
-
self._tool_name = tool_name
|
|
354
|
-
self._tool_description = tool_description
|
|
355
|
-
self._input_schema = (model_from_mcp_schema(self._tool_name, tool_input_schema) if tool_input_schema else None)
|
|
356
|
-
|
|
357
|
-
@property
|
|
358
|
-
def name(self):
|
|
359
|
-
"""Returns the name of the tool."""
|
|
360
|
-
return self._tool_name
|
|
361
|
-
|
|
362
|
-
@property
|
|
363
|
-
def description(self):
|
|
364
|
-
"""
|
|
365
|
-
Returns the tool's description. If none was provided. Provides a simple description using the tool's name
|
|
366
|
-
"""
|
|
367
|
-
if not self._tool_description:
|
|
368
|
-
return f"MCP Tool {self._tool_name}"
|
|
369
|
-
return self._tool_description
|
|
370
|
-
|
|
371
|
-
@property
|
|
372
|
-
def input_schema(self):
|
|
373
|
-
"""
|
|
374
|
-
Returns the tool's input_schema.
|
|
375
|
-
"""
|
|
376
|
-
return self._input_schema
|
|
377
|
-
|
|
378
|
-
def set_description(self, description: str):
|
|
379
|
-
"""
|
|
380
|
-
Manually define the tool's description using the provided string.
|
|
381
|
-
"""
|
|
382
|
-
self._tool_description = description
|
|
383
|
-
|
|
384
|
-
async def acall(self, tool_args: dict) -> str:
|
|
385
|
-
"""
|
|
386
|
-
Call the MCP tool with the provided arguments.
|
|
387
|
-
|
|
388
|
-
Args:
|
|
389
|
-
tool_args (dict[str, Any]): A dictionary of key value pairs to serve as inputs for the MCP tool.
|
|
390
|
-
"""
|
|
391
|
-
result = await self._session.call_tool(self._tool_name, tool_args)
|
|
392
|
-
|
|
393
|
-
output = []
|
|
394
|
-
|
|
395
|
-
for res in result.content:
|
|
396
|
-
if isinstance(res, TextContent):
|
|
397
|
-
output.append(res.text)
|
|
398
|
-
else:
|
|
399
|
-
# Log non-text content for now
|
|
400
|
-
logger.warning("Got not-text output from %s of type %s", self.name, type(res))
|
|
401
|
-
result_str = "\n".join(output)
|
|
402
|
-
|
|
403
|
-
if result.isError:
|
|
404
|
-
raise RuntimeError(result_str)
|
|
405
|
-
|
|
406
|
-
return result_str
|