mcp-use 0.1.0__py3-none-any.whl → 1.0.1__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.

Potentially problematic release.


This version of mcp-use might be problematic. Click here for more details.

@@ -1,108 +0,0 @@
1
- """
2
- Tool converter for different LLM providers.
3
-
4
- This module provides utilities for converting between MCP tool schemas
5
- and LLM-specific formats.
6
- """
7
-
8
- from enum import Enum, auto
9
- from typing import Any
10
-
11
- from .formats import AnthropicToolFormat, OpenAIToolFormat, ToolFormat
12
-
13
-
14
- class ModelProvider(Enum):
15
- """Enum for supported model providers."""
16
-
17
- OPENAI = auto()
18
- ANTHROPIC = auto()
19
-
20
- @classmethod
21
- def from_string(cls, value: str) -> "ModelProvider":
22
- """Convert a string to a ModelProvider enum.
23
-
24
- Args:
25
- value: The string to convert.
26
-
27
- Returns:
28
- The corresponding ModelProvider enum value.
29
-
30
- Raises:
31
- ValueError: If the string is not a valid model provider.
32
- """
33
- value = value.lower()
34
- if value in ("openai", "open_ai", "open-ai"):
35
- return cls.OPENAI
36
- elif value in ("anthropic", "claude"):
37
- return cls.ANTHROPIC
38
- else:
39
- raise ValueError(f"Unsupported model provider: {value}")
40
-
41
-
42
- class ToolConverter:
43
- """Converter for MCP tools to different LLM formats.
44
-
45
- This class provides utilities for converting between MCP tool schemas
46
- and LLM-specific formats.
47
- """
48
-
49
- _format_classes: dict[ModelProvider, type[ToolFormat]] = {
50
- ModelProvider.OPENAI: OpenAIToolFormat,
51
- ModelProvider.ANTHROPIC: AnthropicToolFormat,
52
- }
53
-
54
- def __init__(self, provider: str | ModelProvider) -> None:
55
- """Initialize a new tool converter.
56
-
57
- Args:
58
- provider: The model provider to convert tools for.
59
- Can be a string or a ModelProvider enum.
60
-
61
- Raises:
62
- ValueError: If the provider is not supported.
63
- """
64
- if isinstance(provider, str):
65
- self.provider = ModelProvider.from_string(provider)
66
- else:
67
- self.provider = provider
68
-
69
- # Create an instance of the appropriate format class
70
- format_class = self._format_classes.get(self.provider)
71
- if not format_class:
72
- raise ValueError(f"Unsupported model provider: {provider}")
73
-
74
- self._format = format_class()
75
-
76
- def convert_tools(self, tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
77
- """Convert a list of MCP tools to the LLM-specific format.
78
-
79
- Args:
80
- tools: The list of MCP tools to convert.
81
-
82
- Returns:
83
- The converted tools in the LLM-specific format.
84
- """
85
- return [self._format.convert_tool(tool) for tool in tools]
86
-
87
- def convert_tool_call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
88
- """Convert a tool call to the MCP format.
89
-
90
- Args:
91
- name: The name of the tool being called.
92
- arguments: The arguments for the tool call.
93
-
94
- Returns:
95
- The converted tool call in the MCP format.
96
- """
97
- return self._format.convert_tool_call(name, arguments)
98
-
99
- def parse_tool_calls(self, response: dict[str, Any]) -> list[dict[str, Any]]:
100
- """Parse tool calls from an LLM response.
101
-
102
- Args:
103
- response: The response from the LLM.
104
-
105
- Returns:
106
- A list of parsed tool calls, each containing 'name' and 'arguments' keys.
107
- """
108
- return self._format.parse_tool_call(response)
mcp_use/tools/formats.py DELETED
@@ -1,181 +0,0 @@
1
- """
2
- Tool format definitions for different LLM providers.
3
-
4
- This module provides type definitions and interfaces for converting
5
- MCP tool schemas to formats required by different LLM providers.
6
- """
7
-
8
- from abc import ABC, abstractmethod
9
- from typing import Any
10
-
11
-
12
- class ToolFormat(ABC):
13
- """Base class for LLM tool formats.
14
-
15
- This abstract class defines the interface for converting MCP tool schemas
16
- to the format required by a specific LLM provider.
17
- """
18
-
19
- @abstractmethod
20
- def convert_tool(self, tool: dict[str, Any]) -> dict[str, Any]:
21
- """Convert an MCP tool schema to the LLM-specific format.
22
-
23
- Args:
24
- tool: The MCP tool schema to convert.
25
-
26
- Returns:
27
- The converted tool in the LLM-specific format.
28
- """
29
- pass
30
-
31
- @abstractmethod
32
- def convert_tool_call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
33
- """Convert a tool call from the LLM format to the MCP format.
34
-
35
- Args:
36
- name: The name of the tool being called.
37
- arguments: The arguments for the tool call.
38
-
39
- Returns:
40
- The converted tool call in the MCP format.
41
- """
42
- pass
43
-
44
- @abstractmethod
45
- def parse_tool_call(self, response: dict[str, Any]) -> list[dict[str, Any]]:
46
- """Parse tool calls from the LLM response.
47
-
48
- Args:
49
- response: The response from the LLM.
50
-
51
- Returns:
52
- A list of parsed tool calls, each containing 'name' and 'arguments' keys.
53
- """
54
- pass
55
-
56
-
57
- class OpenAIToolFormat(ToolFormat):
58
- """Tool format for OpenAI models.
59
-
60
- This class converts between MCP tool schemas and the format required by
61
- OpenAI's function calling API.
62
- """
63
-
64
- def convert_tool(self, tool: dict[str, Any]) -> dict[str, Any]:
65
- """Convert an MCP tool schema to the OpenAI function format.
66
-
67
- Args:
68
- tool: The MCP tool schema to convert.
69
-
70
- Returns:
71
- The converted tool in the OpenAI function format.
72
- """
73
- return {
74
- "type": "function",
75
- "function": {
76
- "name": tool["name"],
77
- "description": tool.get("description", ""),
78
- "parameters": tool.get("inputSchema", {}),
79
- },
80
- }
81
-
82
- def convert_tool_call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
83
- """Convert a tool call from the OpenAI format to the MCP format.
84
-
85
- Args:
86
- name: The name of the tool being called.
87
- arguments: The arguments for the tool call.
88
-
89
- Returns:
90
- The converted tool call in the MCP format.
91
- """
92
- return {"name": name, "arguments": arguments}
93
-
94
- def parse_tool_call(self, response: dict[str, Any]) -> list[dict[str, Any]]:
95
- """Parse tool calls from the OpenAI response.
96
-
97
- Args:
98
- response: The response from OpenAI.
99
-
100
- Returns:
101
- A list of parsed tool calls, each containing 'name' and 'arguments' keys.
102
- """
103
- tool_calls = []
104
-
105
- # Navigate through the response structure to find tool calls
106
- for message in response.get("choices", [{}])[0].get("message", {}).get("tool_calls", []):
107
- if message.get("type") == "function":
108
- function = message.get("function", {})
109
- name = function.get("name", "")
110
-
111
- # Parse the arguments
112
- arguments = {}
113
- args_str = function.get("arguments", "{}")
114
- try:
115
- import json
116
-
117
- arguments = json.loads(args_str)
118
- except Exception:
119
- pass
120
-
121
- tool_calls.append({"name": name, "arguments": arguments})
122
-
123
- return tool_calls
124
-
125
-
126
- class AnthropicToolFormat(ToolFormat):
127
- """Tool format for Anthropic models.
128
-
129
- This class converts between MCP tool schemas and the format required by
130
- Anthropic's tool use API.
131
- """
132
-
133
- def convert_tool(self, tool: dict[str, Any]) -> dict[str, Any]:
134
- """Convert an MCP tool schema to the Anthropic tool format.
135
-
136
- Args:
137
- tool: The MCP tool schema to convert.
138
-
139
- Returns:
140
- The converted tool in the Anthropic tool format.
141
- """
142
- return {
143
- "name": tool["name"],
144
- "description": tool.get("description", ""),
145
- "input_schema": tool.get("inputSchema", {}),
146
- }
147
-
148
- def convert_tool_call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
149
- """Convert a tool call from the Anthropic format to the MCP format.
150
-
151
- Args:
152
- name: The name of the tool being called.
153
- arguments: The arguments for the tool call.
154
-
155
- Returns:
156
- The converted tool call in the MCP format.
157
- """
158
- return {"name": name, "arguments": arguments}
159
-
160
- def parse_tool_call(self, response: dict[str, Any]) -> list[dict[str, Any]]:
161
- """Parse tool calls from the Anthropic response.
162
-
163
- Args:
164
- response: The response from Anthropic.
165
-
166
- Returns:
167
- A list of parsed tool calls, each containing 'name' and 'arguments' keys.
168
- """
169
- tool_calls = []
170
-
171
- # Navigate through the response structure to find tool calls
172
- content_blocks = response.get("content", [])
173
- for block in content_blocks:
174
- if block.get("type") == "tool_use":
175
- tool_use = block.get("tool_use", {})
176
- name = tool_use.get("name", "")
177
- arguments = tool_use.get("input", {})
178
-
179
- tool_calls.append({"name": name, "arguments": arguments})
180
-
181
- return tool_calls
mcp_use/types.py DELETED
@@ -1,33 +0,0 @@
1
- """
2
- Type definitions for the mcp_use package.
3
-
4
- This module provides type definitions used throughout the mcp_use package.
5
- """
6
-
7
- from typing import Any
8
-
9
- from pydantic import BaseModel
10
-
11
-
12
- class Tool(BaseModel):
13
- """MCP Tool definition."""
14
-
15
- name: str
16
- description: str | None = None
17
- inputSchema: dict[str, Any] = {}
18
- outputSchema: dict[str, Any] | None = None
19
-
20
-
21
- class TextContent(BaseModel):
22
- """Text content returned by an MCP tool."""
23
-
24
- type: str = "text"
25
- text: str
26
- mime_type: str | None = "text/plain"
27
-
28
-
29
- class ToolResult(BaseModel):
30
- """Result of a tool execution."""
31
-
32
- content: list[TextContent | dict[str, Any]]
33
- isError: bool = False
@@ -1,287 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: mcp_use
3
- Version: 0.1.0
4
- Summary: Model-Agnostic MCP Library for LLMs
5
- Home-page: https://github.com/pietrozullo/mcp_use
6
- Author: Pietro Zullo
7
- Author-email: pietro.zullo@gmail.com
8
- Classifier: Development Status :: 3 - Alpha
9
- Classifier: Intended Audience :: Developers
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Operating System :: OS Independent
12
- Classifier: Programming Language :: Python :: 3
13
- Classifier: Programming Language :: Python :: 3.11
14
- Classifier: Programming Language :: Python :: 3.12
15
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
- Requires-Python: >=3.11
17
- Description-Content-Type: text/markdown
18
- License-File: LICENSE
19
- Requires-Dist: mcp
20
- Requires-Dist: langchain>=0.1.0
21
- Requires-Dist: langchain-community>=0.0.10
22
- Requires-Dist: websockets>=12.0
23
- Requires-Dist: aiohttp>=3.9.0
24
- Requires-Dist: pydantic>=2.0.0
25
- Requires-Dist: typing-extensions>=4.8.0
26
- Requires-Dist: jsonschema-pydantic>=0.1.0
27
- Requires-Dist: python-dotenv>=1.0.0
28
- Provides-Extra: dev
29
- Requires-Dist: pytest>=7.4.0; extra == "dev"
30
- Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
31
- Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
32
- Requires-Dist: black>=23.9.0; extra == "dev"
33
- Requires-Dist: isort>=5.12.0; extra == "dev"
34
- Requires-Dist: mypy>=1.5.0; extra == "dev"
35
- Requires-Dist: ruff>=0.1.0; extra == "dev"
36
- Provides-Extra: anthropic
37
- Requires-Dist: anthropic>=0.15.0; extra == "anthropic"
38
- Provides-Extra: openai
39
- Requires-Dist: openai>=1.10.0; extra == "openai"
40
- Dynamic: author
41
- Dynamic: author-email
42
- Dynamic: classifier
43
- Dynamic: description
44
- Dynamic: description-content-type
45
- Dynamic: home-page
46
- Dynamic: license-file
47
- Dynamic: provides-extra
48
- Dynamic: requires-dist
49
- Dynamic: requires-python
50
- Dynamic: summary
51
-
52
- # Model-Agnostic MCP Library for LLMs
53
-
54
- A Python library that lets any LLM (Language Learning Model) use MCP (Multi-Channel Platform) tools through a unified interface. The goal is to let developers easily connect any LLM to tools like web browsing, file operations, etc.
55
-
56
- ## Core Concept
57
-
58
- - Leverage existing LangChain adapters rather than reinventing them
59
- - Focus on bridging MCPs and LangChain's tool ecosystem
60
-
61
- ## Key Components
62
-
63
- ### Connectors
64
-
65
- Bridge to MCP implementations:
66
-
67
- - `stdio.py`: For local MCP processes
68
- - `websocket.py`: For remote WebSocket MCPs
69
- - `http.py`: For HTTP API MCPs
70
-
71
- ### Tool Conversion
72
-
73
- Convert between MCP and LangChain formats:
74
-
75
- - Convert MCP tool schemas to formats needed by different LLMs
76
- - Support OpenAI function calling, Anthropic tool format, etc.
77
-
78
- ### Session Management
79
-
80
- Handle connection lifecycle:
81
-
82
- - Authenticate and initialize MCP connections
83
- - Discover and register available tools
84
- - Handle tool calling with proper error management
85
-
86
- ### Agent Integration
87
-
88
- Ready-to-use agent implementations:
89
-
90
- - Pre-configured for MCP tool usage
91
- - Optimized prompts for tool selection
92
-
93
- ## Installation
94
-
95
- ```bash
96
- pip install mcp_use
97
- ```
98
-
99
- Or install from source:
100
-
101
- ```bash
102
- git clone https://github.com/pietrozullo/mcp_use.git
103
- cd mcp_use
104
- pip install -e .
105
- ```
106
-
107
- ## Quick Start
108
-
109
- Here's a simple example to get you started:
110
-
111
- ```python
112
- import asyncio
113
- from mcp import StdioServerParameters
114
- from mcp_use import MCPAgent
115
-
116
- async def main():
117
- # Create server parameters for stdio connection
118
- server_params = StdioServerParameters(
119
- command="npx",
120
- args=["@playwright/mcp@latest"],
121
- )
122
-
123
- # Create a model-agnostic MCP client
124
- mcp_client = MCPAgent(
125
- server_params=server_params,
126
- model_provider="anthropic", # Or "openai"
127
- model_name="claude-3-7-sonnet-20250219", # Or "gpt-4o" for OpenAI
128
- temperature=0.7
129
- )
130
-
131
- # Initialize the client
132
- await mcp_client.initialize()
133
-
134
- # Run a query using the agent with tools
135
- result = await mcp_client.run_query(
136
- "Using internet tell me how many people work at OpenAI"
137
- )
138
-
139
- print("Result:")
140
- print(result)
141
-
142
- # Close the client
143
- await mcp_client.close()
144
-
145
- if __name__ == "__main__":
146
- asyncio.run(main())
147
- ```
148
-
149
- ## Simplified Usage
150
-
151
- You can also use the simplified interface that handles connector lifecycle management automatically:
152
-
153
- ```python
154
- import asyncio
155
- from langchain_openai import ChatOpenAI
156
- from mcp_use import MCPAgent
157
- from mcp_use.connectors.stdio import StdioConnector
158
-
159
- async def main():
160
- # Create the connector
161
- connector = StdioConnector(
162
- command="npx",
163
- args=["@playwright/mcp@latest"],
164
- )
165
-
166
- # Create the LLM
167
- llm = ChatOpenAI(model="gpt-4o-mini")
168
-
169
- # Create MCP client
170
- mcp_client = MCPAgent(connector=connector, llm=llm, max_steps=30)
171
-
172
- # Run a query - MCPAgent handles connector lifecycle internally
173
- result = await mcp_client.run(
174
- "Using internet tell me how many people work at OpenAI",
175
- # manage_connector=True is the default
176
- )
177
-
178
- print("Result:")
179
- print(result)
180
-
181
- if __name__ == "__main__":
182
- asyncio.run(main())
183
- ```
184
-
185
- ## Configuration File Support
186
-
187
- mcp_use supports initialization from configuration files, making it easy to manage and switch between different MCP server setups:
188
-
189
- ```python
190
- import asyncio
191
- from mcp_use import create_session_from_config
192
-
193
- async def main():
194
- # Create an MCP session from a config file
195
- session = create_session_from_config("mcp-config.json")
196
-
197
- # Initialize the session
198
- await session.initialize()
199
-
200
- # Use the session...
201
-
202
- # Disconnect when done
203
- await session.disconnect()
204
-
205
- if __name__ == "__main__":
206
- asyncio.run(main())
207
- ```
208
-
209
- Example configuration file (`mcp-config.json`):
210
-
211
- ```json
212
- {
213
- "mcpServers": {
214
- "playwright": {
215
- "command": "npx",
216
- "args": ["@playwright/mcp@latest", "headless"],
217
- "env": {
218
- "PLAYWRIGHT_WS_ENDPOINT": "ws://localhost:41965/"
219
- }
220
- }
221
- }
222
- }
223
- ```
224
-
225
- ## MCPClient for Managing Multiple Servers
226
-
227
- The `MCPClient` class provides a higher-level abstraction for managing multiple MCP servers from a single client:
228
-
229
- ```python
230
- import asyncio
231
- from langchain_anthropic import ChatAnthropic
232
- from mcp_use import MCPAgent, MCPClient
233
-
234
- async def main():
235
- # Create a client from a config file
236
- client = MCPClient.from_config_file("mcp-config.json")
237
-
238
- # Or initialize with a config file path
239
- # client = MCPClient("mcp-config.json")
240
-
241
- # Or programmatically add servers
242
- client.add_server(
243
- "local-ws",
244
- {
245
- "command": "npx",
246
- "args": ["@playwright/mcp@latest", "headless"]
247
- }
248
- )
249
-
250
- # Create an LLM
251
- llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")
252
-
253
- # Create an agent using the client
254
- agent = MCPAgent(
255
- llm=llm,
256
- client=client,
257
- server_name="playwright", # Optional, uses first server if not specified
258
- max_steps=30
259
- )
260
-
261
- # Run a query
262
- result = await agent.run("Your query here")
263
-
264
- # Close all sessions
265
- await client.close_all_sessions()
266
-
267
- if __name__ == "__main__":
268
- asyncio.run(main())
269
- ```
270
-
271
- This approach simplifies working with multiple MCP servers and allows for more dynamic configuration management.
272
-
273
- ## Advanced Usage
274
-
275
- See the `examples` directory for more advanced usage examples:
276
-
277
- - `browser_use.py`: Shows how to use MCPClient with configuration files for browser automation
278
-
279
- ## Requirements
280
-
281
- - Python 3.11+
282
- - MCP implementation (like Playwright MCP)
283
- - LangChain and appropriate model libraries (OpenAI, Anthropic, etc.)
284
-
285
- ## License
286
-
287
- MIT
@@ -1,23 +0,0 @@
1
- mcp_use/__init__.py,sha256=k_D8e8BbU7OEzXlbkGgKayfgoSU1frQhWd2RxoLOT6E,838
2
- mcp_use/client.py,sha256=nu_SXM_WNHaV8354uZN8ZtV9iL0p9Gnloh56Zof44vk,7162
3
- mcp_use/config.py,sha256=Q-ItKT-gzFN2NiHhss1S7MKVu4cHj2nOshd_mjJ0upY,3232
4
- mcp_use/logging.py,sha256=2-hSB7ZWcHEx_OFHNg8GIbSGCZx3MW4mZGGWxi2Ew3E,2690
5
- mcp_use/session.py,sha256=-Zz6EMliZ10ZJdFY-jFa3xFCdSJetN0BoQVJ3eAAfc4,5343
6
- mcp_use/types.py,sha256=_HajP_FjhUzw9y9_cHWL20dVP5555oyESS_T717fDUI,675
7
- mcp_use/agents/__init__.py,sha256=ukchMTqCOID6ikvLmJ-6sldWTVFIzztGQo4BX6QeQr8,312
8
- mcp_use/agents/base.py,sha256=bfuldi_89AbSbNc8KeTiCArRT9V62CNxHOWYkLHWjyA,1605
9
- mcp_use/agents/langchain_agent.py,sha256=Tmsu1N5RIsLqLJzjlxODG6zMYFoCshZ7iwGpxAIIBL8,8904
10
- mcp_use/agents/mcpagent.py,sha256=R1cjgx2sjbCrr0lHJSOEnoA8UIH_aTk1xyuf6z_RGFU,5434
11
- mcp_use/connectors/__init__.py,sha256=jnd-7pPPJMb0UNJ6aD9lInj5Tlamc8lA_mFyG8RWJpo,385
12
- mcp_use/connectors/base.py,sha256=bTFxtejKhFFqhBetj1yAdkn1EXjP3YtHUdQDYOxA4uU,1642
13
- mcp_use/connectors/http.py,sha256=ryNOJFof98rAKkIzccMQNLYtzu1V2KC9s8R2PKP4EFY,4702
14
- mcp_use/connectors/stdio.py,sha256=LjbrPu8FtB1FLMLBdK7NpRQrYMhx_QITdZWH3e47fW8,4483
15
- mcp_use/connectors/websocket.py,sha256=nRMaURCP1d1dGTAHCn49RFOWKLtKAqdWot04STgtodg,5301
16
- mcp_use/tools/__init__.py,sha256=-fOvmDVWd3LAga1VNoQsZ5Fm7b4DtMvR1Wi8RtUnYMs,333
17
- mcp_use/tools/converter.py,sha256=4KuRTEPIFN-babh_mK7ltXwnlDu-c4XsjZiL3b2x_M0,3294
18
- mcp_use/tools/formats.py,sha256=PDWbmMLkxLftDo5EHAMAKYTBhOmrHpi73w1ee5xJhtw,5666
19
- mcp_use-0.1.0.dist-info/licenses/LICENSE,sha256=7Pw7dbwJSBw8zH-WE03JnR5uXvitRtaGTP9QWPcexcs,1068
20
- mcp_use-0.1.0.dist-info/METADATA,sha256=3_ud5LMbAqJbvEwwPa23BcFLBhie7ypZKyRvhRaRqJg,7340
21
- mcp_use-0.1.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
22
- mcp_use-0.1.0.dist-info/top_level.txt,sha256=xK9hG-ab5BJu7z6yGSxpeT3eVVTyzbpFiwJ0h8oknBM,8
23
- mcp_use-0.1.0.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- mcp_use