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