forked from awslabs/mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_test_client.py
More file actions
154 lines (124 loc) · 5.38 KB
/
mcp_test_client.py
File metadata and controls
154 lines (124 loc) · 5.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""MCP Test Client using the official MCP Python SDK."""
import logging
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
class StdioMcpClient:
"""MCP client for testing servers over stdio transport using the official SDK."""
def __init__(self, command: str, args: List[str], env: Optional[Dict[str, str]] = None):
"""Initialize the MCP test client."""
self.command = command
self.args = args
self.env = env or {}
self.server_params = StdioServerParameters(command=command, args=args, env=self.env)
self.session: Optional[ClientSession] = None
self._capabilities: Optional[Dict[str, Any]] = None
async def connect(self) -> Dict[str, Any]:
"""Connect to the MCP server and initialize the connection."""
try:
# Create stdio client and session
self.transport = stdio_client(self.server_params)
self.read, self.write = await self.transport.__aenter__()
self.session = ClientSession(self.read, self.write)
await self.session.__aenter__()
# Initialize the session
init_result = await self.session.initialize()
self._capabilities = (
init_result.serverInfo.model_dump() if init_result.serverInfo else {}
)
logger.info('Successfully connected to MCP server')
return self._capabilities
except Exception as e:
logger.error(f'Failed to connect to MCP server: {e}')
await self.disconnect()
raise
async def disconnect(self):
"""Disconnect from the MCP server and cleanup resources."""
try:
if self.session:
await self.session.__aexit__(None, None, None)
if hasattr(self, 'transport'):
await self.transport.__aexit__(None, None, None)
except Exception as e:
logger.error(f'Error during disconnect: {e}')
finally:
self.session = None
self._capabilities = None
async def ping(self) -> bool:
"""Send a ping to the server to check if it's alive."""
try:
# MCP doesn't have a standard ping method, so we'll try to list tools
# If it succeeds, the server is alive
await self.session.list_tools()
return True
except Exception as e:
logger.error(f'Ping failed: {e}')
return False
async def list_tools(self) -> List[types.Tool]:
"""List all available tools."""
try:
tools_response = await self.session.list_tools()
return tools_response.tools
except Exception as e:
logger.error(f'Failed to list tools: {e}')
return []
async def call_tool(self, name: str, arguments: Dict[str, Any]) -> types.CallToolResult:
"""Call a specific tool with given arguments."""
try:
result = await self.session.call_tool(name, arguments)
return result
except Exception as e:
logger.error(f'Failed to call tool {name}: {e}')
raise
async def list_resources(self) -> List[types.Resource]:
"""List all available resources."""
try:
resources_response = await self.session.list_resources()
return resources_response.resources
except Exception as e:
logger.error(f'Failed to list resources: {e}')
return []
async def read_resource(self, uri: str) -> types.ReadResourceResult:
"""Read a specific resource."""
try:
result = await self.session.read_resource(uri)
return result
except Exception as e:
logger.error(f'Failed to read resource {uri}: {e}')
raise
async def list_prompts(self) -> List[types.Prompt]:
"""List all available prompts."""
try:
prompts_response = await self.session.list_prompts()
return prompts_response.prompts
except Exception as e:
logger.error(f'Failed to list prompts: {e}')
return []
async def get_prompt(self, name: str, arguments: Dict[str, Any]) -> types.GetPromptResult:
"""Get a specific prompt with given arguments."""
try:
result = await self.session.get_prompt(name, arguments)
return result
except Exception as e:
logger.error(f'Failed to get prompt {name}: {e}')
raise
@property
def capabilities(self) -> Optional[Dict[str, Any]]:
"""Get the server capabilities."""
return self._capabilities
# Alias for backward compatibility
MCPTestClient = StdioMcpClient