chuk-tool-processor 0.4.1__py3-none-any.whl → 0.5.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 chuk-tool-processor might be problematic. Click here for more details.

@@ -1,9 +1,9 @@
1
1
  # chuk_tool_processor/mcp/transport/stdio_transport.py
2
2
  from __future__ import annotations
3
3
 
4
- from contextlib import AsyncExitStack
5
4
  import json
6
5
  from typing import Dict, Any, List, Optional
6
+ import logging
7
7
 
8
8
  # ------------------------------------------------------------------ #
9
9
  # Local import #
@@ -11,187 +11,382 @@ from typing import Dict, Any, List, Optional
11
11
  from .base_transport import MCPBaseTransport
12
12
 
13
13
  # ------------------------------------------------------------------ #
14
- # chuk-protocol imports #
14
+ # New chuk-mcp API imports only #
15
15
  # ------------------------------------------------------------------ #
16
- from chuk_mcp.mcp_client.transport.stdio.stdio_client import stdio_client
17
- from chuk_mcp.mcp_client.messages.initialize.send_messages import send_initialize
18
- from chuk_mcp.mcp_client.messages.ping.send_messages import send_ping
16
+ from chuk_mcp.transports.stdio import stdio_client
17
+ from chuk_mcp.transports.stdio.parameters import StdioParameters
19
18
 
20
- # tools
21
- from chuk_mcp.mcp_client.messages.tools.send_messages import (
22
- send_tools_call,
19
+ from chuk_mcp.protocol.messages import (
20
+ send_initialize,
21
+ send_ping,
23
22
  send_tools_list,
23
+ send_tools_call,
24
24
  )
25
25
 
26
- # NEW: resources & prompts
27
- from chuk_mcp.mcp_client.messages.resources.send_messages import (
28
- send_resources_list,
29
- )
30
- from chuk_mcp.mcp_client.messages.prompts.send_messages import (
31
- send_prompts_list,
32
- )
26
+ # Try to import resources and prompts if available
27
+ try:
28
+ from chuk_mcp.protocol.messages import (
29
+ send_resources_list,
30
+ send_resources_read,
31
+ )
32
+ HAS_RESOURCES = True
33
+ except ImportError:
34
+ HAS_RESOURCES = False
35
+
36
+ try:
37
+ from chuk_mcp.protocol.messages import (
38
+ send_prompts_list,
39
+ send_prompts_get,
40
+ )
41
+ HAS_PROMPTS = True
42
+ except ImportError:
43
+ HAS_PROMPTS = False
44
+
45
+ logger = logging.getLogger(__name__)
33
46
 
34
47
 
35
48
  class StdioTransport(MCPBaseTransport):
36
49
  """
37
- Stdio transport for MCP communication.
50
+ STDIO transport for MCP communication using new chuk-mcp APIs.
38
51
  """
39
52
 
40
53
  def __init__(self, server_params):
41
- self.server_params = server_params
54
+ """
55
+ Initialize STDIO transport.
56
+
57
+ Args:
58
+ server_params: Either a dict with 'command' and 'args',
59
+ or a StdioParameters object
60
+ """
61
+ # Convert dict format to StdioParameters
62
+ if isinstance(server_params, dict):
63
+ self.server_params = StdioParameters(
64
+ command=server_params.get('command', 'python'),
65
+ args=server_params.get('args', [])
66
+ )
67
+ else:
68
+ self.server_params = server_params
69
+
42
70
  self.read_stream = None
43
71
  self.write_stream = None
44
- self._context_stack: Optional[AsyncExitStack] = None
72
+ self._client_context = None
45
73
 
46
74
  # --------------------------------------------------------------------- #
47
75
  # Connection management #
48
76
  # --------------------------------------------------------------------- #
49
77
  async def initialize(self) -> bool:
78
+ """Initialize the STDIO transport."""
50
79
  try:
51
- self._context_stack = AsyncExitStack()
52
- await self._context_stack.__aenter__()
53
-
54
- ctx = stdio_client(self.server_params)
55
- self.read_stream, self.write_stream = await self._context_stack.enter_async_context(
56
- ctx
57
- )
58
-
80
+ logger.info("Initializing STDIO transport...")
81
+
82
+ # Use the new stdio_client context manager
83
+ self._client_context = stdio_client(self.server_params)
84
+ self.read_stream, self.write_stream = await self._client_context.__aenter__()
85
+
86
+ # Send initialize message
87
+ logger.debug("Sending initialize message...")
59
88
  init_result = await send_initialize(self.read_stream, self.write_stream)
60
- return bool(init_result)
89
+
90
+ if init_result:
91
+ logger.info("STDIO transport initialized successfully")
92
+ return True
93
+ else:
94
+ logger.error("Initialize message failed")
95
+ await self._cleanup()
96
+ return False
61
97
 
62
- except Exception as e: # pragma: no cover
63
- import logging
98
+ except Exception as e:
99
+ logger.error(f"Error initializing STDIO transport: {e}", exc_info=True)
100
+ await self._cleanup()
101
+ return False
64
102
 
65
- logging.error(f"Error initializing stdio transport: {e}")
66
- if self._context_stack:
103
+ async def close(self) -> None:
104
+ """Close the transport with proper error handling."""
105
+ try:
106
+ # Handle both old _context_stack and new _client_context for test compatibility
107
+ if hasattr(self, '_context_stack') and self._context_stack:
67
108
  try:
68
109
  await self._context_stack.__aexit__(None, None, None)
69
- except Exception:
70
- pass
71
- return False
110
+ logger.debug("Context stack closed")
111
+ except asyncio.CancelledError:
112
+ # Expected during shutdown - don't log as error
113
+ logger.debug("Context stack close cancelled during shutdown")
114
+ except Exception as e:
115
+ logger.error(f"Error closing context stack: {e}")
116
+ elif self._client_context:
117
+ try:
118
+ await self._client_context.__aexit__(None, None, None)
119
+ logger.debug("STDIO client context closed")
120
+ except asyncio.CancelledError:
121
+ # Expected during shutdown - don't log as error
122
+ logger.debug("Client context close cancelled during shutdown")
123
+ except Exception as e:
124
+ logger.error(f"Error closing client context: {e}")
125
+ except Exception as e:
126
+ logger.error(f"Error during transport cleanup: {e}")
127
+ finally:
128
+ await self._cleanup()
72
129
 
73
- async def close(self) -> None:
74
- if self._context_stack:
75
- try:
76
- await self._context_stack.__aexit__(None, None, None)
77
- except Exception:
78
- pass
130
+ async def _cleanup(self) -> None:
131
+ """Internal cleanup method."""
132
+ # Clean up both old and new context attributes for test compatibility
133
+ if hasattr(self, '_context_stack'):
134
+ self._context_stack = None
135
+ self._client_context = None
79
136
  self.read_stream = None
80
137
  self.write_stream = None
81
- self._context_stack = None
82
138
 
83
139
  # --------------------------------------------------------------------- #
84
- # Utility #
140
+ # Core MCP Operations #
85
141
  # --------------------------------------------------------------------- #
86
142
  async def send_ping(self) -> bool:
143
+ """Send a ping."""
87
144
  if not self.read_stream or not self.write_stream:
145
+ logger.error("Cannot send ping: streams not available")
146
+ return False
147
+
148
+ try:
149
+ result = await send_ping(self.read_stream, self.write_stream)
150
+ logger.debug(f"Ping result: {result}")
151
+ return bool(result)
152
+ except Exception as e:
153
+ logger.error(f"Ping failed: {e}")
88
154
  return False
89
- return await send_ping(self.read_stream, self.write_stream)
90
155
 
91
156
  async def get_tools(self) -> List[Dict[str, Any]]:
157
+ """Get list of available tools."""
92
158
  if not self.read_stream or not self.write_stream:
159
+ logger.error("Cannot get tools: streams not available")
160
+ return []
161
+
162
+ try:
163
+ tools_response = await send_tools_list(self.read_stream, self.write_stream)
164
+
165
+ # Handle both dict response and direct tools list
166
+ if isinstance(tools_response, dict):
167
+ tools = tools_response.get("tools", [])
168
+ elif isinstance(tools_response, list):
169
+ tools = tools_response
170
+ else:
171
+ logger.warning(f"Unexpected tools response type: {type(tools_response)}")
172
+ tools = []
173
+
174
+ logger.debug(f"Retrieved {len(tools)} tools")
175
+ return tools
176
+
177
+ except Exception as e:
178
+ logger.error(f"Error getting tools: {e}")
93
179
  return []
94
- tools_response = await send_tools_list(self.read_stream, self.write_stream)
95
- return tools_response.get("tools", [])
96
180
 
97
- # NEW ------------------------------------------------------------------ #
98
- # Resources / Prompts #
99
- # --------------------------------------------------------------------- #
100
- async def list_resources(self) -> Dict[str, Any]:
181
+ async def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
101
182
  """
102
- Return the result of *resources/list*. If the connection is not yet
103
- initialised an empty dict is returned.
183
+ Execute a tool.
184
+
185
+ Returns normalized response in format:
186
+ {
187
+ "isError": bool,
188
+ "content": Any, # Result data if successful
189
+ "error": str # Error message if failed
190
+ }
104
191
  """
105
192
  if not self.read_stream or not self.write_stream:
193
+ return {
194
+ "isError": True,
195
+ "error": "Transport not initialized"
196
+ }
197
+
198
+ try:
199
+ logger.debug(f"Calling tool {tool_name} with args: {arguments}")
200
+
201
+ raw_response = await send_tools_call(
202
+ self.read_stream,
203
+ self.write_stream,
204
+ tool_name,
205
+ arguments
206
+ )
207
+
208
+ logger.debug(f"Tool {tool_name} raw response: {raw_response}")
209
+ return self._normalize_tool_response(raw_response)
210
+
211
+ except Exception as e:
212
+ logger.error(f"Error calling tool {tool_name}: {e}")
213
+ return {
214
+ "isError": True,
215
+ "error": f"Tool execution failed: {str(e)}"
216
+ }
217
+
218
+ def _normalize_tool_response(self, raw_response: Dict[str, Any]) -> Dict[str, Any]:
219
+ """Normalize tool response to consistent format."""
220
+ # Handle explicit error in response
221
+ if "error" in raw_response:
222
+ error_info = raw_response["error"]
223
+ if isinstance(error_info, dict):
224
+ error_msg = error_info.get("message", "Unknown error")
225
+ else:
226
+ error_msg = str(error_info)
227
+
228
+ return {
229
+ "isError": True,
230
+ "error": error_msg
231
+ }
232
+
233
+ # Handle successful response with result (MCP standard)
234
+ if "result" in raw_response:
235
+ result = raw_response["result"]
236
+
237
+ # If result has content, extract it
238
+ if isinstance(result, dict) and "content" in result:
239
+ return {
240
+ "isError": False,
241
+ "content": self._extract_content(result["content"])
242
+ }
243
+ else:
244
+ return {
245
+ "isError": False,
246
+ "content": result
247
+ }
248
+
249
+ # Handle direct content-based response
250
+ if "content" in raw_response:
251
+ return {
252
+ "isError": False,
253
+ "content": self._extract_content(raw_response["content"])
254
+ }
255
+
256
+ # Fallback: return whatever the server sent
257
+ return {
258
+ "isError": False,
259
+ "content": raw_response
260
+ }
261
+
262
+ def _extract_content(self, content_list: Any) -> Any:
263
+ """Extract content from MCP content list format."""
264
+ if not isinstance(content_list, list) or not content_list:
265
+ return content_list
266
+
267
+ # Handle single content item (most common)
268
+ if len(content_list) == 1:
269
+ content_item = content_list[0]
270
+ if isinstance(content_item, dict):
271
+ if content_item.get("type") == "text":
272
+ text_content = content_item.get("text", "")
273
+ # Try to parse JSON, fall back to plain text
274
+ try:
275
+ return json.loads(text_content)
276
+ except json.JSONDecodeError:
277
+ return text_content
278
+ else:
279
+ # Non-text content (image, audio, etc.)
280
+ return content_item
281
+
282
+ # Multiple content items - return the list
283
+ return content_list
284
+
285
+ # --------------------------------------------------------------------- #
286
+ # Resources Operations (if available) #
287
+ # --------------------------------------------------------------------- #
288
+ async def list_resources(self) -> Dict[str, Any]:
289
+ """Get list of available resources."""
290
+ if not HAS_RESOURCES:
291
+ logger.warning("Resources not supported in current chuk-mcp version")
292
+ return {}
293
+
294
+ if not self.read_stream or not self.write_stream:
295
+ logger.error("Cannot list resources: streams not available")
106
296
  return {}
297
+
107
298
  try:
108
- return await send_resources_list(self.read_stream, self.write_stream)
109
- except Exception as exc: # pragma: no cover
110
- import logging
299
+ response = await send_resources_list(self.read_stream, self.write_stream)
300
+ return response if isinstance(response, dict) else {}
301
+ except Exception as e:
302
+ logger.error(f"Error listing resources: {e}")
303
+ return {}
111
304
 
112
- logging.error(f"Error listing resources: {exc}")
305
+ async def read_resource(self, uri: str) -> Dict[str, Any]:
306
+ """Read a specific resource by URI."""
307
+ if not HAS_RESOURCES:
308
+ logger.warning("Resources not supported in current chuk-mcp version")
309
+ return {}
310
+
311
+ if not self.read_stream or not self.write_stream:
312
+ logger.error("Cannot read resource: streams not available")
313
+ return {}
314
+
315
+ try:
316
+ response = await send_resources_read(self.read_stream, self.write_stream, uri)
317
+ return response if isinstance(response, dict) else {}
318
+ except Exception as e:
319
+ logger.error(f"Error reading resource {uri}: {e}")
113
320
  return {}
114
321
 
322
+ # --------------------------------------------------------------------- #
323
+ # Prompts Operations (if available) #
324
+ # --------------------------------------------------------------------- #
115
325
  async def list_prompts(self) -> Dict[str, Any]:
116
- """
117
- Return the result of *prompts/list*. If the connection is not yet
118
- initialised an empty dict is returned.
119
- """
326
+ """Get list of available prompts."""
327
+ if not HAS_PROMPTS:
328
+ logger.warning("Prompts not supported in current chuk-mcp version")
329
+ return {}
330
+
120
331
  if not self.read_stream or not self.write_stream:
332
+ logger.error("Cannot list prompts: streams not available")
121
333
  return {}
334
+
122
335
  try:
123
- return await send_prompts_list(self.read_stream, self.write_stream)
124
- except Exception as exc: # pragma: no cover
125
- import logging
336
+ response = await send_prompts_list(self.read_stream, self.write_stream)
337
+ return response if isinstance(response, dict) else {}
338
+ except Exception as e:
339
+ logger.error(f"Error listing prompts: {e}")
340
+ return {}
126
341
 
127
- logging.error(f"Error listing prompts: {exc}")
342
+ async def get_prompt(self, name: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
343
+ """Get a specific prompt by name."""
344
+ if not HAS_PROMPTS:
345
+ logger.warning("Prompts not supported in current chuk-mcp version")
346
+ return {}
347
+
348
+ if not self.read_stream or not self.write_stream:
349
+ logger.error("Cannot get prompt: streams not available")
350
+ return {}
351
+
352
+ try:
353
+ response = await send_prompts_get(
354
+ self.read_stream,
355
+ self.write_stream,
356
+ name,
357
+ arguments or {}
358
+ )
359
+ return response if isinstance(response, dict) else {}
360
+ except Exception as e:
361
+ logger.error(f"Error getting prompt {name}: {e}")
128
362
  return {}
129
363
 
130
- # OPTIONAL helper ------------------------------------------------------ #
131
- def get_streams(self):
132
- """
133
- Expose the low-level streams so legacy callers can access them
134
- directly. The base-class' default returns an empty list; here we
135
- return a single-element list when the transport is active.
136
- """
364
+ # --------------------------------------------------------------------- #
365
+ # Utility Methods #
366
+ # --------------------------------------------------------------------- #
367
+ def get_streams(self) -> List[tuple]:
368
+ """Get the underlying streams for advanced usage."""
137
369
  if self.read_stream and self.write_stream:
138
370
  return [(self.read_stream, self.write_stream)]
139
371
  return []
140
372
 
141
- # --------------------------------------------------------------------- #
142
- # Main entry-point #
143
- # --------------------------------------------------------------------- #
144
- async def call_tool(
145
- self, tool_name: str, arguments: Dict[str, Any]
146
- ) -> Dict[str, Any]:
147
- """
148
- Execute *tool_name* with *arguments* and normalise the server's reply.
373
+ def is_connected(self) -> bool:
374
+ """Check if transport is connected and ready."""
375
+ return self.read_stream is not None and self.write_stream is not None
149
376
 
150
- The echo-server often returns:
151
- {
152
- "content": [{"type":"text","text":"{\"message\":\"…\"}"}],
153
- "isError": false
154
- }
155
- We unwrap that so callers just receive either a dict or a plain string.
156
- """
157
- if not self.read_stream or not self.write_stream:
158
- return {"isError": True, "error": "Transport not initialized"}
377
+ async def __aenter__(self):
378
+ """Async context manager entry."""
379
+ success = await self.initialize()
380
+ if not success:
381
+ raise RuntimeError("Failed to initialize STDIO transport")
382
+ return self
159
383
 
160
- try:
161
- raw = await send_tools_call(
162
- self.read_stream, self.write_stream, tool_name, arguments
163
- )
164
-
165
- # Handle explicit error wrapper
166
- if "error" in raw:
167
- return {
168
- "isError": True,
169
- "error": raw["error"].get("message", "Unknown error"),
170
- }
384
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
385
+ """Async context manager exit."""
386
+ await self.close()
171
387
 
172
- # Preferred: servers that put the answer under "result"
173
- if "result" in raw:
174
- return {"isError": False, "content": raw["result"]}
175
-
176
- # Common echo-server shape: top-level "content" list
177
- if "content" in raw:
178
- clist = raw["content"]
179
- if isinstance(clist, list) and clist:
180
- first = clist[0]
181
- if isinstance(first, dict) and first.get("type") == "text":
182
- text = first.get("text", "")
183
- # Try to parse as JSON; fall back to plain string
184
- try:
185
- parsed = json.loads(text)
186
- return {"isError": False, "content": parsed}
187
- except json.JSONDecodeError:
188
- return {"isError": False, "content": text}
189
-
190
- # Fallback: give caller whatever the server sent
191
- return {"isError": False, "content": raw}
192
-
193
- except Exception as e: # pragma: no cover
194
- import logging
195
-
196
- logging.error(f"Error calling tool {tool_name}: {e}")
197
- return {"isError": True, "error": str(e)}
388
+ def __repr__(self) -> str:
389
+ """String representation for debugging."""
390
+ status = "connected" if self.is_connected() else "disconnected"
391
+ cmd_info = f"command={getattr(self.server_params, 'command', 'unknown')}"
392
+ return f"StdioTransport(status={status}, {cmd_info})"