swarmauri_toolkit_mcpclient 0.1.0__tar.gz

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.
@@ -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 [2025] [Jacob Stewart @ Swarmauri]
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.
@@ -0,0 +1,7 @@
1
+ swarmauri_toolkit_mcpclient
2
+
3
+ Distribution: swarmauri_toolkit_mcpclient
4
+ Repository: https://github.com/swarmauri/swarmauri-sdk
5
+
6
+ Author attribution: Jacob Stewart.
7
+ Licensed under Apache-2.0. See LICENSE.
@@ -0,0 +1,391 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_toolkit_mcpclient
3
+ Version: 0.1.0
4
+ Summary: Discover and call Model Context Protocol server tools from Swarmauri agents.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ Keywords: swarmauri,toolkit,agents,mcp,model-context-protocol,tool-discovery,stdio,streamable-http
9
+ Author: Jacob Stewart
10
+ Author-email: jacob@swarmauri.com
11
+ Requires-Python: >=3.10,<3.15
12
+ Classifier: Development Status :: 1 - Planning
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Requires-Dist: anyio (>=4.7,<5)
20
+ Requires-Dist: httpx (>=0.28.1,<1)
21
+ Requires-Dist: mcp (>=1.30,<2)
22
+ Requires-Dist: pydantic (>=2.11,<3)
23
+ Requires-Dist: swarmauri_base (>=0.11.0)
24
+ Project-URL: Repository, https://github.com/swarmauri/swarmauri-sdk
25
+ Description-Content-Type: text/markdown
26
+
27
+ # swarmauri_toolkit_mcpclient
28
+
29
+ <!-- readme-standards:begin branding -->
30
+ <p align="center"><a href="https://github.com/swarmauri/swarmauri-sdk"><img src="https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/swarmauri.brand.theme.svg" alt="Swarmauri SDK" width="300"></a></p>
31
+ <p align="center"><strong>swarmauri_toolkit_mcpclient</strong></p>
32
+ <p align="center">Discover and call Model Context Protocol server tools from Swarmauri agents.</p>
33
+ <p align="center">
34
+ <a href="https://pypi.org/project/swarmauri_toolkit_mcpclient/"><img alt="pypi: swarmauri_toolkit_mcpclient unpublished" src="https://img.shields.io/static/v1?label=pypi&amp;message=swarmauri_toolkit_mcpclient%20unpublished&amp;labelColor=292421&amp;color=805500"></a>
35
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/pyproject.toml"><img alt="Source version: 0.1.0" src="https://img.shields.io/static/v1?label=Source%20version&amp;message=0.1.0&amp;labelColor=292421&amp;color=994525"></a>
36
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/pyproject.toml"><img alt="Python: &gt;=3.10,&lt;3.15" src="https://img.shields.io/static/v1?label=Python&amp;message=%3E%3D3.10%2C%3C3.15&amp;labelColor=292421&amp;color=994525"></a>
37
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/pyproject.toml"><img alt="Layer: community" src="https://img.shields.io/static/v1?label=Layer&amp;message=community&amp;labelColor=292421&amp;color=994525"></a>
38
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md#lifecycle-and-migration"><img alt="Lifecycle: active" src="https://img.shields.io/static/v1?label=Lifecycle&amp;message=active&amp;labelColor=292421&amp;color=24654A"></a>
39
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/static/v1?label=License&amp;message=Apache-2.0&amp;labelColor=292421&amp;color=994525"></a>
40
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/NOTICE"><img alt="Notice: attribution" src="https://img.shields.io/static/v1?label=Notice&amp;message=attribution&amp;labelColor=292421&amp;color=994525"></a>
41
+ </p>
42
+ <p align="center">
43
+ <a href="https://pypi.org/project/swarmauri_toolkit_mcpclient/"><img alt="pypi downloads: swarmauri_toolkit_mcpclient: unpublished" src="https://img.shields.io/static/v1?label=pypi%20downloads&amp;message=swarmauri_toolkit_mcpclient%3A%20unpublished&amp;labelColor=292421&amp;color=805500"></a>
44
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md"><img alt="README hits: swarmauri_toolkit_mcpclient" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md.svg?label=README%20hits&amp;labelColor=292421&amp;color=08704E"></a>
45
+ </p>
46
+ <p align="center">
47
+ <a href="https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"><img alt="README standards: CI gate" src="https://img.shields.io/static/v1?label=README%20standards&amp;message=CI%20gate&amp;labelColor=292421&amp;color=67437E"></a>
48
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/tests/i9n/test_toolkit.py"><img alt="Tests: integration tests" src="https://img.shields.io/static/v1?label=Tests&amp;message=integration%20tests&amp;labelColor=292421&amp;color=67437E"></a>
49
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md#certification-status"><img alt="Certification: not certified" src="https://img.shields.io/static/v1?label=Certification&amp;message=not%20certified&amp;labelColor=292421&amp;color=805500"></a>
50
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/tools/readme/POLICY.md"><img alt="Governance: repository policy" src="https://img.shields.io/static/v1?label=Governance&amp;message=repository%20policy&amp;labelColor=292421&amp;color=67437E"></a>
51
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/tests/i9n/test_toolkit.py"><img alt="Evidence: source and tests" src="https://img.shields.io/static/v1?label=Evidence&amp;message=source%20and%20tests&amp;labelColor=292421&amp;color=67437E"></a>
52
+ </p>
53
+ <p align="center"><a href="#overview">Overview</a> · <a href="#installation">Installation</a> · <a href="#quick-start">Quick Start</a> · <a href="#usage">Usage</a> · <a href="#public-api-and-import-surfaces">API</a> · <a href="#contributing">Contributing</a> · <a href="#governance">Governance</a> · <a href="#license">License</a></p>
54
+ <!-- readme-standards:end branding -->
55
+
56
+ ---
57
+
58
+ ## Overview
59
+
60
+ ### Summary
61
+
62
+ Connect Swarmauri agents to tools exposed by a Model Context Protocol (MCP) server.
63
+
64
+ ### Why This Package
65
+
66
+ The adapter turns advertised MCP tools into Swarmauri tool objects and reuses one client session across discovery and invocation.
67
+
68
+ ### When to Use
69
+
70
+ Use this toolkit when your agent needs tools provided by a local subprocess or a remote MCP endpoint.
71
+
72
+ ### Features
73
+
74
+ - Discover every page of server tools and restrict exposure with an optional allowlist.
75
+ - Connect over stdio or Streamable HTTP.
76
+ - Call tools synchronously or through the asynchronous wrapper.
77
+ - Return MCP content blocks, structured output and the tool error flag.
78
+
79
+ ### Non-Goals
80
+
81
+ The scope is client-side tool discovery and invocation. MCP resources, prompts, and server hosting are outside this package's scope.
82
+
83
+ ---
84
+
85
+ ## Getting Started
86
+
87
+ ### Prerequisites
88
+
89
+ Use Python 3.10 through 3.14 and a running HTTP MCP server or a local command that launches a stdio server. The agent example also uses the Swarmauri standard kernel, which requires Python 3.11 or later.
90
+
91
+ ### Installation
92
+
93
+ #### Install with uv
94
+
95
+ <!-- readme-standards:begin installation.uv -->
96
+ `swarmauri_toolkit_mcpclient` is not declared published. From the source checkout:
97
+
98
+ ```bash
99
+ uv pip install .
100
+ ```
101
+ <!-- readme-standards:end installation.uv -->
102
+
103
+ #### Install with pip
104
+
105
+ <!-- readme-standards:begin installation.pip -->
106
+ `swarmauri_toolkit_mcpclient` is not declared published. From the source checkout:
107
+
108
+ ```bash
109
+ python -m pip install .
110
+ ```
111
+ <!-- readme-standards:end installation.pip -->
112
+
113
+ #### Install with Poetry
114
+
115
+ <!-- readme-standards:begin installation.poetry -->
116
+ `swarmauri_toolkit_mcpclient` is not declared published. From a separate Poetry project, replace the path with your checkout:
117
+
118
+ ```bash
119
+ poetry add /path/to/swarmauri_toolkit_mcpclient
120
+ ```
121
+ <!-- readme-standards:end installation.poetry -->
122
+
123
+ ### Quick Start
124
+
125
+ #### Example
126
+
127
+ <!-- readme-standards:begin example.quick-start -->
128
+ Source: [docs/readme/quick_start.py](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/docs/readme/quick_start.py).
129
+
130
+ ```python
131
+ """Discover and call a tool on the example stdio MCP server."""
132
+
133
+ from pathlib import Path
134
+ import sys
135
+
136
+ from mcp import StdioServerParameters
137
+
138
+ from swarmauri_toolkit_mcpclient import MCPToolkit
139
+
140
+
141
+ if __name__ == "__main__":
142
+ fixture = (
143
+ Path(__file__).resolve().parents[2] / "tests/i9n/fixture_server.py"
144
+ )
145
+ server = StdioServerParameters(command=sys.executable, args=[str(fixture)])
146
+ with MCPToolkit.connect(server, allowed_tools={"sum_values"}) as toolkit:
147
+ result = toolkit.get_tool_by_name("sum_values")(values=[2, 3])
148
+ print(result["structuredContent"])
149
+ ```
150
+ <!-- readme-standards:end example.quick-start -->
151
+
152
+ #### Expected Result
153
+
154
+ The stdio example prints a structured result containing `{'total': 5}`.
155
+
156
+ ---
157
+
158
+ ## Usage
159
+
160
+ ### Common Workflows
161
+
162
+ <!-- readme-standards:begin example.usage -->
163
+ Source: [docs/readme/usage.py](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/docs/readme/usage.py).
164
+
165
+ ```python
166
+ """Give a Swarmauri agent access to a remote weather tool."""
167
+
168
+ from swarmauri_standard.agents.ToolAgent import ToolAgent
169
+
170
+ from swarmauri_toolkit_mcpclient import MCPToolkit
171
+
172
+
173
+ def ask_weather(llm, conversation):
174
+ """Use a configured tool model and conversation to ask for the weather."""
175
+ with MCPToolkit.connect(
176
+ "https://weather.example.com/mcp",
177
+ allowed_tools={"get_weather"},
178
+ ) as toolkit:
179
+ agent = ToolAgent(llm=llm, conversation=conversation, toolkit=toolkit)
180
+ return agent.exec(
181
+ "What's the weather in Chicago?",
182
+ llm_kwargs={"tool_choice": "auto"},
183
+ )
184
+ ```
185
+ <!-- readme-standards:end example.usage -->
186
+
187
+ ### Configuration
188
+
189
+ Pass HTTP request headers with `headers`, configure the per-request timeout with `timeout`, and choose tools by original server name with `allowed_tools`.
190
+
191
+ **OAuth for Streamable HTTP**
192
+
193
+ Pass an MCP SDK OAuth provider as `auth` when opening the toolkit.
194
+ The provider authenticates both discovery and tool requests. Choose the provider
195
+ and token storage in the application before giving the toolkit to an agent.
196
+
197
+ ```python
198
+ from mcp.client.auth.extensions.client_credentials import (
199
+ ClientCredentialsOAuthProvider,
200
+ )
201
+
202
+ from swarmauri_toolkit_mcpclient import MCPToolkit
203
+
204
+
205
+ def connect_agent(endpoint, issuer, client_id, client_secret, storage):
206
+ """Open an MCP session for a provisioned agent service principal."""
207
+ auth = ClientCredentialsOAuthProvider(
208
+ server_url=endpoint,
209
+ issuer=issuer,
210
+ client_id=client_id,
211
+ client_secret=client_secret,
212
+ storage=storage,
213
+ )
214
+ return MCPToolkit.connect(endpoint, auth=auth)
215
+ ```
216
+
217
+ Use a separate service principal per autonomous agent when the MCP server must
218
+ authorize or audit them individually. Load each principal's credentials from the
219
+ application's secret store and pass its trusted authorization server `issuer`.
220
+ The SDK obtains a new access token when the current service token expires.
221
+
222
+ For user consent, pass `mcp.client.auth.OAuthClientProvider` with the application's
223
+ redirect and callback handlers. Set `timeout` to accommodate the consent window,
224
+ for example 300 seconds. The SDK uses authorization code with PKCE and renews
225
+ access during the connection when the issuer provides a refresh token. A delegated grant carries the user's permissions. A distinct
226
+ server-visible agent identity requires the issuer and server to support it.
227
+
228
+ Supply a separate SDK `TokenStorage` scope per agent, authorization issuer, MCP
229
+ resource, and delegated user or grant. The application controls persistence and
230
+ should coordinate concurrent connections that share a refresh-token grant. Use a
231
+ fresh provider per connection and HTTPS in production. A stored client
232
+ registration should be bound to its issuer. Keep credentials in the application
233
+ and turn consent or reauthorization into an application interaction.
234
+
235
+ ### Error Handling
236
+
237
+ Check `isError` in the result for server-reported tool failures. Transport and protocol failures raise exceptions. An unknown allowlist entry fails discovery.
238
+
239
+ ### Best Practices
240
+
241
+ Keep the connection context open for the entire agent run. Open a new context to rediscover the server's tool catalog.
242
+
243
+ ---
244
+
245
+ ## Package Boundary
246
+
247
+ ### What It Owns
248
+
249
+ The toolkit owns the MCP client session, paginated tool discovery, name mapping, and submission of tool arguments and results.
250
+
251
+ ### Public API and Import Surfaces
252
+
253
+ Import `MCPToolkit` or `MCPTool` from `swarmauri_toolkit_mcpclient`. The installed toolkit is also available under `swarmauri.toolkits.MCPToolkit`.
254
+
255
+ ### Entry Points
256
+
257
+ <!-- readme-standards:begin entry-points -->
258
+ - `swarmauri.toolkits` → `MCPToolkit` → `swarmauri_toolkit_mcpclient:MCPToolkit`
259
+ <!-- readme-standards:end entry-points -->
260
+
261
+ ### Injected Dependencies
262
+
263
+ Provide a Streamable HTTP URL or an MCP `StdioServerParameters` object. Supply HTTP authentication headers when required by the endpoint.
264
+
265
+ ### Protocol Consumers
266
+
267
+ A Swarmauri `ToolAgent` consumes the toolkit through the existing toolkit and tool contracts. Direct callers can use `get_tool_by_name`.
268
+
269
+ ### Extensions
270
+
271
+ The OpenAI and Anthropic converters can read each tool's original JSON Schema. Other converters use the Swarmauri parameter metadata.
272
+
273
+ ---
274
+
275
+ ## Operations and Readiness
276
+
277
+ ### Operational Requirements
278
+
279
+ The stdio transport requires permission to launch the configured executable. Streamable HTTP requires network access to the configured endpoint.
280
+
281
+ ### Health and Observability
282
+
283
+ Connection initialization and the first tool listing are completed before the context yields. Callers can record MCP tool outcomes and transport errors in their own logs.
284
+
285
+ ### Security and Resource Limits
286
+
287
+ Use an allowlist to limit the tools agents can invoke, and configure a request timeout appropriate for the server.
288
+
289
+ ### Compatibility
290
+
291
+ The toolkit uses MCP Python SDK 1.x and supports Python 3.10 through 3.14. Use `await tool.acall(...)` for direct calls from an asyncio application.
292
+
293
+ ---
294
+
295
+ ## Verification
296
+
297
+ ### Tests
298
+
299
+ The package suite covers pagination, both transports, and an agent round trip with a mocked model response.
300
+
301
+ ### Certification Status
302
+
303
+ Package verification is covered by repository CI and local integration tests.
304
+
305
+ ### Evidence
306
+
307
+ See [the MCP integration tests](tests/i9n/test_toolkit.py) for the expected tool call, result, and error behavior.
308
+
309
+ ---
310
+
311
+ ## FAQ
312
+
313
+ ### Why
314
+
315
+ A single toolkit lets an agent share the same MCP connection across tool calls.
316
+
317
+ ### How
318
+
319
+ Call `MCPToolkit.connect` and pass the toolkit to the agent or call a tool by its discovered name.
320
+
321
+ ### When
322
+
323
+ Connect before the agent starts. Exit the context when the agent finishes using server tools.
324
+
325
+ ---
326
+
327
+ ## Documentation and Related Packages
328
+
329
+ ### More Documentation
330
+
331
+ See [the MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) for server and transport configuration.
332
+
333
+ ### Related Packages
334
+
335
+ `swarmauri_base` provides the toolkit and tool contracts. `swarmauri_standard` provides `ToolAgent` and the schema converters.
336
+
337
+ ### Project Links
338
+
339
+ <!-- readme-standards:begin project-links -->
340
+ - [Repository](https://github.com/swarmauri/swarmauri-sdk)
341
+ - [pypi: swarmauri_toolkit_mcpclient](https://pypi.org/project/swarmauri_toolkit_mcpclient/)
342
+ <!-- readme-standards:end project-links -->
343
+
344
+ ---
345
+
346
+ ## Contributing
347
+
348
+ ### How to Contribute
349
+
350
+ Submit toolkit changes through the [Swarmauri contribution guide](../../../AGENTS.md).
351
+
352
+ ### Development Setup
353
+
354
+ From the repository root, run `uv run --directory pkgs --package swarmauri_toolkit_mcpclient pytest 50-community/swarmauri_toolkit_mcpclient/tests`.
355
+
356
+ ### Notes for Maintainers
357
+
358
+ Use the local MCP test fixture to validate changes to discovery or result translation without external model credentials.
359
+
360
+ ---
361
+
362
+ ## Governance
363
+
364
+ ### Ownership and Decision Making
365
+
366
+ The Swarmauri SDK maintainers review changes to this community integration.
367
+
368
+ ### Standards and Policies
369
+
370
+ This README follows the repository's [package README policy](../../../tools/readme/POLICY.md).
371
+
372
+ ### Lifecycle and Migration
373
+
374
+ This initial community package is available from a repository checkout. Reconnect to rebuild callable tools from server metadata.
375
+
376
+ ---
377
+
378
+ ## License and Attribution
379
+
380
+ ### License
381
+
382
+ <!-- readme-standards:begin license -->
383
+ Licensed under `Apache-2.0`. See [LICENSE](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/LICENSE).
384
+ <!-- readme-standards:end license -->
385
+
386
+ ### Notices
387
+
388
+ <!-- readme-standards:begin notices -->
389
+ See [NOTICE](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/NOTICE) for attribution.
390
+ <!-- readme-standards:end notices -->
391
+
@@ -0,0 +1,364 @@
1
+ # swarmauri_toolkit_mcpclient
2
+
3
+ <!-- readme-standards:begin branding -->
4
+ <p align="center"><a href="https://github.com/swarmauri/swarmauri-sdk"><img src="https://raw.githubusercontent.com/swarmauri/swarmauri-sdk/master/assets/swarmauri.brand.theme.svg" alt="Swarmauri SDK" width="300"></a></p>
5
+ <p align="center"><strong>swarmauri_toolkit_mcpclient</strong></p>
6
+ <p align="center">Discover and call Model Context Protocol server tools from Swarmauri agents.</p>
7
+ <p align="center">
8
+ <a href="https://pypi.org/project/swarmauri_toolkit_mcpclient/"><img alt="pypi: swarmauri_toolkit_mcpclient unpublished" src="https://img.shields.io/static/v1?label=pypi&amp;message=swarmauri_toolkit_mcpclient%20unpublished&amp;labelColor=292421&amp;color=805500"></a>
9
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/pyproject.toml"><img alt="Source version: 0.1.0" src="https://img.shields.io/static/v1?label=Source%20version&amp;message=0.1.0&amp;labelColor=292421&amp;color=994525"></a>
10
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/pyproject.toml"><img alt="Python: &gt;=3.10,&lt;3.15" src="https://img.shields.io/static/v1?label=Python&amp;message=%3E%3D3.10%2C%3C3.15&amp;labelColor=292421&amp;color=994525"></a>
11
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/pyproject.toml"><img alt="Layer: community" src="https://img.shields.io/static/v1?label=Layer&amp;message=community&amp;labelColor=292421&amp;color=994525"></a>
12
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md#lifecycle-and-migration"><img alt="Lifecycle: active" src="https://img.shields.io/static/v1?label=Lifecycle&amp;message=active&amp;labelColor=292421&amp;color=24654A"></a>
13
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/static/v1?label=License&amp;message=Apache-2.0&amp;labelColor=292421&amp;color=994525"></a>
14
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/NOTICE"><img alt="Notice: attribution" src="https://img.shields.io/static/v1?label=Notice&amp;message=attribution&amp;labelColor=292421&amp;color=994525"></a>
15
+ </p>
16
+ <p align="center">
17
+ <a href="https://pypi.org/project/swarmauri_toolkit_mcpclient/"><img alt="pypi downloads: swarmauri_toolkit_mcpclient: unpublished" src="https://img.shields.io/static/v1?label=pypi%20downloads&amp;message=swarmauri_toolkit_mcpclient%3A%20unpublished&amp;labelColor=292421&amp;color=805500"></a>
18
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md"><img alt="README hits: swarmauri_toolkit_mcpclient" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md.svg?label=README%20hits&amp;labelColor=292421&amp;color=08704E"></a>
19
+ </p>
20
+ <p align="center">
21
+ <a href="https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"><img alt="README standards: CI gate" src="https://img.shields.io/static/v1?label=README%20standards&amp;message=CI%20gate&amp;labelColor=292421&amp;color=67437E"></a>
22
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/tests/i9n/test_toolkit.py"><img alt="Tests: integration tests" src="https://img.shields.io/static/v1?label=Tests&amp;message=integration%20tests&amp;labelColor=292421&amp;color=67437E"></a>
23
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md#certification-status"><img alt="Certification: not certified" src="https://img.shields.io/static/v1?label=Certification&amp;message=not%20certified&amp;labelColor=292421&amp;color=805500"></a>
24
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/tools/readme/POLICY.md"><img alt="Governance: repository policy" src="https://img.shields.io/static/v1?label=Governance&amp;message=repository%20policy&amp;labelColor=292421&amp;color=67437E"></a>
25
+ <a href="https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/tests/i9n/test_toolkit.py"><img alt="Evidence: source and tests" src="https://img.shields.io/static/v1?label=Evidence&amp;message=source%20and%20tests&amp;labelColor=292421&amp;color=67437E"></a>
26
+ </p>
27
+ <p align="center"><a href="#overview">Overview</a> · <a href="#installation">Installation</a> · <a href="#quick-start">Quick Start</a> · <a href="#usage">Usage</a> · <a href="#public-api-and-import-surfaces">API</a> · <a href="#contributing">Contributing</a> · <a href="#governance">Governance</a> · <a href="#license">License</a></p>
28
+ <!-- readme-standards:end branding -->
29
+
30
+ ---
31
+
32
+ ## Overview
33
+
34
+ ### Summary
35
+
36
+ Connect Swarmauri agents to tools exposed by a Model Context Protocol (MCP) server.
37
+
38
+ ### Why This Package
39
+
40
+ The adapter turns advertised MCP tools into Swarmauri tool objects and reuses one client session across discovery and invocation.
41
+
42
+ ### When to Use
43
+
44
+ Use this toolkit when your agent needs tools provided by a local subprocess or a remote MCP endpoint.
45
+
46
+ ### Features
47
+
48
+ - Discover every page of server tools and restrict exposure with an optional allowlist.
49
+ - Connect over stdio or Streamable HTTP.
50
+ - Call tools synchronously or through the asynchronous wrapper.
51
+ - Return MCP content blocks, structured output and the tool error flag.
52
+
53
+ ### Non-Goals
54
+
55
+ The scope is client-side tool discovery and invocation. MCP resources, prompts, and server hosting are outside this package's scope.
56
+
57
+ ---
58
+
59
+ ## Getting Started
60
+
61
+ ### Prerequisites
62
+
63
+ Use Python 3.10 through 3.14 and a running HTTP MCP server or a local command that launches a stdio server. The agent example also uses the Swarmauri standard kernel, which requires Python 3.11 or later.
64
+
65
+ ### Installation
66
+
67
+ #### Install with uv
68
+
69
+ <!-- readme-standards:begin installation.uv -->
70
+ `swarmauri_toolkit_mcpclient` is not declared published. From the source checkout:
71
+
72
+ ```bash
73
+ uv pip install .
74
+ ```
75
+ <!-- readme-standards:end installation.uv -->
76
+
77
+ #### Install with pip
78
+
79
+ <!-- readme-standards:begin installation.pip -->
80
+ `swarmauri_toolkit_mcpclient` is not declared published. From the source checkout:
81
+
82
+ ```bash
83
+ python -m pip install .
84
+ ```
85
+ <!-- readme-standards:end installation.pip -->
86
+
87
+ #### Install with Poetry
88
+
89
+ <!-- readme-standards:begin installation.poetry -->
90
+ `swarmauri_toolkit_mcpclient` is not declared published. From a separate Poetry project, replace the path with your checkout:
91
+
92
+ ```bash
93
+ poetry add /path/to/swarmauri_toolkit_mcpclient
94
+ ```
95
+ <!-- readme-standards:end installation.poetry -->
96
+
97
+ ### Quick Start
98
+
99
+ #### Example
100
+
101
+ <!-- readme-standards:begin example.quick-start -->
102
+ Source: [docs/readme/quick_start.py](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/docs/readme/quick_start.py).
103
+
104
+ ```python
105
+ """Discover and call a tool on the example stdio MCP server."""
106
+
107
+ from pathlib import Path
108
+ import sys
109
+
110
+ from mcp import StdioServerParameters
111
+
112
+ from swarmauri_toolkit_mcpclient import MCPToolkit
113
+
114
+
115
+ if __name__ == "__main__":
116
+ fixture = (
117
+ Path(__file__).resolve().parents[2] / "tests/i9n/fixture_server.py"
118
+ )
119
+ server = StdioServerParameters(command=sys.executable, args=[str(fixture)])
120
+ with MCPToolkit.connect(server, allowed_tools={"sum_values"}) as toolkit:
121
+ result = toolkit.get_tool_by_name("sum_values")(values=[2, 3])
122
+ print(result["structuredContent"])
123
+ ```
124
+ <!-- readme-standards:end example.quick-start -->
125
+
126
+ #### Expected Result
127
+
128
+ The stdio example prints a structured result containing `{'total': 5}`.
129
+
130
+ ---
131
+
132
+ ## Usage
133
+
134
+ ### Common Workflows
135
+
136
+ <!-- readme-standards:begin example.usage -->
137
+ Source: [docs/readme/usage.py](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/docs/readme/usage.py).
138
+
139
+ ```python
140
+ """Give a Swarmauri agent access to a remote weather tool."""
141
+
142
+ from swarmauri_standard.agents.ToolAgent import ToolAgent
143
+
144
+ from swarmauri_toolkit_mcpclient import MCPToolkit
145
+
146
+
147
+ def ask_weather(llm, conversation):
148
+ """Use a configured tool model and conversation to ask for the weather."""
149
+ with MCPToolkit.connect(
150
+ "https://weather.example.com/mcp",
151
+ allowed_tools={"get_weather"},
152
+ ) as toolkit:
153
+ agent = ToolAgent(llm=llm, conversation=conversation, toolkit=toolkit)
154
+ return agent.exec(
155
+ "What's the weather in Chicago?",
156
+ llm_kwargs={"tool_choice": "auto"},
157
+ )
158
+ ```
159
+ <!-- readme-standards:end example.usage -->
160
+
161
+ ### Configuration
162
+
163
+ Pass HTTP request headers with `headers`, configure the per-request timeout with `timeout`, and choose tools by original server name with `allowed_tools`.
164
+
165
+ **OAuth for Streamable HTTP**
166
+
167
+ Pass an MCP SDK OAuth provider as `auth` when opening the toolkit.
168
+ The provider authenticates both discovery and tool requests. Choose the provider
169
+ and token storage in the application before giving the toolkit to an agent.
170
+
171
+ ```python
172
+ from mcp.client.auth.extensions.client_credentials import (
173
+ ClientCredentialsOAuthProvider,
174
+ )
175
+
176
+ from swarmauri_toolkit_mcpclient import MCPToolkit
177
+
178
+
179
+ def connect_agent(endpoint, issuer, client_id, client_secret, storage):
180
+ """Open an MCP session for a provisioned agent service principal."""
181
+ auth = ClientCredentialsOAuthProvider(
182
+ server_url=endpoint,
183
+ issuer=issuer,
184
+ client_id=client_id,
185
+ client_secret=client_secret,
186
+ storage=storage,
187
+ )
188
+ return MCPToolkit.connect(endpoint, auth=auth)
189
+ ```
190
+
191
+ Use a separate service principal per autonomous agent when the MCP server must
192
+ authorize or audit them individually. Load each principal's credentials from the
193
+ application's secret store and pass its trusted authorization server `issuer`.
194
+ The SDK obtains a new access token when the current service token expires.
195
+
196
+ For user consent, pass `mcp.client.auth.OAuthClientProvider` with the application's
197
+ redirect and callback handlers. Set `timeout` to accommodate the consent window,
198
+ for example 300 seconds. The SDK uses authorization code with PKCE and renews
199
+ access during the connection when the issuer provides a refresh token. A delegated grant carries the user's permissions. A distinct
200
+ server-visible agent identity requires the issuer and server to support it.
201
+
202
+ Supply a separate SDK `TokenStorage` scope per agent, authorization issuer, MCP
203
+ resource, and delegated user or grant. The application controls persistence and
204
+ should coordinate concurrent connections that share a refresh-token grant. Use a
205
+ fresh provider per connection and HTTPS in production. A stored client
206
+ registration should be bound to its issuer. Keep credentials in the application
207
+ and turn consent or reauthorization into an application interaction.
208
+
209
+ ### Error Handling
210
+
211
+ Check `isError` in the result for server-reported tool failures. Transport and protocol failures raise exceptions. An unknown allowlist entry fails discovery.
212
+
213
+ ### Best Practices
214
+
215
+ Keep the connection context open for the entire agent run. Open a new context to rediscover the server's tool catalog.
216
+
217
+ ---
218
+
219
+ ## Package Boundary
220
+
221
+ ### What It Owns
222
+
223
+ The toolkit owns the MCP client session, paginated tool discovery, name mapping, and submission of tool arguments and results.
224
+
225
+ ### Public API and Import Surfaces
226
+
227
+ Import `MCPToolkit` or `MCPTool` from `swarmauri_toolkit_mcpclient`. The installed toolkit is also available under `swarmauri.toolkits.MCPToolkit`.
228
+
229
+ ### Entry Points
230
+
231
+ <!-- readme-standards:begin entry-points -->
232
+ - `swarmauri.toolkits` → `MCPToolkit` → `swarmauri_toolkit_mcpclient:MCPToolkit`
233
+ <!-- readme-standards:end entry-points -->
234
+
235
+ ### Injected Dependencies
236
+
237
+ Provide a Streamable HTTP URL or an MCP `StdioServerParameters` object. Supply HTTP authentication headers when required by the endpoint.
238
+
239
+ ### Protocol Consumers
240
+
241
+ A Swarmauri `ToolAgent` consumes the toolkit through the existing toolkit and tool contracts. Direct callers can use `get_tool_by_name`.
242
+
243
+ ### Extensions
244
+
245
+ The OpenAI and Anthropic converters can read each tool's original JSON Schema. Other converters use the Swarmauri parameter metadata.
246
+
247
+ ---
248
+
249
+ ## Operations and Readiness
250
+
251
+ ### Operational Requirements
252
+
253
+ The stdio transport requires permission to launch the configured executable. Streamable HTTP requires network access to the configured endpoint.
254
+
255
+ ### Health and Observability
256
+
257
+ Connection initialization and the first tool listing are completed before the context yields. Callers can record MCP tool outcomes and transport errors in their own logs.
258
+
259
+ ### Security and Resource Limits
260
+
261
+ Use an allowlist to limit the tools agents can invoke, and configure a request timeout appropriate for the server.
262
+
263
+ ### Compatibility
264
+
265
+ The toolkit uses MCP Python SDK 1.x and supports Python 3.10 through 3.14. Use `await tool.acall(...)` for direct calls from an asyncio application.
266
+
267
+ ---
268
+
269
+ ## Verification
270
+
271
+ ### Tests
272
+
273
+ The package suite covers pagination, both transports, and an agent round trip with a mocked model response.
274
+
275
+ ### Certification Status
276
+
277
+ Package verification is covered by repository CI and local integration tests.
278
+
279
+ ### Evidence
280
+
281
+ See [the MCP integration tests](tests/i9n/test_toolkit.py) for the expected tool call, result, and error behavior.
282
+
283
+ ---
284
+
285
+ ## FAQ
286
+
287
+ ### Why
288
+
289
+ A single toolkit lets an agent share the same MCP connection across tool calls.
290
+
291
+ ### How
292
+
293
+ Call `MCPToolkit.connect` and pass the toolkit to the agent or call a tool by its discovered name.
294
+
295
+ ### When
296
+
297
+ Connect before the agent starts. Exit the context when the agent finishes using server tools.
298
+
299
+ ---
300
+
301
+ ## Documentation and Related Packages
302
+
303
+ ### More Documentation
304
+
305
+ See [the MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) for server and transport configuration.
306
+
307
+ ### Related Packages
308
+
309
+ `swarmauri_base` provides the toolkit and tool contracts. `swarmauri_standard` provides `ToolAgent` and the schema converters.
310
+
311
+ ### Project Links
312
+
313
+ <!-- readme-standards:begin project-links -->
314
+ - [Repository](https://github.com/swarmauri/swarmauri-sdk)
315
+ - [pypi: swarmauri_toolkit_mcpclient](https://pypi.org/project/swarmauri_toolkit_mcpclient/)
316
+ <!-- readme-standards:end project-links -->
317
+
318
+ ---
319
+
320
+ ## Contributing
321
+
322
+ ### How to Contribute
323
+
324
+ Submit toolkit changes through the [Swarmauri contribution guide](../../../AGENTS.md).
325
+
326
+ ### Development Setup
327
+
328
+ From the repository root, run `uv run --directory pkgs --package swarmauri_toolkit_mcpclient pytest 50-community/swarmauri_toolkit_mcpclient/tests`.
329
+
330
+ ### Notes for Maintainers
331
+
332
+ Use the local MCP test fixture to validate changes to discovery or result translation without external model credentials.
333
+
334
+ ---
335
+
336
+ ## Governance
337
+
338
+ ### Ownership and Decision Making
339
+
340
+ The Swarmauri SDK maintainers review changes to this community integration.
341
+
342
+ ### Standards and Policies
343
+
344
+ This README follows the repository's [package README policy](../../../tools/readme/POLICY.md).
345
+
346
+ ### Lifecycle and Migration
347
+
348
+ This initial community package is available from a repository checkout. Reconnect to rebuild callable tools from server metadata.
349
+
350
+ ---
351
+
352
+ ## License and Attribution
353
+
354
+ ### License
355
+
356
+ <!-- readme-standards:begin license -->
357
+ Licensed under `Apache-2.0`. See [LICENSE](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/LICENSE).
358
+ <!-- readme-standards:end license -->
359
+
360
+ ### Notices
361
+
362
+ <!-- readme-standards:begin notices -->
363
+ See [NOTICE](https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/NOTICE) for attribution.
364
+ <!-- readme-standards:end notices -->
@@ -0,0 +1,98 @@
1
+ [project]
2
+ name = "swarmauri_toolkit_mcpclient"
3
+ version = "0.1.0"
4
+ description = "Discover and call Model Context Protocol server tools from Swarmauri agents."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE", "NOTICE"]
8
+ requires-python = ">=3.10,<3.15"
9
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
10
+ keywords = [
11
+ "swarmauri", "toolkit", "agents", "mcp", "model-context-protocol",
12
+ "tool-discovery", "stdio", "streamable-http",
13
+ ]
14
+ classifiers = [
15
+ "Development Status :: 1 - Planning",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Programming Language :: Python :: 3.14",
22
+ ]
23
+ dependencies = [
24
+ "anyio>=4.7,<5",
25
+ "httpx>=0.28.1,<1",
26
+ "mcp>=1.30,<2",
27
+ "pydantic>=2.11,<3",
28
+ "swarmauri_base >=0.11.0",
29
+ ]
30
+
31
+ [project.urls]
32
+ Repository = "https://github.com/swarmauri/swarmauri-sdk"
33
+
34
+ [project.entry-points."swarmauri.toolkits"]
35
+ MCPToolkit = "swarmauri_toolkit_mcpclient:MCPToolkit"
36
+
37
+ [tool.uv.sources]
38
+ swarmauri_base = { workspace = true }
39
+ swarmauri_standard = { workspace = true }
40
+
41
+ [tool.pytest.ini_options]
42
+ markers = ["unit: Unit tests", "i9n: Integration tests"]
43
+
44
+ [build-system]
45
+ requires = ["poetry-core>=1.0.0"]
46
+ build-backend = "poetry.core.masonry.api"
47
+
48
+ [dependency-groups]
49
+ dev = ["pytest>=8.0", "ruff>=0.9.9", "swarmauri_standard; python_version >= '3.11'"]
50
+
51
+ [tool.readme_standards]
52
+ policy = "package-guide-v1"
53
+ readme = "README.md"
54
+ brand = "swarmauri"
55
+ brand_catalog = "../../../tools/readme/brands.toml"
56
+ repository = "https://github.com/swarmauri/swarmauri-sdk"
57
+ ref = "master"
58
+ package_path = "pkgs/50-community/swarmauri_toolkit_mcpclient"
59
+ layer = "community"
60
+ lifecycle = "active"
61
+ license_file = "LICENSE"
62
+ notice_file = "NOTICE"
63
+
64
+ [tool.readme_standards.distributions.pypi]
65
+ name = "swarmauri_toolkit_mcpclient"
66
+ published = false
67
+
68
+ [tool.readme_standards.examples.quick_start]
69
+ source = "docs/readme/quick_start.py"
70
+ test = "tests/i9n/test_toolkit.py"
71
+ language = "python"
72
+ expected_exit_code = 0
73
+
74
+ [tool.readme_standards.examples.usage]
75
+ source = "docs/readme/usage.py"
76
+ test = "tests/i9n/test_toolkit.py"
77
+ language = "python"
78
+ expected_exit_code = 0
79
+
80
+ [tool.readme_standards.statuses.readme]
81
+ label = "CI gate"
82
+ url = "https://github.com/swarmauri/swarmauri-sdk/actions/workflows/readme-standards.yml"
83
+
84
+ [tool.readme_standards.statuses.tests]
85
+ label = "integration tests"
86
+ url = "https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/tests/i9n/test_toolkit.py"
87
+
88
+ [tool.readme_standards.statuses.certification]
89
+ label = "not certified"
90
+ url = "https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/README.md#certification-status"
91
+
92
+ [tool.readme_standards.statuses.governance]
93
+ label = "repository policy"
94
+ url = "https://github.com/swarmauri/swarmauri-sdk/blob/master/tools/readme/POLICY.md"
95
+
96
+ [tool.readme_standards.statuses.evidence]
97
+ label = "source and tests"
98
+ url = "https://github.com/swarmauri/swarmauri-sdk/blob/master/pkgs/50-community/swarmauri_toolkit_mcpclient/tests/i9n/test_toolkit.py"
@@ -0,0 +1,49 @@
1
+ """Adapt a discovered MCP tool to the Swarmauri tool interface."""
2
+
3
+ import asyncio
4
+ from typing import Any, Literal
5
+
6
+ from anyio.from_thread import BlockingPortal
7
+ from mcp import ClientSession
8
+ from pydantic import PrivateAttr
9
+ from swarmauri_base.ComponentBase import ComponentBase
10
+ from swarmauri_base.tools.ToolBase import ToolBase
11
+
12
+
13
+ @ComponentBase.register_type(ToolBase, "MCPTool")
14
+ class MCPTool(ToolBase):
15
+ """Forward keyword arguments to a tool on a connected MCP server."""
16
+
17
+ type: Literal["MCPTool"] = "MCPTool"
18
+ remote_name: str
19
+ input_schema: dict[str, Any]
20
+ _connection: tuple[BlockingPortal, ClientSession] | None = PrivateAttr(
21
+ default=None
22
+ )
23
+
24
+ async def _invoke(
25
+ self, session: ClientSession, arguments: dict[str, Any]
26
+ ) -> dict[str, Any]:
27
+ result = await session.call_tool(self.remote_name, arguments=arguments)
28
+ return result.model_dump(mode="json", by_alias=True, exclude_none=True)
29
+
30
+ def _connected(self) -> tuple[BlockingPortal, ClientSession]:
31
+ if self._connection is None:
32
+ raise RuntimeError(
33
+ "Discover MCP tools inside MCPToolkit.connect()."
34
+ )
35
+ return self._connection
36
+
37
+ def __call__(self, /, **arguments: Any) -> dict[str, Any]:
38
+ """Call the remote tool and return its JSON-compatible MCP result."""
39
+ portal, session = self._connected()
40
+ return portal.call(self._invoke, session, arguments)
41
+
42
+ call = __call__
43
+
44
+ async def acall(self, /, **arguments: Any) -> dict[str, Any]:
45
+ """Call the remote tool without blocking an asyncio event loop."""
46
+ portal, session = self._connected()
47
+ return await asyncio.wrap_future(
48
+ portal.start_task_soon(self._invoke, session, arguments)
49
+ )
@@ -0,0 +1,195 @@
1
+ """Discover MCP tools over stdio or Streamable HTTP."""
2
+
3
+ import re
4
+ from collections.abc import AsyncIterator, Collection, Iterator, Mapping
5
+ from contextlib import (
6
+ AsyncExitStack,
7
+ ExitStack,
8
+ asynccontextmanager,
9
+ contextmanager,
10
+ )
11
+ from datetime import timedelta
12
+ from hashlib import sha256
13
+ from typing import Literal
14
+
15
+ import httpx
16
+ from anyio.from_thread import start_blocking_portal
17
+ from mcp import ClientSession, StdioServerParameters
18
+ from mcp.client.stdio import stdio_client
19
+ from mcp.client.streamable_http import streamable_http_client
20
+ from mcp.types import Tool
21
+ from swarmauri_base.ComponentBase import ComponentBase
22
+ from swarmauri_base.toolkits.ToolkitBase import ToolkitBase
23
+ from swarmauri_base.tools.ParameterBase import ParameterBase
24
+
25
+ from swarmauri_toolkit_mcpclient.MCPTool import MCPTool
26
+
27
+
28
+ @asynccontextmanager
29
+ async def _connect(
30
+ server: str | StdioServerParameters,
31
+ headers: Mapping[str, str] | None,
32
+ auth: httpx.Auth | None,
33
+ timeout: float,
34
+ ) -> AsyncIterator[ClientSession]:
35
+ async with AsyncExitStack() as stack:
36
+ if isinstance(server, str):
37
+ http_client = await stack.enter_async_context(
38
+ httpx.AsyncClient(headers=headers, auth=auth, timeout=timeout)
39
+ )
40
+ read, write, _ = await stack.enter_async_context(
41
+ streamable_http_client(server, http_client=http_client)
42
+ )
43
+ else:
44
+ read, write = await stack.enter_async_context(stdio_client(server))
45
+ session = await stack.enter_async_context(
46
+ ClientSession(
47
+ read, write, read_timeout_seconds=timedelta(seconds=timeout)
48
+ )
49
+ )
50
+ await session.initialize()
51
+ yield session
52
+
53
+
54
+ async def _list_tools(session: ClientSession) -> list[Tool]:
55
+ tools: list[Tool] = []
56
+ cursors: set[str] = set()
57
+ page = await session.list_tools()
58
+ while True:
59
+ tools.extend(page.tools)
60
+ cursor = page.nextCursor
61
+ if cursor is None:
62
+ return tools
63
+ if cursor in cursors:
64
+ raise ValueError(
65
+ "The MCP server returned a repeated tools/list cursor."
66
+ )
67
+ cursors.add(cursor)
68
+ page = await session.list_tools(cursor=cursor)
69
+
70
+
71
+ def _agent_name(remote_name: str) -> str:
72
+ if re.fullmatch(r"[A-Za-z0-9_-]{1,64}", remote_name):
73
+ return remote_name
74
+ prefix = re.sub(r"[^A-Za-z0-9_-]", "_", remote_name)[:47]
75
+ digest = sha256(remote_name.encode()).hexdigest()[:16]
76
+ return f"{prefix}_{digest}"
77
+
78
+
79
+ def _parameters(tool: Tool) -> list[ParameterBase]:
80
+ """Project simple fields for converters that use Swarmauri parameters."""
81
+ schema = tool.inputSchema
82
+ required = set(schema.get("required", []))
83
+ parameters = []
84
+ for name, prop in schema.get("properties", {}).items():
85
+ prop = prop if isinstance(prop, dict) else {}
86
+ prop_type = prop.get("type")
87
+ enum = prop.get("enum")
88
+ items = prop.get("items")
89
+ parameters.append(
90
+ ParameterBase(
91
+ name=name,
92
+ description=prop.get("description", ""),
93
+ required=name in required,
94
+ input_type=prop_type
95
+ if isinstance(prop_type, str)
96
+ else "string",
97
+ enum=enum
98
+ if enum and all(isinstance(value, str) for value in enum)
99
+ else None,
100
+ items={
101
+ key: value
102
+ for key, value in items.items()
103
+ if isinstance(value, str)
104
+ }
105
+ if isinstance(items, dict)
106
+ else None,
107
+ )
108
+ )
109
+ return parameters
110
+
111
+
112
+ @ComponentBase.register_type(ToolkitBase, "MCPToolkit")
113
+ class MCPToolkit(ToolkitBase):
114
+ """Expose tools discovered during an MCP client session."""
115
+
116
+ type: Literal["MCPToolkit"] = "MCPToolkit"
117
+
118
+ @classmethod
119
+ @contextmanager
120
+ def connect(
121
+ cls,
122
+ server: str | StdioServerParameters,
123
+ *,
124
+ headers: Mapping[str, str] | None = None,
125
+ auth: httpx.Auth | None = None,
126
+ timeout: float = 30,
127
+ allowed_tools: Collection[str] | None = None,
128
+ ) -> Iterator["MCPToolkit"]:
129
+ """Connect and discover tools for the lifetime of a context.
130
+
131
+ Args:
132
+ server: A Streamable HTTP endpoint URL or stdio server parameters.
133
+ headers: Optional authentication or application headers for HTTP.
134
+ auth: Optional HTTP auth provider, such as an MCP OAuth provider.
135
+ timeout: Request timeout in seconds.
136
+ allowed_tools: Original MCP tool names to expose, if specified.
137
+
138
+ Yields:
139
+ A toolkit with the discovered tools, bound to the open session.
140
+ """
141
+ if timeout <= 0:
142
+ raise ValueError("MCP request timeout must be positive.")
143
+ if headers is not None and not isinstance(server, str):
144
+ raise ValueError("MCP headers apply only to HTTP connections.")
145
+ if auth is not None:
146
+ if not isinstance(server, str):
147
+ raise ValueError(
148
+ "MCP HTTP auth applies only to HTTP connections."
149
+ )
150
+ if headers is not None and any(
151
+ name.lower() == "authorization" for name in headers
152
+ ):
153
+ raise ValueError("Use either auth or an Authorization header.")
154
+ if isinstance(allowed_tools, str):
155
+ raise TypeError("Pass allowed_tools as a collection of names.")
156
+
157
+ with start_blocking_portal() as portal, ExitStack() as connection:
158
+ session = connection.enter_context(
159
+ portal.wrap_async_context_manager(
160
+ _connect(server, headers, auth, timeout)
161
+ )
162
+ )
163
+ try:
164
+ toolkit = cls()
165
+ remote_names = set()
166
+ for definition in portal.call(_list_tools, session):
167
+ remote_name = definition.name
168
+ if (
169
+ allowed_tools is not None
170
+ and remote_name not in allowed_tools
171
+ ):
172
+ continue
173
+ name = _agent_name(remote_name)
174
+ if name in toolkit.tools:
175
+ raise ValueError(f"Duplicate MCP tool name: {name!r}")
176
+ tool = MCPTool(
177
+ name=name,
178
+ remote_name=remote_name,
179
+ description=definition.description or "",
180
+ parameters=_parameters(definition),
181
+ input_schema=definition.inputSchema,
182
+ )
183
+ tool._connection = (portal, session)
184
+ toolkit.add_tool(tool)
185
+ remote_names.add(remote_name)
186
+
187
+ missing = set(allowed_tools or ()) - remote_names
188
+ if missing:
189
+ raise ValueError(
190
+ f"MCP tools not found: {', '.join(sorted(missing))}"
191
+ )
192
+ yield toolkit
193
+ finally:
194
+ # Keep caller exceptions out of the MCP transport task group.
195
+ connection.close()
@@ -0,0 +1,9 @@
1
+ """Expose the MCP client toolkit and its remote tool adapter."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from swarmauri_toolkit_mcpclient.MCPToolkit import MCPToolkit
6
+ from swarmauri_toolkit_mcpclient.MCPTool import MCPTool
7
+
8
+ __version__ = version("swarmauri_toolkit_mcpclient")
9
+ __all__ = ["MCPTool", "MCPToolkit", "__version__"]