code-puppy 0.0.130__py3-none-any.whl → 0.0.132__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.
@@ -0,0 +1,404 @@
1
+ """
2
+ MCP Server with blocking startup capability and stderr capture.
3
+
4
+ This module provides MCP servers that:
5
+ 1. Capture stderr output from stdio servers
6
+ 2. Block until fully initialized before allowing operations
7
+ 3. Emit stderr to users via emit_info with message groups
8
+ """
9
+
10
+ import asyncio
11
+ import os
12
+ import tempfile
13
+ import threading
14
+ import uuid
15
+ from typing import Optional, Callable, List
16
+ from contextlib import asynccontextmanager
17
+ from pydantic_ai.mcp import MCPServerStdio
18
+ from mcp.client.stdio import StdioServerParameters, stdio_client
19
+ from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
20
+ from mcp.shared.session import SessionMessage
21
+ from code_puppy.messaging import emit_info
22
+
23
+
24
+ class StderrFileCapture:
25
+ """Captures stderr to a file and monitors it in a background thread."""
26
+
27
+ def __init__(self, server_name: str, emit_to_user: bool = True, message_group: Optional[uuid.UUID] = None):
28
+ self.server_name = server_name
29
+ self.emit_to_user = emit_to_user
30
+ self.message_group = message_group or uuid.uuid4()
31
+ self.temp_file = None
32
+ self.temp_path = None
33
+ self.monitor_thread = None
34
+ self.stop_monitoring = threading.Event()
35
+ self.captured_lines = []
36
+
37
+ def start(self):
38
+ """Start capture by creating temp file and monitor thread."""
39
+ # Create temp file
40
+ self.temp_file = tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.err')
41
+ self.temp_path = self.temp_file.name
42
+
43
+ # Start monitoring thread
44
+ self.stop_monitoring.clear()
45
+ self.monitor_thread = threading.Thread(target=self._monitor_file)
46
+ self.monitor_thread.daemon = True
47
+ self.monitor_thread.start()
48
+
49
+ return self.temp_file
50
+
51
+ def _monitor_file(self):
52
+ """Monitor the temp file for new content."""
53
+ if not self.temp_path:
54
+ return
55
+
56
+ last_pos = 0
57
+ while not self.stop_monitoring.is_set():
58
+ try:
59
+ with open(self.temp_path, 'r') as f:
60
+ f.seek(last_pos)
61
+ new_content = f.read()
62
+ if new_content:
63
+ last_pos = f.tell()
64
+ # Process new lines
65
+ for line in new_content.splitlines():
66
+ if line.strip():
67
+ self.captured_lines.append(line)
68
+ if self.emit_to_user:
69
+ emit_info(
70
+ f"[bold white on blue] MCP {self.server_name} [/bold white on blue] {line}",
71
+ style="dim cyan",
72
+ message_group=self.message_group
73
+ )
74
+
75
+ except Exception:
76
+ pass # File might not exist yet or be deleted
77
+
78
+ self.stop_monitoring.wait(0.1) # Check every 100ms
79
+
80
+ def stop(self):
81
+ """Stop monitoring and clean up."""
82
+ self.stop_monitoring.set()
83
+ if self.monitor_thread:
84
+ self.monitor_thread.join(timeout=1)
85
+
86
+ if self.temp_file:
87
+ try:
88
+ self.temp_file.close()
89
+ except:
90
+ pass
91
+
92
+ if self.temp_path and os.path.exists(self.temp_path):
93
+ try:
94
+ # Read any remaining content
95
+ with open(self.temp_path, 'r') as f:
96
+ content = f.read()
97
+ for line in content.splitlines():
98
+ if line.strip() and line not in self.captured_lines:
99
+ self.captured_lines.append(line)
100
+ if self.emit_to_user:
101
+ emit_info(
102
+ f"[bold white on blue] MCP {self.server_name} [/bold white on blue] {line}",
103
+ style="dim cyan",
104
+ message_group=self.message_group
105
+ )
106
+
107
+ os.unlink(self.temp_path)
108
+ except:
109
+ pass
110
+
111
+ def get_captured_lines(self) -> List[str]:
112
+ """Get all captured lines."""
113
+ return self.captured_lines.copy()
114
+
115
+
116
+ class SimpleCapturedMCPServerStdio(MCPServerStdio):
117
+ """
118
+ MCPServerStdio that captures stderr to a file and optionally emits to user.
119
+ """
120
+
121
+ def __init__(
122
+ self,
123
+ command: str,
124
+ args=(),
125
+ env=None,
126
+ cwd=None,
127
+ emit_stderr: bool = True,
128
+ message_group: Optional[uuid.UUID] = None,
129
+ **kwargs
130
+ ):
131
+ super().__init__(command=command, args=args, env=env, cwd=cwd, **kwargs)
132
+ self.emit_stderr = emit_stderr
133
+ self.message_group = message_group or uuid.uuid4()
134
+ self._stderr_capture = None
135
+
136
+ @asynccontextmanager
137
+ async def client_streams(self):
138
+ """Create streams with stderr capture."""
139
+ server = StdioServerParameters(
140
+ command=self.command,
141
+ args=list(self.args),
142
+ env=self.env,
143
+ cwd=self.cwd
144
+ )
145
+
146
+ # Create stderr capture
147
+ server_name = getattr(self, 'tool_prefix', self.command)
148
+ self._stderr_capture = StderrFileCapture(server_name, self.emit_stderr, self.message_group)
149
+ stderr_file = self._stderr_capture.start()
150
+
151
+ try:
152
+ async with stdio_client(server=server, errlog=stderr_file) as (read_stream, write_stream):
153
+ yield read_stream, write_stream
154
+ finally:
155
+ self._stderr_capture.stop()
156
+
157
+ def get_captured_stderr(self) -> List[str]:
158
+ """Get captured stderr lines."""
159
+ if self._stderr_capture:
160
+ return self._stderr_capture.get_captured_lines()
161
+ return []
162
+
163
+
164
+ class BlockingMCPServerStdio(SimpleCapturedMCPServerStdio):
165
+ """
166
+ MCP Server that blocks until fully initialized.
167
+
168
+ This server ensures that initialization is complete before
169
+ allowing any operations, preventing race conditions.
170
+ """
171
+
172
+ def __init__(self, *args, **kwargs):
173
+ super().__init__(*args, **kwargs)
174
+ self._initialized = asyncio.Event()
175
+ self._init_error: Optional[Exception] = None
176
+ self._initialization_task = None
177
+
178
+ async def __aenter__(self):
179
+ """Enter context and track initialization."""
180
+ try:
181
+ # Start initialization
182
+ result = await super().__aenter__()
183
+
184
+ # Mark as initialized
185
+ self._initialized.set()
186
+
187
+ # Emit success message
188
+ server_name = getattr(self, 'tool_prefix', self.command)
189
+ emit_info(
190
+ f"✅ MCP Server '{server_name}' initialized successfully",
191
+ style="green",
192
+ message_group=self.message_group
193
+ )
194
+
195
+ return result
196
+
197
+ except Exception as e:
198
+ # Store error and mark as initialized (with error)
199
+ self._init_error = e
200
+ self._initialized.set()
201
+
202
+ # Emit error message
203
+ server_name = getattr(self, 'tool_prefix', self.command)
204
+ emit_info(
205
+ f"❌ MCP Server '{server_name}' failed to initialize: {e}",
206
+ style="red",
207
+ message_group=self.message_group
208
+ )
209
+
210
+ raise
211
+
212
+ async def wait_until_ready(self, timeout: float = 30.0) -> bool:
213
+ """
214
+ Wait until the server is ready.
215
+
216
+ Args:
217
+ timeout: Maximum time to wait in seconds
218
+
219
+ Returns:
220
+ True if server is ready, False if timeout or error
221
+
222
+ Raises:
223
+ TimeoutError: If server doesn't initialize within timeout
224
+ Exception: If server initialization failed
225
+ """
226
+ try:
227
+ await asyncio.wait_for(self._initialized.wait(), timeout=timeout)
228
+
229
+ # Check if there was an initialization error
230
+ if self._init_error:
231
+ raise self._init_error
232
+
233
+ return True
234
+
235
+ except asyncio.TimeoutError:
236
+ server_name = getattr(self, 'tool_prefix', self.command)
237
+ raise TimeoutError(f"Server '{server_name}' initialization timeout after {timeout}s")
238
+
239
+ async def ensure_ready(self, timeout: float = 30.0):
240
+ """
241
+ Ensure server is ready before proceeding.
242
+
243
+ This is a convenience method that raises if not ready.
244
+
245
+ Args:
246
+ timeout: Maximum time to wait in seconds
247
+
248
+ Raises:
249
+ TimeoutError: If server doesn't initialize within timeout
250
+ Exception: If server initialization failed
251
+ """
252
+ await self.wait_until_ready(timeout)
253
+
254
+ def is_ready(self) -> bool:
255
+ """
256
+ Check if server is ready without blocking.
257
+
258
+ Returns:
259
+ True if server is initialized and ready
260
+ """
261
+ return self._initialized.is_set() and self._init_error is None
262
+
263
+
264
+ class StartupMonitor:
265
+ """
266
+ Monitor for tracking multiple server startups.
267
+
268
+ This class helps coordinate startup of multiple MCP servers
269
+ and ensures all are ready before proceeding.
270
+ """
271
+
272
+ def __init__(self, message_group: Optional[uuid.UUID] = None):
273
+ self.servers = {}
274
+ self.startup_times = {}
275
+ self.message_group = message_group or uuid.uuid4()
276
+
277
+ def add_server(self, name: str, server: BlockingMCPServerStdio):
278
+ """Add a server to monitor."""
279
+ self.servers[name] = server
280
+
281
+ async def wait_all_ready(self, timeout: float = 30.0) -> dict:
282
+ """
283
+ Wait for all servers to be ready.
284
+
285
+ Args:
286
+ timeout: Maximum time to wait for all servers
287
+
288
+ Returns:
289
+ Dictionary of server names to ready status
290
+ """
291
+ import time
292
+ results = {}
293
+
294
+ # Create tasks for all servers
295
+ async def wait_server(name: str, server: BlockingMCPServerStdio):
296
+ start = time.time()
297
+ try:
298
+ await server.wait_until_ready(timeout)
299
+ self.startup_times[name] = time.time() - start
300
+ results[name] = True
301
+ emit_info(
302
+ f" {name}: Ready in {self.startup_times[name]:.2f}s",
303
+ style="dim green",
304
+ message_group=self.message_group
305
+ )
306
+ except Exception as e:
307
+ self.startup_times[name] = time.time() - start
308
+ results[name] = False
309
+ emit_info(
310
+ f" {name}: Failed after {self.startup_times[name]:.2f}s - {e}",
311
+ style="dim red",
312
+ message_group=self.message_group
313
+ )
314
+
315
+ # Wait for all servers in parallel
316
+ emit_info(
317
+ f"⏳ Waiting for {len(self.servers)} MCP servers to initialize...",
318
+ style="cyan",
319
+ message_group=self.message_group
320
+ )
321
+
322
+ tasks = [
323
+ asyncio.create_task(wait_server(name, server))
324
+ for name, server in self.servers.items()
325
+ ]
326
+
327
+ await asyncio.gather(*tasks, return_exceptions=True)
328
+
329
+ # Report summary
330
+ ready_count = sum(1 for r in results.values() if r)
331
+ total_count = len(results)
332
+
333
+ if ready_count == total_count:
334
+ emit_info(
335
+ f"✅ All {total_count} servers ready!",
336
+ style="green bold",
337
+ message_group=self.message_group
338
+ )
339
+ else:
340
+ emit_info(
341
+ f"⚠️ {ready_count}/{total_count} servers ready",
342
+ style="yellow",
343
+ message_group=self.message_group
344
+ )
345
+
346
+ return results
347
+
348
+ def get_startup_report(self) -> str:
349
+ """Get a report of startup times."""
350
+ lines = ["Server Startup Times:"]
351
+ for name, time_taken in self.startup_times.items():
352
+ status = "✅" if self.servers[name].is_ready() else "❌"
353
+ lines.append(f" {status} {name}: {time_taken:.2f}s")
354
+ return "\n".join(lines)
355
+
356
+
357
+ async def start_servers_with_blocking(*servers: BlockingMCPServerStdio, timeout: float = 30.0, message_group: Optional[uuid.UUID] = None):
358
+ """
359
+ Start multiple servers and wait for all to be ready.
360
+
361
+ Args:
362
+ *servers: Variable number of BlockingMCPServerStdio instances
363
+ timeout: Maximum time to wait for all servers
364
+ message_group: Optional UUID for grouping log messages
365
+
366
+ Returns:
367
+ List of ready servers
368
+
369
+ Example:
370
+ server1 = BlockingMCPServerStdio(...)
371
+ server2 = BlockingMCPServerStdio(...)
372
+ ready = await start_servers_with_blocking(server1, server2)
373
+ """
374
+ monitor = StartupMonitor(message_group=message_group)
375
+
376
+ for i, server in enumerate(servers):
377
+ name = getattr(server, 'tool_prefix', f"server-{i}")
378
+ monitor.add_server(name, server)
379
+
380
+ # Start all servers
381
+ async def start_server(server):
382
+ async with server:
383
+ await asyncio.sleep(0.1) # Keep context alive briefly
384
+ return server
385
+
386
+ # Start servers in parallel
387
+ server_tasks = [
388
+ asyncio.create_task(start_server(server))
389
+ for server in servers
390
+ ]
391
+
392
+ # Wait for all to be ready
393
+ results = await monitor.wait_all_ready(timeout)
394
+
395
+ # Get the report
396
+ emit_info(monitor.get_startup_report(), message_group=monitor.message_group)
397
+
398
+ # Return ready servers
399
+ ready_servers = [
400
+ server for name, server in monitor.servers.items()
401
+ if results.get(name, False)
402
+ ]
403
+
404
+ return ready_servers
@@ -0,0 +1,282 @@
1
+ """
2
+ Custom MCPServerStdio that captures stderr output properly.
3
+
4
+ This module provides a version of MCPServerStdio that captures subprocess
5
+ stderr output and makes it available through proper logging channels.
6
+ """
7
+
8
+ import asyncio
9
+ import io
10
+ import logging
11
+ import os
12
+ import sys
13
+ import tempfile
14
+ from contextlib import asynccontextmanager
15
+ from typing import AsyncIterator, Sequence, Optional, Any
16
+ from threading import Thread
17
+ from queue import Queue, Empty
18
+
19
+ from pydantic_ai.mcp import MCPServerStdio
20
+ from mcp.client.stdio import StdioServerParameters, stdio_client
21
+ from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
22
+ from mcp.shared.session import SessionMessage
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class StderrCapture:
28
+ """
29
+ Captures stderr output using a pipe and background reader.
30
+ """
31
+
32
+ def __init__(self, name: str, handler: Optional[callable] = None):
33
+ """
34
+ Initialize stderr capture.
35
+
36
+ Args:
37
+ name: Name for this capture stream
38
+ handler: Optional function to call with captured lines
39
+ """
40
+ self.name = name
41
+ self.handler = handler or self._default_handler
42
+ self._captured_lines = []
43
+ self._reader_task = None
44
+ self._pipe_r = None
45
+ self._pipe_w = None
46
+
47
+ def _default_handler(self, line: str):
48
+ """Default handler that logs to Python logging."""
49
+ if line.strip():
50
+ logger.debug(f"[MCP {self.name}] {line.rstrip()}")
51
+
52
+ async def start_capture(self):
53
+ """Start capturing stderr by creating a pipe and reader task."""
54
+ # Create a pipe for capturing stderr
55
+ self._pipe_r, self._pipe_w = os.pipe()
56
+
57
+ # Make the read end non-blocking
58
+ os.set_blocking(self._pipe_r, False)
59
+
60
+ # Start background task to read from pipe
61
+ self._reader_task = asyncio.create_task(self._read_pipe())
62
+
63
+ # Return the write end as the file descriptor for stderr
64
+ return self._pipe_w
65
+
66
+ async def _read_pipe(self):
67
+ """Background task to read from the pipe."""
68
+ loop = asyncio.get_event_loop()
69
+ buffer = b''
70
+
71
+ try:
72
+ while True:
73
+ # Use asyncio's add_reader for efficient async reading
74
+ future = asyncio.Future()
75
+
76
+ def read_callback():
77
+ try:
78
+ data = os.read(self._pipe_r, 4096)
79
+ future.set_result(data)
80
+ except BlockingIOError:
81
+ future.set_result(b'')
82
+ except Exception as e:
83
+ future.set_exception(e)
84
+
85
+ loop.add_reader(self._pipe_r, read_callback)
86
+ try:
87
+ data = await future
88
+ finally:
89
+ loop.remove_reader(self._pipe_r)
90
+
91
+ if not data:
92
+ await asyncio.sleep(0.1)
93
+ continue
94
+
95
+ # Process the data
96
+ buffer += data
97
+
98
+ # Look for complete lines
99
+ while b'\n' in buffer:
100
+ line, buffer = buffer.split(b'\n', 1)
101
+ line_str = line.decode('utf-8', errors='replace')
102
+ if line_str:
103
+ self._captured_lines.append(line_str)
104
+ self.handler(line_str)
105
+
106
+ except asyncio.CancelledError:
107
+ # Process any remaining buffer
108
+ if buffer:
109
+ line_str = buffer.decode('utf-8', errors='replace')
110
+ if line_str:
111
+ self._captured_lines.append(line_str)
112
+ self.handler(line_str)
113
+ raise
114
+
115
+ async def stop_capture(self):
116
+ """Stop capturing and clean up."""
117
+ if self._reader_task:
118
+ self._reader_task.cancel()
119
+ try:
120
+ await self._reader_task
121
+ except asyncio.CancelledError:
122
+ pass
123
+
124
+ if self._pipe_r is not None:
125
+ os.close(self._pipe_r)
126
+ if self._pipe_w is not None:
127
+ os.close(self._pipe_w)
128
+
129
+ def get_captured_lines(self) -> list[str]:
130
+ """Get all captured lines."""
131
+ return self._captured_lines.copy()
132
+
133
+
134
+ class CapturedMCPServerStdio(MCPServerStdio):
135
+ """
136
+ Extended MCPServerStdio that captures and handles stderr output.
137
+
138
+ This class captures stderr from the subprocess and makes it available
139
+ through proper logging channels instead of letting it pollute the console.
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ command: str,
145
+ args: Sequence[str] = (),
146
+ env: dict[str, str] | None = None,
147
+ cwd: str | None = None,
148
+ stderr_handler: Optional[callable] = None,
149
+ **kwargs
150
+ ):
151
+ """
152
+ Initialize captured stdio server.
153
+
154
+ Args:
155
+ command: The command to run
156
+ args: Arguments for the command
157
+ env: Environment variables
158
+ cwd: Working directory
159
+ stderr_handler: Optional function to handle stderr lines
160
+ **kwargs: Additional arguments for MCPServerStdio
161
+ """
162
+ super().__init__(command=command, args=args, env=env, cwd=cwd, **kwargs)
163
+ self.stderr_handler = stderr_handler
164
+ self._stderr_capture = None
165
+ self._captured_lines = []
166
+
167
+ @asynccontextmanager
168
+ async def client_streams(
169
+ self,
170
+ ) -> AsyncIterator[
171
+ tuple[
172
+ MemoryObjectReceiveStream[SessionMessage | Exception],
173
+ MemoryObjectSendStream[SessionMessage],
174
+ ]
175
+ ]:
176
+ """Create the streams for the MCP server with stderr capture."""
177
+ server = StdioServerParameters(
178
+ command=self.command,
179
+ args=list(self.args),
180
+ env=self.env,
181
+ cwd=self.cwd
182
+ )
183
+
184
+ # Create stderr capture
185
+ def stderr_line_handler(line: str):
186
+ """Handle captured stderr lines."""
187
+ self._captured_lines.append(line)
188
+
189
+ if self.stderr_handler:
190
+ self.stderr_handler(line)
191
+ else:
192
+ # Default: log at DEBUG level to avoid console spam
193
+ logger.debug(f"[MCP Server {self.command}] {line}")
194
+
195
+ self._stderr_capture = StderrCapture(self.command, stderr_line_handler)
196
+
197
+ # For now, use devnull for stderr to suppress output
198
+ # We'll capture it through other means if needed
199
+ with open(os.devnull, 'w') as devnull:
200
+ async with stdio_client(server=server, errlog=devnull) as (read_stream, write_stream):
201
+ yield read_stream, write_stream
202
+
203
+ def get_captured_stderr(self) -> list[str]:
204
+ """
205
+ Get all captured stderr lines.
206
+
207
+ Returns:
208
+ List of captured stderr lines
209
+ """
210
+ return self._captured_lines.copy()
211
+
212
+ def clear_captured_stderr(self):
213
+ """Clear the captured stderr buffer."""
214
+ self._captured_lines.clear()
215
+
216
+
217
+ class StderrCollector:
218
+ """
219
+ A centralized collector for stderr from multiple MCP servers.
220
+
221
+ This can be used to aggregate stderr from all MCP servers in one place.
222
+ """
223
+
224
+ def __init__(self):
225
+ """Initialize the collector."""
226
+ self.servers = {}
227
+ self.all_lines = []
228
+
229
+ def create_handler(self, server_name: str, emit_to_user: bool = False):
230
+ """
231
+ Create a handler function for a specific server.
232
+
233
+ Args:
234
+ server_name: Name to identify this server
235
+ emit_to_user: If True, emit stderr lines to user via emit_info
236
+
237
+ Returns:
238
+ Handler function that can be passed to CapturedMCPServerStdio
239
+ """
240
+ def handler(line: str):
241
+ # Store with server identification
242
+ import time
243
+ entry = {
244
+ 'server': server_name,
245
+ 'line': line,
246
+ 'timestamp': time.time()
247
+ }
248
+
249
+ if server_name not in self.servers:
250
+ self.servers[server_name] = []
251
+
252
+ self.servers[server_name].append(line)
253
+ self.all_lines.append(entry)
254
+
255
+ # Emit to user if requested
256
+ if emit_to_user:
257
+ from code_puppy.messaging import emit_info
258
+ emit_info(f"[MCP {server_name}] {line}", style="dim cyan")
259
+
260
+ return handler
261
+
262
+ def get_server_output(self, server_name: str) -> list[str]:
263
+ """Get all output from a specific server."""
264
+ return self.servers.get(server_name, []).copy()
265
+
266
+ def get_all_output(self) -> list[dict]:
267
+ """Get all output from all servers with metadata."""
268
+ return self.all_lines.copy()
269
+
270
+ def clear(self, server_name: Optional[str] = None):
271
+ """Clear captured output."""
272
+ if server_name:
273
+ if server_name in self.servers:
274
+ self.servers[server_name].clear()
275
+ # Also clear from all_lines
276
+ self.all_lines = [
277
+ entry for entry in self.all_lines
278
+ if entry['server'] != server_name
279
+ ]
280
+ else:
281
+ self.servers.clear()
282
+ self.all_lines.clear()