omnispindle 1.0.0__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.
- Omnispindle/__init__.py +187 -0
- Omnispindle/__main__.py +121 -0
- Omnispindle/ai_assistant.py +422 -0
- Omnispindle/api_client.py +275 -0
- Omnispindle/api_tools.py +395 -0
- Omnispindle/auth.py +117 -0
- Omnispindle/auth0_actions/custom_token_exchange.js +78 -0
- Omnispindle/auth_flow.py +173 -0
- Omnispindle/auth_setup.py +240 -0
- Omnispindle/auth_utils.py +80 -0
- Omnispindle/chat-to-create-todos-from-work.txt +2018 -0
- Omnispindle/context.py +16 -0
- Omnispindle/database.py +164 -0
- Omnispindle/http_server.py +99 -0
- Omnispindle/hybrid_tools.py +407 -0
- Omnispindle/mcp_handler.py +60 -0
- Omnispindle/middleware.py +194 -0
- Omnispindle/models/__init__.py +1 -0
- Omnispindle/models/config.py +11 -0
- Omnispindle/mqtt.py +80 -0
- Omnispindle/patches.py +233 -0
- Omnispindle/requirements.txt +371 -0
- Omnispindle/scheduler.py +756 -0
- Omnispindle/server.py +282 -0
- Omnispindle/sse_handler.py +169 -0
- Omnispindle/stdio_http_server.py +73 -0
- Omnispindle/stdio_server.py +528 -0
- Omnispindle/todo_log_service.py +423 -0
- Omnispindle/token_exchange.py +174 -0
- Omnispindle/tools.py +1166 -0
- Omnispindle/utils.py +258 -0
- Omnispindle/verify_token.py +43 -0
- omnispindle-1.0.0.dist-info/METADATA +291 -0
- omnispindle-1.0.0.dist-info/RECORD +36 -0
- omnispindle-1.0.0.dist-info/WHEEL +4 -0
- omnispindle-1.0.0.dist-info/entry_points.txt +4 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from typing import AsyncGenerator, Coroutine, Any, Callable
|
|
6
|
+
|
|
7
|
+
from starlette.requests import Request
|
|
8
|
+
from starlette.responses import StreamingResponse
|
|
9
|
+
|
|
10
|
+
from .tools import ToolCall, handle_tool_call
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def mcp_handler(request: Request, get_current_user: Callable[[], Coroutine[Any, Any, Any]]) -> StreamingResponse:
|
|
16
|
+
user = await get_current_user()
|
|
17
|
+
if not user:
|
|
18
|
+
return StreamingResponse(content="Unauthorized", status_code=401)
|
|
19
|
+
|
|
20
|
+
async def event_generator() -> AsyncGenerator[str, None]:
|
|
21
|
+
buffer = ""
|
|
22
|
+
while True:
|
|
23
|
+
try:
|
|
24
|
+
# Read data from the request body stream
|
|
25
|
+
chunk = await request.stream().read()
|
|
26
|
+
if not chunk:
|
|
27
|
+
await asyncio.sleep(0.1)
|
|
28
|
+
continue
|
|
29
|
+
|
|
30
|
+
buffer += chunk.decode('utf-8')
|
|
31
|
+
logger.debug(f"Received chunk: {chunk.decode('utf-8')}")
|
|
32
|
+
logger.debug(f"Buffer content: {buffer}")
|
|
33
|
+
|
|
34
|
+
# Process buffer for complete JSON objects
|
|
35
|
+
while '\n' in buffer:
|
|
36
|
+
line, buffer = buffer.split('\n', 1)
|
|
37
|
+
if line:
|
|
38
|
+
logger.debug(f"Processing line: {line}")
|
|
39
|
+
try:
|
|
40
|
+
data = json.loads(line)
|
|
41
|
+
tool_call = ToolCall.parse_obj(data)
|
|
42
|
+
response = await handle_tool_call(tool_call)
|
|
43
|
+
response_json = json.dumps(response.dict())
|
|
44
|
+
logger.debug(f"Sending response: {response_json}")
|
|
45
|
+
yield f"{response_json}\n"
|
|
46
|
+
except json.JSONDecodeError as e:
|
|
47
|
+
logger.error(f"JSON decode error: {e} for line: {line}")
|
|
48
|
+
except Exception as e:
|
|
49
|
+
logger.error(f"Error processing tool call: {e}")
|
|
50
|
+
error_response = {"status": "error", "message": str(e)}
|
|
51
|
+
yield f"{json.dumps(error_response)}\n"
|
|
52
|
+
|
|
53
|
+
except asyncio.CancelledError:
|
|
54
|
+
logger.info("Client disconnected.")
|
|
55
|
+
break
|
|
56
|
+
except Exception as e:
|
|
57
|
+
logger.error(f"An unexpected error occurred: {e}")
|
|
58
|
+
break
|
|
59
|
+
|
|
60
|
+
return StreamingResponse(event_generator(), media_type="application/json")
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
2
|
+
from starlette.responses import Response, JSONResponse
|
|
3
|
+
from starlette.types import ASGIApp
|
|
4
|
+
import logging
|
|
5
|
+
import asyncio
|
|
6
|
+
import anyio
|
|
7
|
+
import inspect
|
|
8
|
+
import functools
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class EnhancedLoggingMiddleware(BaseHTTPMiddleware):
|
|
15
|
+
"""
|
|
16
|
+
Middleware to log requests and responses, providing more context than default logging.
|
|
17
|
+
"""
|
|
18
|
+
def __init__(self, app: ASGIApp, logger: logging.Logger):
|
|
19
|
+
super().__init__(app)
|
|
20
|
+
self.logger = logger
|
|
21
|
+
|
|
22
|
+
async def dispatch(self, request, call_next):
|
|
23
|
+
start_time = time.time()
|
|
24
|
+
|
|
25
|
+
# Log request details
|
|
26
|
+
self.logger.info(f"Request: {request.method} {request.url.path}")
|
|
27
|
+
|
|
28
|
+
response = await call_next(request)
|
|
29
|
+
|
|
30
|
+
process_time = (time.time() - start_time) * 1000
|
|
31
|
+
|
|
32
|
+
# Log response details
|
|
33
|
+
self.logger.info(
|
|
34
|
+
f"Response: {response.status_code} "
|
|
35
|
+
f"({request.method} {request.url.path}) "
|
|
36
|
+
f"took {process_time:.2f}ms"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
return response
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# Placeholder for rate limit middleware
|
|
43
|
+
async def rate_limit_middleware(request, call_next):
|
|
44
|
+
"""
|
|
45
|
+
This is a placeholder for a rate limiting middleware.
|
|
46
|
+
It currently does nothing but can be expanded later.
|
|
47
|
+
"""
|
|
48
|
+
# TODO: Implement actual rate limiting logic
|
|
49
|
+
response = await call_next(request)
|
|
50
|
+
return response
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ConnectionErrorsMiddleware(BaseHTTPMiddleware):
|
|
54
|
+
"""
|
|
55
|
+
Middleware to handle various connection-related errors that occur when clients disconnect.
|
|
56
|
+
This handles common exceptions from SSE connections and long-polling requests.
|
|
57
|
+
"""
|
|
58
|
+
async def dispatch(self, request, call_next):
|
|
59
|
+
try:
|
|
60
|
+
return await call_next(request)
|
|
61
|
+
except RuntimeError as exc:
|
|
62
|
+
if str(exc) == 'No response returned.' and await request.is_disconnected():
|
|
63
|
+
logger.debug("Client disconnected with 'No response returned' error")
|
|
64
|
+
return Response(status_code=204)
|
|
65
|
+
raise
|
|
66
|
+
except (anyio.WouldBlock, asyncio.exceptions.CancelledError) as exc:
|
|
67
|
+
# These are common with SSE and WebSocket connections when clients disconnect
|
|
68
|
+
if await request.is_disconnected():
|
|
69
|
+
logger.debug(f"Handled {type(exc).__name__} for disconnected client")
|
|
70
|
+
return Response(status_code=204)
|
|
71
|
+
raise
|
|
72
|
+
except ConnectionResetError as exc:
|
|
73
|
+
logger.debug("Client connection was reset")
|
|
74
|
+
return Response(status_code=204)
|
|
75
|
+
except ConnectionAbortedError as exc:
|
|
76
|
+
logger.debug("Client connection was aborted")
|
|
77
|
+
return Response(status_code=204)
|
|
78
|
+
|
|
79
|
+
# Keep the old middleware for backward compatibility
|
|
80
|
+
SuppressNoResponseReturnedMiddleware = ConnectionErrorsMiddleware
|
|
81
|
+
|
|
82
|
+
class NoneTypeResponseMiddleware(BaseHTTPMiddleware):
|
|
83
|
+
"""
|
|
84
|
+
Middleware to handle 'NoneType' object is not callable errors.
|
|
85
|
+
This occurs when a route handler returns None instead of a proper response object.
|
|
86
|
+
"""
|
|
87
|
+
async def dispatch(self, request, call_next):
|
|
88
|
+
try:
|
|
89
|
+
response = await call_next(request)
|
|
90
|
+
if response is None:
|
|
91
|
+
# Log the path that returned None
|
|
92
|
+
logger.debug(f"Route handler for {request.url.path} returned None instead of a response object")
|
|
93
|
+
# Return a generic 204 No Content response
|
|
94
|
+
return Response(status_code=204)
|
|
95
|
+
return response
|
|
96
|
+
except TypeError as exc:
|
|
97
|
+
if "'NoneType' object is not callable" in str(exc):
|
|
98
|
+
logger.debug(f"Caught NoneType error in {request.url.path}: {str(exc)}")
|
|
99
|
+
return Response(
|
|
100
|
+
status_code=204,
|
|
101
|
+
headers=[(b"content-type", b"text/plain")]
|
|
102
|
+
)
|
|
103
|
+
raise
|
|
104
|
+
|
|
105
|
+
def create_asgi_error_handler(app):
|
|
106
|
+
"""
|
|
107
|
+
Create a low-level ASGI wrapper that handles errors and provides fallbacks.
|
|
108
|
+
|
|
109
|
+
This is a more aggressive approach that wraps the entire ASGI application
|
|
110
|
+
to handle errors at the lowest level of the stack.
|
|
111
|
+
"""
|
|
112
|
+
@functools.wraps(app)
|
|
113
|
+
async def error_handling_app(scope, receive, send):
|
|
114
|
+
# Define a patched send function
|
|
115
|
+
original_send = send
|
|
116
|
+
|
|
117
|
+
async def patched_send(message):
|
|
118
|
+
try:
|
|
119
|
+
await original_send(message)
|
|
120
|
+
except Exception as e:
|
|
121
|
+
logger.debug(f"Error in send: {type(e).__name__}: {str(e)}")
|
|
122
|
+
# Send a fallback response if possible
|
|
123
|
+
if message.get("type") == "http.response.start":
|
|
124
|
+
try:
|
|
125
|
+
await original_send({
|
|
126
|
+
"type": "http.response.start",
|
|
127
|
+
"status": 204,
|
|
128
|
+
"headers": [(b"content-type", b"text/plain")]
|
|
129
|
+
})
|
|
130
|
+
await original_send({
|
|
131
|
+
"type": "http.response.body",
|
|
132
|
+
"body": b"",
|
|
133
|
+
"more_body": False
|
|
134
|
+
})
|
|
135
|
+
except Exception as e2:
|
|
136
|
+
logger.debug(f"Failed to send fallback response: {str(e2)}")
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
# Run the main application
|
|
140
|
+
await app(scope, receive, patched_send)
|
|
141
|
+
except TypeError as e:
|
|
142
|
+
if "'NoneType' object is not callable" in str(e):
|
|
143
|
+
logger.debug(f"Caught NoneType error at ASGI level: {str(e)}")
|
|
144
|
+
try:
|
|
145
|
+
# Send a fallback response
|
|
146
|
+
await send({
|
|
147
|
+
"type": "http.response.start",
|
|
148
|
+
"status": 204,
|
|
149
|
+
"headers": [(b"content-type", b"text/plain")]
|
|
150
|
+
})
|
|
151
|
+
await send({
|
|
152
|
+
"type": "http.response.body",
|
|
153
|
+
"body": b"",
|
|
154
|
+
"more_body": False
|
|
155
|
+
})
|
|
156
|
+
except Exception as e2:
|
|
157
|
+
logger.debug(f"Failed to send fallback response after NoneType error: {str(e2)}")
|
|
158
|
+
else:
|
|
159
|
+
logger.warning(f"Unhandled TypeError: {str(e)}")
|
|
160
|
+
# Try to send a 500 response
|
|
161
|
+
try:
|
|
162
|
+
await send({
|
|
163
|
+
"type": "http.response.start",
|
|
164
|
+
"status": 500,
|
|
165
|
+
"headers": [(b"content-type", b"text/plain")]
|
|
166
|
+
})
|
|
167
|
+
await send({
|
|
168
|
+
"type": "http.response.body",
|
|
169
|
+
"body": b"Internal Server Error",
|
|
170
|
+
"more_body": False
|
|
171
|
+
})
|
|
172
|
+
except Exception:
|
|
173
|
+
pass # We tried our best
|
|
174
|
+
except (asyncio.exceptions.CancelledError, anyio.WouldBlock) as e:
|
|
175
|
+
logger.debug(f"Connection error: {type(e).__name__}")
|
|
176
|
+
# These are common with client disconnections, so we just log and don't try to respond
|
|
177
|
+
except Exception as e:
|
|
178
|
+
logger.warning(f"Unhandled exception in ASGI app: {type(e).__name__}: {str(e)}")
|
|
179
|
+
# Try to send a 500 response
|
|
180
|
+
try:
|
|
181
|
+
await send({
|
|
182
|
+
"type": "http.response.start",
|
|
183
|
+
"status": 500,
|
|
184
|
+
"headers": [(b"content-type", b"text/plain")]
|
|
185
|
+
})
|
|
186
|
+
await send({
|
|
187
|
+
"type": "http.response.body",
|
|
188
|
+
"body": b"Internal Server Error",
|
|
189
|
+
"more_body": False
|
|
190
|
+
})
|
|
191
|
+
except Exception:
|
|
192
|
+
pass # We tried our best
|
|
193
|
+
|
|
194
|
+
return error_handling_app
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Omnispindle models package
|
Omnispindle/mqtt.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import subprocess
|
|
3
|
+
import shutil
|
|
4
|
+
from typing import Optional, Any
|
|
5
|
+
|
|
6
|
+
from fastmcp import Context
|
|
7
|
+
|
|
8
|
+
# MQTT configuration from environment
|
|
9
|
+
MQTT_HOST = os.getenv("MQTT_HOST", "localhost")
|
|
10
|
+
MQTT_PORT = int(os.getenv("MQTT_PORT", 1883))
|
|
11
|
+
MOSQUITTO_PUB_AVAILABLE = shutil.which("mosquitto_pub") is not None
|
|
12
|
+
|
|
13
|
+
async def mqtt_publish(topic: str, message: str, ctx: Optional[Context] = None, retain: bool = False) -> bool:
|
|
14
|
+
"""
|
|
15
|
+
Publish a message to an MQTT topic using mosquitto_pub
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
topic: MQTT topic to publish to
|
|
19
|
+
message: Message content to publish
|
|
20
|
+
ctx: Optional context for logging
|
|
21
|
+
retain: Whether to set the retain flag
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
True if publish successful, False otherwise
|
|
25
|
+
"""
|
|
26
|
+
if not MOSQUITTO_PUB_AVAILABLE:
|
|
27
|
+
print(f"MQTT publishing not available - would publish {message} to {topic} (retain={retain})")
|
|
28
|
+
return False
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
cmd = ["mosquitto_pub", "-h", MQTT_HOST, "-p", str(MQTT_PORT), "-t", topic, "-m", str(message)]
|
|
32
|
+
if retain:
|
|
33
|
+
cmd.append("-r")
|
|
34
|
+
subprocess.run(cmd, check=True, capture_output=True, text=True)
|
|
35
|
+
|
|
36
|
+
# Safe context logging with error handling
|
|
37
|
+
if ctx:
|
|
38
|
+
try:
|
|
39
|
+
await ctx.info(f"MQTT published to {topic}: {message} (retain={retain})")
|
|
40
|
+
except Exception as log_error:
|
|
41
|
+
# Fallback to standard logging if context logging fails
|
|
42
|
+
print(f"MQTT published to {topic}: {message} (retain={retain})")
|
|
43
|
+
print(f"Context logging failed: {log_error}")
|
|
44
|
+
|
|
45
|
+
return True
|
|
46
|
+
except subprocess.CalledProcessError as e:
|
|
47
|
+
error_msg = f"Failed to publish MQTT message: {str(e)}"
|
|
48
|
+
|
|
49
|
+
# Safe context logging with error handling
|
|
50
|
+
if ctx:
|
|
51
|
+
try:
|
|
52
|
+
await ctx.error(error_msg)
|
|
53
|
+
except Exception as log_error:
|
|
54
|
+
# Fallback to standard logging if context logging fails
|
|
55
|
+
print(error_msg)
|
|
56
|
+
print(f"Context logging failed: {log_error}")
|
|
57
|
+
else:
|
|
58
|
+
print(error_msg)
|
|
59
|
+
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def mqtt_get(topic: str) -> Optional[str]:
|
|
64
|
+
"""
|
|
65
|
+
Get the latest message from an MQTT topic
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
topic: MQTT topic to retrieve from
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
The message content or None if retrieval failed
|
|
72
|
+
"""
|
|
73
|
+
try:
|
|
74
|
+
cmd = ["mosquitto_sub", "-h", MQTT_HOST, "-p", str(MQTT_PORT), "-t", topic, "-C", "1"]
|
|
75
|
+
result = subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=3)
|
|
76
|
+
return result.stdout.strip()
|
|
77
|
+
except subprocess.SubprocessError as e:
|
|
78
|
+
error_msg = f"Failed to get MQTT message: {str(e)}"
|
|
79
|
+
print(error_msg)
|
|
80
|
+
return None
|
Omnispindle/patches.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import inspect
|
|
3
|
+
import importlib
|
|
4
|
+
import functools
|
|
5
|
+
import asyncio
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Dict, Any
|
|
8
|
+
from contextlib import asynccontextmanager
|
|
9
|
+
from starlette.responses import Response
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
def apply_patches():
|
|
14
|
+
"""
|
|
15
|
+
Apply monkey patches to external libraries to fix common errors.
|
|
16
|
+
"""
|
|
17
|
+
logger.info("Applying monkey patches to external libraries")
|
|
18
|
+
|
|
19
|
+
# Patch Starlette routing - be more careful about checking first
|
|
20
|
+
try:
|
|
21
|
+
import starlette.routing
|
|
22
|
+
|
|
23
|
+
# Instead of trying to patch Route.app directly (which might not exist in 0.45.3),
|
|
24
|
+
# we'll patch the Router's handle method to catch None responses
|
|
25
|
+
if hasattr(starlette.routing, "Router") and hasattr(starlette.routing.Router, "handle"):
|
|
26
|
+
original_handle = starlette.routing.Router.handle
|
|
27
|
+
|
|
28
|
+
@functools.wraps(original_handle)
|
|
29
|
+
async def patched_handle(self, scope, receive, send):
|
|
30
|
+
try:
|
|
31
|
+
await original_handle(self, scope, receive, send)
|
|
32
|
+
except TypeError as e:
|
|
33
|
+
if "'NoneType' object is not callable" in str(e):
|
|
34
|
+
logger.debug(f"Caught NoneType error in Router.handle: {scope.get('path', 'unknown')}")
|
|
35
|
+
# Send a fallback 204 response
|
|
36
|
+
await send({
|
|
37
|
+
"type": "http.response.start",
|
|
38
|
+
"status": 204,
|
|
39
|
+
"headers": [(b"content-type", b"text/plain")]
|
|
40
|
+
})
|
|
41
|
+
await send({
|
|
42
|
+
"type": "http.response.body",
|
|
43
|
+
"body": b"",
|
|
44
|
+
"more_body": False
|
|
45
|
+
})
|
|
46
|
+
else:
|
|
47
|
+
raise
|
|
48
|
+
|
|
49
|
+
# Apply the patch
|
|
50
|
+
starlette.routing.Router.handle = patched_handle
|
|
51
|
+
logger.info("Patched starlette.routing.Router.handle")
|
|
52
|
+
|
|
53
|
+
# Now we need to patch the _exception_handler.py which is the source of the NoneType errors
|
|
54
|
+
# This is a deeper fix for the most common error
|
|
55
|
+
import starlette._exception_handler
|
|
56
|
+
|
|
57
|
+
# Get the original wrap_app_handling_exceptions function
|
|
58
|
+
original_wrap_app = starlette._exception_handler.wrap_app_handling_exceptions
|
|
59
|
+
|
|
60
|
+
# Create a patched version that catches NoneType errors
|
|
61
|
+
@functools.wraps(original_wrap_app)
|
|
62
|
+
def patched_wrap_app_handling_exceptions(app, conn):
|
|
63
|
+
"""
|
|
64
|
+
This patches the key function in starlette._exception_handler that's causing the NoneType errors.
|
|
65
|
+
It handles the case where an endpoint returns None by returning a 204 response.
|
|
66
|
+
"""
|
|
67
|
+
# First get the wrapped ASGI app from the original function
|
|
68
|
+
wrapped_app = original_wrap_app(app, conn)
|
|
69
|
+
|
|
70
|
+
# Now wrap it with our safe version
|
|
71
|
+
@functools.wraps(wrapped_app)
|
|
72
|
+
async def safe_wrapped_app(scope, receive, send):
|
|
73
|
+
try:
|
|
74
|
+
# Call the original wrapped app
|
|
75
|
+
return await wrapped_app(scope, receive, send)
|
|
76
|
+
except TypeError as e:
|
|
77
|
+
if "'NoneType' object is not callable" in str(e):
|
|
78
|
+
logger.debug(f"Caught NoneType error in _exception_handler: {scope.get('path', 'unknown')}")
|
|
79
|
+
|
|
80
|
+
# Send a fallback 204 No Content response
|
|
81
|
+
await send({
|
|
82
|
+
"type": "http.response.start",
|
|
83
|
+
"status": 204,
|
|
84
|
+
"headers": [(b"content-type", b"text/plain")]
|
|
85
|
+
})
|
|
86
|
+
await send({
|
|
87
|
+
"type": "http.response.body",
|
|
88
|
+
"body": b"",
|
|
89
|
+
"more_body": False
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
# Don't re-raise the exception
|
|
93
|
+
return
|
|
94
|
+
else:
|
|
95
|
+
# Other TypeErrors should be re-raised
|
|
96
|
+
pass
|
|
97
|
+
except Exception as e:
|
|
98
|
+
# For other exceptions, let the original error handling take over
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
# Return our patched app
|
|
102
|
+
return safe_wrapped_app
|
|
103
|
+
|
|
104
|
+
# Replace the original function with our patched version
|
|
105
|
+
starlette._exception_handler.wrap_app_handling_exceptions = patched_wrap_app_handling_exceptions
|
|
106
|
+
logger.info("Patched starlette._exception_handler.wrap_app_handling_exceptions")
|
|
107
|
+
else:
|
|
108
|
+
logger.info("starlette.routing.Router.handle not found - skipping patch")
|
|
109
|
+
except Exception as e:
|
|
110
|
+
logger.error(f"Failed to apply Starlette router patches: {str(e)}")
|
|
111
|
+
|
|
112
|
+
# Patch FastMCP's log method to properly handle async send_log_message calls
|
|
113
|
+
try:
|
|
114
|
+
from fastmcp.server import FastMCP
|
|
115
|
+
|
|
116
|
+
# Store the original log method
|
|
117
|
+
original_log = FastMCP.log
|
|
118
|
+
|
|
119
|
+
@functools.wraps(original_log)
|
|
120
|
+
async def patched_log(self, level: str, message: str, logger_name: str = None, **extra):
|
|
121
|
+
"""
|
|
122
|
+
Patched log method that properly handles the async send_log_message call.
|
|
123
|
+
|
|
124
|
+
This fixes the "RuntimeWarning: coroutine 'ServerSession.send_log_message' was never awaited" warning
|
|
125
|
+
by ensuring the coroutine is properly awaited in an async context.
|
|
126
|
+
"""
|
|
127
|
+
try:
|
|
128
|
+
# Call the original log method which should properly await send_log_message
|
|
129
|
+
return await original_log(self, level, message, logger_name, **extra)
|
|
130
|
+
except Exception as e:
|
|
131
|
+
# If there's an error with MCP logging, fall back to standard logging
|
|
132
|
+
# to avoid breaking the application
|
|
133
|
+
import logging
|
|
134
|
+
logger = logging.getLogger(logger_name or __name__)
|
|
135
|
+
getattr(logger, level.lower(), logger.info)(f"{message}")
|
|
136
|
+
logger.debug(f"FastMCP log fallback used due to error: {str(e)}")
|
|
137
|
+
|
|
138
|
+
# Apply the patch
|
|
139
|
+
FastMCP.log = patched_log
|
|
140
|
+
logger.info("Patched FastMCP.log to fix unawaited send_log_message warnings")
|
|
141
|
+
|
|
142
|
+
except Exception as e:
|
|
143
|
+
logger.error(f"Failed to apply FastMCP log patches: {str(e)}")
|
|
144
|
+
|
|
145
|
+
# Patch MCP's SSE module to properly handle client disconnects
|
|
146
|
+
try:
|
|
147
|
+
import mcp.server.sse
|
|
148
|
+
import sse_starlette
|
|
149
|
+
from sse_starlette.sse import EventSourceResponse
|
|
150
|
+
|
|
151
|
+
# Store original method
|
|
152
|
+
original_connect_sse = mcp.server.sse.SseServerTransport.connect_sse
|
|
153
|
+
|
|
154
|
+
# Patch the connect_sse method to handle disconnects better and ensure it returns a Response
|
|
155
|
+
@asynccontextmanager
|
|
156
|
+
async def patched_connect_sse(self, scope, receive, send):
|
|
157
|
+
# Log the client connecting
|
|
158
|
+
client = scope.get("client", ("unknown", 0))
|
|
159
|
+
logger.debug(f"SSE client connected: {client[0]}:{client[1]}")
|
|
160
|
+
|
|
161
|
+
# Add better error handling
|
|
162
|
+
try:
|
|
163
|
+
async with original_connect_sse(self, scope, receive, send) as result:
|
|
164
|
+
yield result
|
|
165
|
+
except asyncio.CancelledError:
|
|
166
|
+
logger.debug(f"SSE client disconnected (CancelledError): {client[0]}:{client[1]}")
|
|
167
|
+
# Don't re-raise, just end gracefully
|
|
168
|
+
except Exception as e:
|
|
169
|
+
logger.debug(f"SSE client error: {client[0]}:{client[1]} - {type(e).__name__}: {str(e)}")
|
|
170
|
+
# Still don't re-raise, exit gracefully
|
|
171
|
+
|
|
172
|
+
logger.debug(f"SSE connection closed for {client[0]}:{client[1]}")
|
|
173
|
+
|
|
174
|
+
# Apply the patch
|
|
175
|
+
mcp.server.sse.SseServerTransport.connect_sse = patched_connect_sse
|
|
176
|
+
logger.info("Patched mcp.server.sse.SseServerTransport.connect_sse")
|
|
177
|
+
|
|
178
|
+
# Important patch: For direct SSE handling, ensure proper response is returned
|
|
179
|
+
original_handle_sse = None
|
|
180
|
+
if hasattr(mcp.server.sse.SseServerTransport, 'handle_sse'):
|
|
181
|
+
original_handle_sse = mcp.server.sse.SseServerTransport.handle_sse
|
|
182
|
+
|
|
183
|
+
@functools.wraps(original_handle_sse)
|
|
184
|
+
async def patched_handle_sse(self, request):
|
|
185
|
+
try:
|
|
186
|
+
response = await original_handle_sse(self, request)
|
|
187
|
+
if response is None:
|
|
188
|
+
# Critical fix: Return empty Response instead of None when connection ends
|
|
189
|
+
logger.debug(f"SSE connection ended, returning empty Response for {request.client}")
|
|
190
|
+
return Response(status_code=204)
|
|
191
|
+
return response
|
|
192
|
+
except Exception as e:
|
|
193
|
+
logger.debug(f"Error in handle_sse: {type(e).__name__}: {str(e)}")
|
|
194
|
+
# Always return a Response instead of None or raising
|
|
195
|
+
return Response(status_code=204)
|
|
196
|
+
|
|
197
|
+
# Apply the patch to handle_sse
|
|
198
|
+
mcp.server.sse.SseServerTransport.handle_sse = patched_handle_sse
|
|
199
|
+
logger.info("Patched mcp.server.sse.SseServerTransport.handle_sse")
|
|
200
|
+
|
|
201
|
+
# Next, let's enhance the EventSourceResponse creation to handle disconnects better
|
|
202
|
+
original_event_source_response = EventSourceResponse.__call__
|
|
203
|
+
|
|
204
|
+
@functools.wraps(original_event_source_response)
|
|
205
|
+
async def patched_event_source_response(self, scope, receive, send):
|
|
206
|
+
"""Override to add better client disconnect handling"""
|
|
207
|
+
client = scope.get("client", ("unknown", 0))
|
|
208
|
+
|
|
209
|
+
try:
|
|
210
|
+
# Call original method with better error handling
|
|
211
|
+
return await original_event_source_response(self, scope, receive, send)
|
|
212
|
+
except asyncio.CancelledError:
|
|
213
|
+
logger.debug(f"SSE stream cancelled for client: {client[0]}:{client[1]}")
|
|
214
|
+
# Don't raise, handle gracefully
|
|
215
|
+
return None
|
|
216
|
+
except TypeError as e:
|
|
217
|
+
if "'NoneType' object is not callable" in str(e):
|
|
218
|
+
logger.debug(f"SSE NoneType error for client: {client[0]}:{client[1]}")
|
|
219
|
+
# Most common error when client disconnects, suppress it
|
|
220
|
+
return None
|
|
221
|
+
raise
|
|
222
|
+
except Exception as e:
|
|
223
|
+
logger.debug(f"SSE error for client {client[0]}:{client[1]}: {type(e).__name__}: {str(e)}")
|
|
224
|
+
raise
|
|
225
|
+
|
|
226
|
+
# Apply the patch directly to the method instead of subclassing
|
|
227
|
+
EventSourceResponse.__call__ = patched_event_source_response
|
|
228
|
+
logger.info("Patched sse_starlette.sse.EventSourceResponse.__call__")
|
|
229
|
+
|
|
230
|
+
except Exception as e:
|
|
231
|
+
logger.error(f"Failed to apply MCP SSE patches: {str(e)}")
|
|
232
|
+
|
|
233
|
+
logger.info("Finished applying monkey patches")
|