fix: fix client code
This commit is contained in:
parent
8873262d7a
commit
8acb5f97a2
1 changed files with 29 additions and 22 deletions
|
|
@ -19,7 +19,7 @@ Before starting, ensure your system meets these requirements:
|
||||||
|
|
||||||
## Setting Up Your Environment
|
## Setting Up Your Environment
|
||||||
|
|
||||||
First, create a new Python project with `uv`:
|
First, create a new Python project with `uv`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Create project directory
|
# Create project directory
|
||||||
|
|
@ -104,7 +104,7 @@ Next, we'll implement the method to connect to an MCP server:
|
||||||
```python
|
```python
|
||||||
async def connect_to_server(self, server_script_path: str):
|
async def connect_to_server(self, server_script_path: str):
|
||||||
"""Connect to an MCP server
|
"""Connect to an MCP server
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
server_script_path: Path to the server script (.py or .js)
|
server_script_path: Path to the server script (.py or .js)
|
||||||
"""
|
"""
|
||||||
|
|
@ -112,20 +112,20 @@ async def connect_to_server(self, server_script_path: str):
|
||||||
is_js = server_script_path.endswith('.js')
|
is_js = server_script_path.endswith('.js')
|
||||||
if not (is_python or is_js):
|
if not (is_python or is_js):
|
||||||
raise ValueError("Server script must be a .py or .js file")
|
raise ValueError("Server script must be a .py or .js file")
|
||||||
|
|
||||||
command = "python" if is_python else "node"
|
command = "python" if is_python else "node"
|
||||||
server_params = StdioServerParameters(
|
server_params = StdioServerParameters(
|
||||||
command=command,
|
command=command,
|
||||||
args=[server_script_path],
|
args=[server_script_path],
|
||||||
env=None
|
env=None
|
||||||
)
|
)
|
||||||
|
|
||||||
stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
|
stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
|
||||||
self.stdio, self.write = stdio_transport
|
self.stdio, self.write = stdio_transport
|
||||||
self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
|
self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
|
||||||
|
|
||||||
await self.session.initialize()
|
await self.session.initialize()
|
||||||
|
|
||||||
# List available tools
|
# List available tools
|
||||||
response = await self.session.list_tools()
|
response = await self.session.list_tools()
|
||||||
tools = response.tools
|
tools = response.tools
|
||||||
|
|
@ -147,7 +147,7 @@ async def process_query(self, query: str) -> str:
|
||||||
]
|
]
|
||||||
|
|
||||||
response = await self.session.list_tools()
|
response = await self.session.list_tools()
|
||||||
available_tools = [{
|
available_tools = [{
|
||||||
"name": tool.name,
|
"name": tool.name,
|
||||||
"description": tool.description,
|
"description": tool.description,
|
||||||
"input_schema": tool.inputSchema
|
"input_schema": tool.inputSchema
|
||||||
|
|
@ -165,27 +165,34 @@ async def process_query(self, query: str) -> str:
|
||||||
tool_results = []
|
tool_results = []
|
||||||
final_text = []
|
final_text = []
|
||||||
|
|
||||||
|
assistant_message_content = []
|
||||||
for content in response.content:
|
for content in response.content:
|
||||||
if content.type == 'text':
|
if content.type == 'text':
|
||||||
final_text.append(content.text)
|
final_text.append(content.text)
|
||||||
|
assistant_message_content.append(content)
|
||||||
elif content.type == 'tool_use':
|
elif content.type == 'tool_use':
|
||||||
tool_name = content.name
|
tool_name = content.name
|
||||||
tool_args = content.input
|
tool_args = content.input
|
||||||
|
|
||||||
# Execute tool call
|
# Execute tool call
|
||||||
result = await self.session.call_tool(tool_name, tool_args)
|
result = await self.session.call_tool(tool_name, tool_args)
|
||||||
tool_results.append({"call": tool_name, "result": result})
|
tool_results.append({"call": tool_name, "result": result})
|
||||||
final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
|
final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
|
||||||
|
|
||||||
# Continue conversation with tool results
|
assistant_message_content.append(content)
|
||||||
if hasattr(content, 'text') and content.text:
|
|
||||||
messages.append({
|
|
||||||
"role": "assistant",
|
|
||||||
"content": content.text
|
|
||||||
})
|
|
||||||
messages.append({
|
messages.append({
|
||||||
"role": "user",
|
"role": "assistant",
|
||||||
"content": result.content
|
"content": assistant_message_content
|
||||||
|
})
|
||||||
|
messages.append({
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{
|
||||||
|
"type": "tool_result",
|
||||||
|
"tool_use_id": content.id,
|
||||||
|
"content": result.content
|
||||||
|
}
|
||||||
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
# Get next response from Claude
|
# Get next response from Claude
|
||||||
|
|
@ -208,17 +215,17 @@ async def chat_loop(self):
|
||||||
"""Run an interactive chat loop"""
|
"""Run an interactive chat loop"""
|
||||||
print("\nMCP Client Started!")
|
print("\nMCP Client Started!")
|
||||||
print("Type your queries or 'quit' to exit.")
|
print("Type your queries or 'quit' to exit.")
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
query = input("\nQuery: ").strip()
|
query = input("\nQuery: ").strip()
|
||||||
|
|
||||||
if query.lower() == 'quit':
|
if query.lower() == 'quit':
|
||||||
break
|
break
|
||||||
|
|
||||||
response = await self.process_query(query)
|
response = await self.process_query(query)
|
||||||
print("\n" + response)
|
print("\n" + response)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"\nError: {str(e)}")
|
print(f"\nError: {str(e)}")
|
||||||
|
|
||||||
|
|
@ -236,7 +243,7 @@ async def main():
|
||||||
if len(sys.argv) < 2:
|
if len(sys.argv) < 2:
|
||||||
print("Usage: python client.py <path_to_server_script>")
|
print("Usage: python client.py <path_to_server_script>")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
client = MCPClient()
|
client = MCPClient()
|
||||||
try:
|
try:
|
||||||
await client.connect_to_server(sys.argv[1])
|
await client.connect_to_server(sys.argv[1])
|
||||||
|
|
@ -427,4 +434,4 @@ If you see:
|
||||||
>
|
>
|
||||||
Understand how MCP connects clients, servers, and LLMs
|
Understand how MCP connects clients, servers, and LLMs
|
||||||
</Card>
|
</Card>
|
||||||
</CardGroup>
|
</CardGroup>
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue