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,275 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
import asyncio
|
|
4
|
+
import aiohttp
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Dict, Any, Optional, List, Union
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from dotenv import load_dotenv
|
|
10
|
+
|
|
11
|
+
load_dotenv()
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class APIResponse:
|
|
16
|
+
"""Structured response from API calls"""
|
|
17
|
+
success: bool
|
|
18
|
+
data: Any = None
|
|
19
|
+
error: Optional[str] = None
|
|
20
|
+
status_code: Optional[int] = None
|
|
21
|
+
|
|
22
|
+
class MadnessAPIClient:
|
|
23
|
+
"""
|
|
24
|
+
HTTP client for madnessinteractive.cc/api endpoints.
|
|
25
|
+
Handles authentication, retries, and response parsing for MCP tools.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, base_url: str = None, auth_token: str = None, api_key: str = None):
|
|
29
|
+
self.base_url = base_url or os.getenv("MADNESS_API_URL", "https://madnessinteractive.cc/api")
|
|
30
|
+
self.auth_token = auth_token or os.getenv("MADNESS_AUTH_TOKEN")
|
|
31
|
+
self.api_key = api_key or os.getenv("MADNESS_API_KEY")
|
|
32
|
+
self.session: Optional[aiohttp.ClientSession] = None
|
|
33
|
+
self.max_retries = 3
|
|
34
|
+
self.timeout = aiohttp.ClientTimeout(total=30)
|
|
35
|
+
|
|
36
|
+
# Authentication priority: JWT token > API key
|
|
37
|
+
self.auth_headers = {}
|
|
38
|
+
if self.auth_token:
|
|
39
|
+
self.auth_headers["Authorization"] = f"Bearer {self.auth_token}"
|
|
40
|
+
logger.info("Using JWT token authentication")
|
|
41
|
+
elif self.api_key:
|
|
42
|
+
self.auth_headers["Authorization"] = f"Bearer {self.api_key}"
|
|
43
|
+
logger.info("Using API key authentication")
|
|
44
|
+
else:
|
|
45
|
+
logger.warning("No authentication configured - API calls may fail")
|
|
46
|
+
|
|
47
|
+
async def __aenter__(self):
|
|
48
|
+
"""Async context manager entry"""
|
|
49
|
+
await self._ensure_session()
|
|
50
|
+
return self
|
|
51
|
+
|
|
52
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
53
|
+
"""Async context manager exit"""
|
|
54
|
+
await self.close()
|
|
55
|
+
|
|
56
|
+
async def _ensure_session(self):
|
|
57
|
+
"""Ensure aiohttp session is created"""
|
|
58
|
+
if not self.session:
|
|
59
|
+
connector = aiohttp.TCPConnector(limit=10, limit_per_host=5)
|
|
60
|
+
self.session = aiohttp.ClientSession(
|
|
61
|
+
timeout=self.timeout,
|
|
62
|
+
connector=connector,
|
|
63
|
+
headers={"User-Agent": "Omnispindle-MCP/1.0"}
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
async def close(self):
|
|
67
|
+
"""Close the aiohttp session"""
|
|
68
|
+
if self.session:
|
|
69
|
+
await self.session.close()
|
|
70
|
+
self.session = None
|
|
71
|
+
|
|
72
|
+
async def _make_request(self, method: str, endpoint: str, **kwargs) -> APIResponse:
|
|
73
|
+
"""
|
|
74
|
+
Make HTTP request with retries and error handling
|
|
75
|
+
"""
|
|
76
|
+
await self._ensure_session()
|
|
77
|
+
|
|
78
|
+
url = f"{self.base_url.rstrip('/')}/{endpoint.lstrip('/')}"
|
|
79
|
+
|
|
80
|
+
# Merge auth headers with any provided headers
|
|
81
|
+
headers = {**self.auth_headers}
|
|
82
|
+
if 'headers' in kwargs:
|
|
83
|
+
headers.update(kwargs['headers'])
|
|
84
|
+
kwargs['headers'] = headers
|
|
85
|
+
|
|
86
|
+
# Add Content-Type for requests with data
|
|
87
|
+
if method.upper() in ['POST', 'PUT', 'PATCH'] and 'json' in kwargs:
|
|
88
|
+
headers.setdefault('Content-Type', 'application/json')
|
|
89
|
+
|
|
90
|
+
last_error = None
|
|
91
|
+
|
|
92
|
+
for attempt in range(self.max_retries + 1):
|
|
93
|
+
try:
|
|
94
|
+
logger.debug(f"API {method.upper()} {url} (attempt {attempt + 1})")
|
|
95
|
+
|
|
96
|
+
async with self.session.request(method, url, **kwargs) as response:
|
|
97
|
+
response_text = await response.text()
|
|
98
|
+
|
|
99
|
+
# Log response details
|
|
100
|
+
logger.debug(f"API Response: {response.status} {len(response_text)} bytes")
|
|
101
|
+
|
|
102
|
+
# Try to parse JSON response
|
|
103
|
+
try:
|
|
104
|
+
response_data = json.loads(response_text) if response_text else {}
|
|
105
|
+
except json.JSONDecodeError:
|
|
106
|
+
response_data = {"raw_response": response_text}
|
|
107
|
+
|
|
108
|
+
# Handle HTTP status codes
|
|
109
|
+
if response.status == 200 or response.status == 201:
|
|
110
|
+
return APIResponse(
|
|
111
|
+
success=True,
|
|
112
|
+
data=response_data,
|
|
113
|
+
status_code=response.status
|
|
114
|
+
)
|
|
115
|
+
elif response.status == 401:
|
|
116
|
+
error_msg = f"Authentication failed (401): {response_data.get('message', 'Invalid credentials')}"
|
|
117
|
+
logger.error(error_msg)
|
|
118
|
+
return APIResponse(
|
|
119
|
+
success=False,
|
|
120
|
+
error=error_msg,
|
|
121
|
+
status_code=response.status
|
|
122
|
+
)
|
|
123
|
+
elif response.status == 403:
|
|
124
|
+
error_msg = f"Access forbidden (403): {response_data.get('message', 'Insufficient permissions')}"
|
|
125
|
+
logger.error(error_msg)
|
|
126
|
+
return APIResponse(
|
|
127
|
+
success=False,
|
|
128
|
+
error=error_msg,
|
|
129
|
+
status_code=response.status
|
|
130
|
+
)
|
|
131
|
+
elif response.status == 404:
|
|
132
|
+
error_msg = f"Resource not found (404): {response_data.get('message', 'Not found')}"
|
|
133
|
+
return APIResponse(
|
|
134
|
+
success=False,
|
|
135
|
+
error=error_msg,
|
|
136
|
+
status_code=response.status
|
|
137
|
+
)
|
|
138
|
+
elif 400 <= response.status < 500:
|
|
139
|
+
# Client error - don't retry
|
|
140
|
+
error_msg = f"Client error ({response.status}): {response_data.get('message', 'Bad request')}"
|
|
141
|
+
logger.error(error_msg)
|
|
142
|
+
return APIResponse(
|
|
143
|
+
success=False,
|
|
144
|
+
error=error_msg,
|
|
145
|
+
status_code=response.status
|
|
146
|
+
)
|
|
147
|
+
elif response.status >= 500:
|
|
148
|
+
# Server error - retry
|
|
149
|
+
error_msg = f"Server error ({response.status}): {response_data.get('message', 'Internal server error')}"
|
|
150
|
+
logger.warning(f"{error_msg} - will retry")
|
|
151
|
+
last_error = error_msg
|
|
152
|
+
|
|
153
|
+
if attempt < self.max_retries:
|
|
154
|
+
# Exponential backoff
|
|
155
|
+
wait_time = 2 ** attempt
|
|
156
|
+
await asyncio.sleep(wait_time)
|
|
157
|
+
continue
|
|
158
|
+
else:
|
|
159
|
+
return APIResponse(
|
|
160
|
+
success=False,
|
|
161
|
+
error=error_msg,
|
|
162
|
+
status_code=response.status
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
except aiohttp.ClientError as e:
|
|
166
|
+
error_msg = f"Network error: {str(e)}"
|
|
167
|
+
logger.warning(f"{error_msg} - attempt {attempt + 1}")
|
|
168
|
+
last_error = error_msg
|
|
169
|
+
|
|
170
|
+
if attempt < self.max_retries:
|
|
171
|
+
# Exponential backoff for network errors
|
|
172
|
+
wait_time = 2 ** attempt
|
|
173
|
+
await asyncio.sleep(wait_time)
|
|
174
|
+
continue
|
|
175
|
+
else:
|
|
176
|
+
return APIResponse(
|
|
177
|
+
success=False,
|
|
178
|
+
error=error_msg,
|
|
179
|
+
status_code=None
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
except Exception as e:
|
|
183
|
+
error_msg = f"Unexpected error: {str(e)}"
|
|
184
|
+
logger.error(error_msg)
|
|
185
|
+
return APIResponse(
|
|
186
|
+
success=False,
|
|
187
|
+
error=error_msg,
|
|
188
|
+
status_code=None
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# Should not reach here, but just in case
|
|
192
|
+
return APIResponse(
|
|
193
|
+
success=False,
|
|
194
|
+
error=last_error or "Unknown error after retries",
|
|
195
|
+
status_code=None
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
# Health check
|
|
199
|
+
async def health_check(self) -> APIResponse:
|
|
200
|
+
"""Check API health and connectivity"""
|
|
201
|
+
return await self._make_request("GET", "/health")
|
|
202
|
+
|
|
203
|
+
# Todo operations
|
|
204
|
+
async def get_todos(self, project: str = None, status: str = None, priority: str = None, limit: int = 100) -> APIResponse:
|
|
205
|
+
"""Get todos with optional filtering"""
|
|
206
|
+
params = {}
|
|
207
|
+
if project:
|
|
208
|
+
params["project"] = project
|
|
209
|
+
if status:
|
|
210
|
+
params["status"] = status
|
|
211
|
+
if priority:
|
|
212
|
+
params["priority"] = priority
|
|
213
|
+
if limit:
|
|
214
|
+
params["limit"] = limit
|
|
215
|
+
|
|
216
|
+
return await self._make_request("GET", "/todos", params=params)
|
|
217
|
+
|
|
218
|
+
async def get_todo(self, todo_id: str) -> APIResponse:
|
|
219
|
+
"""Get a specific todo by ID"""
|
|
220
|
+
return await self._make_request("GET", f"/todos/{todo_id}")
|
|
221
|
+
|
|
222
|
+
async def create_todo(self, description: str, project: str, priority: str = "Medium", metadata: Optional[Dict[str, Any]] = None) -> APIResponse:
|
|
223
|
+
"""Create a new todo"""
|
|
224
|
+
payload = {
|
|
225
|
+
"description": description,
|
|
226
|
+
"project": project,
|
|
227
|
+
"priority": priority
|
|
228
|
+
}
|
|
229
|
+
if metadata:
|
|
230
|
+
payload["metadata"] = metadata
|
|
231
|
+
|
|
232
|
+
return await self._make_request("POST", "/todos", json=payload)
|
|
233
|
+
|
|
234
|
+
async def update_todo(self, todo_id: str, updates: Dict[str, Any]) -> APIResponse:
|
|
235
|
+
"""Update an existing todo"""
|
|
236
|
+
return await self._make_request("PUT", f"/todos/{todo_id}", json=updates)
|
|
237
|
+
|
|
238
|
+
async def delete_todo(self, todo_id: str) -> APIResponse:
|
|
239
|
+
"""Delete a todo"""
|
|
240
|
+
return await self._make_request("DELETE", f"/todos/{todo_id}")
|
|
241
|
+
|
|
242
|
+
async def complete_todo(self, todo_id: str, comment: str = None) -> APIResponse:
|
|
243
|
+
"""Mark a todo as complete"""
|
|
244
|
+
payload = {}
|
|
245
|
+
if comment:
|
|
246
|
+
payload["comment"] = comment
|
|
247
|
+
|
|
248
|
+
return await self._make_request("POST", f"/todos/{todo_id}/complete", json=payload)
|
|
249
|
+
|
|
250
|
+
async def get_todo_stats(self, project: str = None) -> APIResponse:
|
|
251
|
+
"""Get todo statistics"""
|
|
252
|
+
params = {}
|
|
253
|
+
if project:
|
|
254
|
+
params["project"] = project
|
|
255
|
+
|
|
256
|
+
return await self._make_request("GET", "/todos/stats", params=params)
|
|
257
|
+
|
|
258
|
+
async def get_projects(self) -> APIResponse:
|
|
259
|
+
"""Get available projects"""
|
|
260
|
+
return await self._make_request("GET", "/projects")
|
|
261
|
+
|
|
262
|
+
# Factory function for creating API client instances
|
|
263
|
+
def create_api_client(auth_token: str = None, api_key: str = None) -> MadnessAPIClient:
|
|
264
|
+
"""Factory function to create API client with authentication"""
|
|
265
|
+
return MadnessAPIClient(auth_token=auth_token, api_key=api_key)
|
|
266
|
+
|
|
267
|
+
# Singleton instance for module-level usage
|
|
268
|
+
_default_client: Optional[MadnessAPIClient] = None
|
|
269
|
+
|
|
270
|
+
async def get_default_client() -> MadnessAPIClient:
|
|
271
|
+
"""Get or create default API client instance"""
|
|
272
|
+
global _default_client
|
|
273
|
+
if not _default_client:
|
|
274
|
+
_default_client = create_api_client()
|
|
275
|
+
return _default_client
|
Omnispindle/api_tools.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""
|
|
2
|
+
API-based tools for Omnispindle MCP server.
|
|
3
|
+
Replaces direct database operations with HTTP API calls to madnessinteractive.cc/api
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
import uuid
|
|
7
|
+
import logging
|
|
8
|
+
from typing import Union, List, Dict, Optional, Any
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
|
|
11
|
+
from .api_client import MadnessAPIClient, APIResponse, get_default_client
|
|
12
|
+
from .context import Context
|
|
13
|
+
from .utils import create_response
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
# Project validation - will be fetched from API
|
|
18
|
+
FALLBACK_VALID_PROJECTS = [
|
|
19
|
+
"madness_interactive", "regressiontestkit", "omnispindle",
|
|
20
|
+
"todomill_projectorium", "swarmonomicon", "hammerspoon",
|
|
21
|
+
"lab_management", "cogwyrm", "docker_implementation",
|
|
22
|
+
"documentation", "eventghost-rust", "hammerghost",
|
|
23
|
+
"quality_assurance", "spindlewrit", "inventorium"
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
def _get_auth_from_context(ctx: Optional[Context]) -> tuple[Optional[str], Optional[str]]:
|
|
27
|
+
"""Extract authentication tokens from context"""
|
|
28
|
+
auth_token = None
|
|
29
|
+
api_key = None
|
|
30
|
+
|
|
31
|
+
if ctx and ctx.user:
|
|
32
|
+
# Try to extract JWT token from user context
|
|
33
|
+
auth_token = ctx.user.get("access_token")
|
|
34
|
+
# Or API key if provided
|
|
35
|
+
api_key = ctx.user.get("api_key")
|
|
36
|
+
|
|
37
|
+
return auth_token, api_key
|
|
38
|
+
|
|
39
|
+
def _convert_api_todo_to_mcp_format(api_todo: dict) -> dict:
|
|
40
|
+
"""
|
|
41
|
+
Convert API todo format to MCP format for backward compatibility
|
|
42
|
+
"""
|
|
43
|
+
# API uses different field names than our MCP tools expect
|
|
44
|
+
mcp_todo = {
|
|
45
|
+
"id": api_todo.get("id"),
|
|
46
|
+
"description": api_todo.get("description"),
|
|
47
|
+
"project": api_todo.get("project"),
|
|
48
|
+
"priority": api_todo.get("priority", "Medium"),
|
|
49
|
+
"status": api_todo.get("status", "pending"),
|
|
50
|
+
"created_at": api_todo.get("created_at"),
|
|
51
|
+
"metadata": api_todo.get("metadata", {})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
# Handle completion data
|
|
55
|
+
if api_todo.get("completed_at"):
|
|
56
|
+
mcp_todo["completed_at"] = api_todo["completed_at"]
|
|
57
|
+
if api_todo.get("duration"):
|
|
58
|
+
mcp_todo["duration"] = api_todo["duration"]
|
|
59
|
+
if api_todo.get("duration_sec"):
|
|
60
|
+
mcp_todo["duration_sec"] = api_todo["duration_sec"]
|
|
61
|
+
|
|
62
|
+
# Handle completion comment from metadata
|
|
63
|
+
if api_todo.get("completion_comment"):
|
|
64
|
+
mcp_todo["metadata"]["completion_comment"] = api_todo["completion_comment"]
|
|
65
|
+
|
|
66
|
+
return mcp_todo
|
|
67
|
+
|
|
68
|
+
def _handle_api_response(api_response: APIResponse) -> str:
|
|
69
|
+
"""
|
|
70
|
+
Convert API response to MCP tool response format
|
|
71
|
+
"""
|
|
72
|
+
if not api_response.success:
|
|
73
|
+
return create_response(False, message=api_response.error or "API request failed")
|
|
74
|
+
|
|
75
|
+
return create_response(True, api_response.data)
|
|
76
|
+
|
|
77
|
+
async def add_todo(description: str, project: str, priority: str = "Medium",
|
|
78
|
+
target_agent: str = "user", metadata: Optional[Dict[str, Any]] = None,
|
|
79
|
+
ctx: Optional[Context] = None) -> str:
|
|
80
|
+
"""
|
|
81
|
+
Creates a task in the specified project with the given priority and target agent.
|
|
82
|
+
Returns a compact representation of the created todo with an ID for reference.
|
|
83
|
+
"""
|
|
84
|
+
try:
|
|
85
|
+
auth_token, api_key = _get_auth_from_context(ctx)
|
|
86
|
+
|
|
87
|
+
# Add target_agent to metadata if provided
|
|
88
|
+
if not metadata:
|
|
89
|
+
metadata = {}
|
|
90
|
+
if target_agent and target_agent != "user":
|
|
91
|
+
metadata["target_agent"] = target_agent
|
|
92
|
+
|
|
93
|
+
async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
|
|
94
|
+
api_response = await client.create_todo(
|
|
95
|
+
description=description,
|
|
96
|
+
project=project,
|
|
97
|
+
priority=priority,
|
|
98
|
+
metadata=metadata
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
if not api_response.success:
|
|
102
|
+
return create_response(False, message=api_response.error or "Failed to create todo")
|
|
103
|
+
|
|
104
|
+
# Extract todo from API response
|
|
105
|
+
api_data = api_response.data
|
|
106
|
+
if isinstance(api_data, dict) and 'todo' in api_data:
|
|
107
|
+
todo_data = api_data['todo']
|
|
108
|
+
elif isinstance(api_data, dict) and 'data' in api_data:
|
|
109
|
+
todo_data = api_data['data']
|
|
110
|
+
else:
|
|
111
|
+
todo_data = api_data
|
|
112
|
+
|
|
113
|
+
# Convert to MCP format
|
|
114
|
+
mcp_todo = _convert_api_todo_to_mcp_format(todo_data)
|
|
115
|
+
|
|
116
|
+
# Create compact response similar to original
|
|
117
|
+
return create_response(True, {
|
|
118
|
+
"operation": "create",
|
|
119
|
+
"status": "success",
|
|
120
|
+
"todo_id": mcp_todo["id"],
|
|
121
|
+
"description": description[:40] + ("..." if len(description) > 40 else ""),
|
|
122
|
+
"project": project
|
|
123
|
+
}, message=f"Todo '{description[:30]}...' created in '{project}'.")
|
|
124
|
+
|
|
125
|
+
except Exception as e:
|
|
126
|
+
logger.error(f"Failed to create todo via API: {str(e)}")
|
|
127
|
+
return create_response(False, message=f"API error: {str(e)}")
|
|
128
|
+
|
|
129
|
+
async def query_todos(filter: Optional[Dict[str, Any]] = None, projection: Optional[Dict[str, Any]] = None,
|
|
130
|
+
limit: int = 100, ctx: Optional[Context] = None) -> str:
|
|
131
|
+
"""
|
|
132
|
+
Query todos with flexible filtering options from API.
|
|
133
|
+
"""
|
|
134
|
+
try:
|
|
135
|
+
auth_token, api_key = _get_auth_from_context(ctx)
|
|
136
|
+
|
|
137
|
+
# Convert MongoDB-style filter to API query parameters
|
|
138
|
+
project = None
|
|
139
|
+
status = None
|
|
140
|
+
priority = None
|
|
141
|
+
|
|
142
|
+
if filter:
|
|
143
|
+
project = filter.get("project")
|
|
144
|
+
status = filter.get("status")
|
|
145
|
+
priority = filter.get("priority")
|
|
146
|
+
|
|
147
|
+
async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
|
|
148
|
+
api_response = await client.get_todos(
|
|
149
|
+
project=project,
|
|
150
|
+
status=status,
|
|
151
|
+
priority=priority,
|
|
152
|
+
limit=limit
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
if not api_response.success:
|
|
156
|
+
return create_response(False, message=api_response.error or "Failed to query todos")
|
|
157
|
+
|
|
158
|
+
# Extract todos from API response
|
|
159
|
+
api_data = api_response.data
|
|
160
|
+
if isinstance(api_data, dict) and 'todos' in api_data:
|
|
161
|
+
todos_list = api_data['todos']
|
|
162
|
+
else:
|
|
163
|
+
todos_list = api_data if isinstance(api_data, list) else []
|
|
164
|
+
|
|
165
|
+
# Convert each todo to MCP format
|
|
166
|
+
mcp_todos = [_convert_api_todo_to_mcp_format(todo) for todo in todos_list]
|
|
167
|
+
|
|
168
|
+
return create_response(True, {"items": mcp_todos})
|
|
169
|
+
|
|
170
|
+
except Exception as e:
|
|
171
|
+
logger.error(f"Failed to query todos via API: {str(e)}")
|
|
172
|
+
return create_response(False, message=f"API error: {str(e)}")
|
|
173
|
+
|
|
174
|
+
async def update_todo(todo_id: str, updates: dict, ctx: Optional[Context] = None) -> str:
|
|
175
|
+
"""
|
|
176
|
+
Update a todo with the provided changes.
|
|
177
|
+
"""
|
|
178
|
+
try:
|
|
179
|
+
auth_token, api_key = _get_auth_from_context(ctx)
|
|
180
|
+
|
|
181
|
+
async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
|
|
182
|
+
api_response = await client.update_todo(todo_id, updates)
|
|
183
|
+
|
|
184
|
+
if not api_response.success:
|
|
185
|
+
return create_response(False, message=api_response.error or f"Failed to update todo {todo_id}")
|
|
186
|
+
|
|
187
|
+
return create_response(True, message=f"Todo {todo_id} updated successfully")
|
|
188
|
+
|
|
189
|
+
except Exception as e:
|
|
190
|
+
logger.error(f"Failed to update todo via API: {str(e)}")
|
|
191
|
+
return create_response(False, message=f"API error: {str(e)}")
|
|
192
|
+
|
|
193
|
+
async def delete_todo(todo_id: str, ctx: Optional[Context] = None) -> str:
|
|
194
|
+
"""
|
|
195
|
+
Delete a todo item by its ID.
|
|
196
|
+
"""
|
|
197
|
+
try:
|
|
198
|
+
auth_token, api_key = _get_auth_from_context(ctx)
|
|
199
|
+
|
|
200
|
+
async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
|
|
201
|
+
api_response = await client.delete_todo(todo_id)
|
|
202
|
+
|
|
203
|
+
if not api_response.success:
|
|
204
|
+
return create_response(False, message=api_response.error or f"Failed to delete todo {todo_id}")
|
|
205
|
+
|
|
206
|
+
return create_response(True, message=f"Todo {todo_id} deleted successfully.")
|
|
207
|
+
|
|
208
|
+
except Exception as e:
|
|
209
|
+
logger.error(f"Failed to delete todo via API: {str(e)}")
|
|
210
|
+
return create_response(False, message=f"API error: {str(e)}")
|
|
211
|
+
|
|
212
|
+
async def get_todo(todo_id: str, ctx: Optional[Context] = None) -> str:
|
|
213
|
+
"""
|
|
214
|
+
Get a specific todo item by its ID.
|
|
215
|
+
"""
|
|
216
|
+
try:
|
|
217
|
+
auth_token, api_key = _get_auth_from_context(ctx)
|
|
218
|
+
|
|
219
|
+
async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
|
|
220
|
+
api_response = await client.get_todo(todo_id)
|
|
221
|
+
|
|
222
|
+
if not api_response.success:
|
|
223
|
+
return create_response(False, message=api_response.error or f"Todo with ID {todo_id} not found.")
|
|
224
|
+
|
|
225
|
+
# Convert to MCP format
|
|
226
|
+
mcp_todo = _convert_api_todo_to_mcp_format(api_response.data)
|
|
227
|
+
return create_response(True, mcp_todo)
|
|
228
|
+
|
|
229
|
+
except Exception as e:
|
|
230
|
+
logger.error(f"Failed to get todo via API: {str(e)}")
|
|
231
|
+
return create_response(False, message=f"API error: {str(e)}")
|
|
232
|
+
|
|
233
|
+
async def mark_todo_complete(todo_id: str, comment: Optional[str] = None, ctx: Optional[Context] = None) -> str:
|
|
234
|
+
"""
|
|
235
|
+
Mark a todo as completed.
|
|
236
|
+
"""
|
|
237
|
+
try:
|
|
238
|
+
auth_token, api_key = _get_auth_from_context(ctx)
|
|
239
|
+
|
|
240
|
+
async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
|
|
241
|
+
api_response = await client.complete_todo(todo_id, comment)
|
|
242
|
+
|
|
243
|
+
if not api_response.success:
|
|
244
|
+
return create_response(False, message=api_response.error or f"Failed to complete todo {todo_id}")
|
|
245
|
+
|
|
246
|
+
return create_response(True, message=f"Todo {todo_id} marked as complete.")
|
|
247
|
+
|
|
248
|
+
except Exception as e:
|
|
249
|
+
logger.error(f"Failed to complete todo via API: {str(e)}")
|
|
250
|
+
return create_response(False, message=f"API error: {str(e)}")
|
|
251
|
+
|
|
252
|
+
async def list_todos_by_status(status: str, limit: int = 100, ctx: Optional[Context] = None) -> str:
|
|
253
|
+
"""
|
|
254
|
+
List todos filtered by their status.
|
|
255
|
+
"""
|
|
256
|
+
if status.lower() not in ['pending', 'completed', 'review']:
|
|
257
|
+
return create_response(False, message="Invalid status. Must be one of 'pending', 'completed', 'review'.")
|
|
258
|
+
|
|
259
|
+
return await query_todos(filter={"status": status.lower()}, limit=limit, ctx=ctx)
|
|
260
|
+
|
|
261
|
+
async def search_todos(query: str, fields: Optional[list] = None, limit: int = 100, ctx: Optional[Context] = None) -> str:
|
|
262
|
+
"""
|
|
263
|
+
Search todos with text search capabilities.
|
|
264
|
+
For API-based search, we'll use the general query endpoint for now.
|
|
265
|
+
"""
|
|
266
|
+
try:
|
|
267
|
+
auth_token, api_key = _get_auth_from_context(ctx)
|
|
268
|
+
|
|
269
|
+
# For now, we'll fetch all todos and filter client-side
|
|
270
|
+
# In future, the API should support text search parameters
|
|
271
|
+
async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
|
|
272
|
+
api_response = await client.get_todos(limit=limit)
|
|
273
|
+
|
|
274
|
+
if not api_response.success:
|
|
275
|
+
return create_response(False, message=api_response.error or "Failed to search todos")
|
|
276
|
+
|
|
277
|
+
# Extract todos from API response
|
|
278
|
+
api_data = api_response.data
|
|
279
|
+
if isinstance(api_data, dict) and 'todos' in api_data:
|
|
280
|
+
todos_list = api_data['todos']
|
|
281
|
+
else:
|
|
282
|
+
todos_list = api_data if isinstance(api_data, list) else []
|
|
283
|
+
|
|
284
|
+
# Client-side text search
|
|
285
|
+
if fields is None:
|
|
286
|
+
fields = ["description", "project"]
|
|
287
|
+
|
|
288
|
+
filtered_todos = []
|
|
289
|
+
query_lower = query.lower()
|
|
290
|
+
|
|
291
|
+
for todo in todos_list:
|
|
292
|
+
for field in fields:
|
|
293
|
+
if field in todo and query_lower in str(todo[field]).lower():
|
|
294
|
+
filtered_todos.append(_convert_api_todo_to_mcp_format(todo))
|
|
295
|
+
break # Don't add the same todo multiple times
|
|
296
|
+
|
|
297
|
+
return create_response(True, {"items": filtered_todos})
|
|
298
|
+
|
|
299
|
+
except Exception as e:
|
|
300
|
+
logger.error(f"Failed to search todos via API: {str(e)}")
|
|
301
|
+
return create_response(False, message=f"API error: {str(e)}")
|
|
302
|
+
|
|
303
|
+
async def list_project_todos(project: str, limit: int = 5, ctx: Optional[Context] = None) -> str:
|
|
304
|
+
"""
|
|
305
|
+
List recent active todos for a specific project.
|
|
306
|
+
"""
|
|
307
|
+
return await query_todos(
|
|
308
|
+
filter={"project": project.lower(), "status": "pending"},
|
|
309
|
+
limit=limit,
|
|
310
|
+
ctx=ctx
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
async def list_projects(include_details: Union[bool, str] = False, madness_root: str = "/Users/d.edens/lab/madness_interactive", ctx: Optional[Context] = None) -> str:
|
|
314
|
+
"""
|
|
315
|
+
List all valid projects from the API.
|
|
316
|
+
"""
|
|
317
|
+
try:
|
|
318
|
+
auth_token, api_key = _get_auth_from_context(ctx)
|
|
319
|
+
|
|
320
|
+
async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
|
|
321
|
+
api_response = await client.get_projects()
|
|
322
|
+
|
|
323
|
+
if not api_response.success:
|
|
324
|
+
# Fallback to hardcoded projects if API fails
|
|
325
|
+
logger.warning(f"API projects fetch failed, using fallback: {api_response.error}")
|
|
326
|
+
return create_response(True, {"projects": FALLBACK_VALID_PROJECTS})
|
|
327
|
+
|
|
328
|
+
# Extract projects from API response
|
|
329
|
+
api_data = api_response.data
|
|
330
|
+
if isinstance(api_data, dict) and 'projects' in api_data:
|
|
331
|
+
projects_list = api_data['projects']
|
|
332
|
+
# Extract just the project names for compatibility
|
|
333
|
+
project_names = [proj.get('id', proj.get('name', '')) for proj in projects_list]
|
|
334
|
+
return create_response(True, {"projects": project_names})
|
|
335
|
+
else:
|
|
336
|
+
return create_response(True, {"projects": FALLBACK_VALID_PROJECTS})
|
|
337
|
+
|
|
338
|
+
except Exception as e:
|
|
339
|
+
logger.error(f"Failed to get projects via API: {str(e)}")
|
|
340
|
+
# Fallback to hardcoded projects
|
|
341
|
+
return create_response(True, {"projects": FALLBACK_VALID_PROJECTS})
|
|
342
|
+
|
|
343
|
+
# Placeholder functions for non-todo operations that aren't yet available via API
|
|
344
|
+
# These maintain backward compatibility while we transition
|
|
345
|
+
|
|
346
|
+
async def add_lesson(language: str, topic: str, lesson_learned: str, tags: Optional[list] = None, ctx: Optional[Context] = None) -> str:
|
|
347
|
+
"""Add a new lesson to the knowledge base - API not yet available"""
|
|
348
|
+
return create_response(False, message="Lesson management not yet available via API. Use local mode.")
|
|
349
|
+
|
|
350
|
+
async def get_lesson(lesson_id: str, ctx: Optional[Context] = None) -> str:
|
|
351
|
+
"""Get a specific lesson by its ID - API not yet available"""
|
|
352
|
+
return create_response(False, message="Lesson management not yet available via API. Use local mode.")
|
|
353
|
+
|
|
354
|
+
async def update_lesson(lesson_id: str, updates: dict, ctx: Optional[Context] = None) -> str:
|
|
355
|
+
"""Update an existing lesson - API not yet available"""
|
|
356
|
+
return create_response(False, message="Lesson management not yet available via API. Use local mode.")
|
|
357
|
+
|
|
358
|
+
async def delete_lesson(lesson_id: str, ctx: Optional[Context] = None) -> str:
|
|
359
|
+
"""Delete a lesson by its ID - API not yet available"""
|
|
360
|
+
return create_response(False, message="Lesson management not yet available via API. Use local mode.")
|
|
361
|
+
|
|
362
|
+
async def search_lessons(query: str, fields: Optional[list] = None, limit: int = 100, brief: bool = False, ctx: Optional[Context] = None) -> str:
|
|
363
|
+
"""Search lessons with text search capabilities - API not yet available"""
|
|
364
|
+
return create_response(False, message="Lesson management not yet available via API. Use local mode.")
|
|
365
|
+
|
|
366
|
+
async def grep_lessons(pattern: str, limit: int = 20, ctx: Optional[Context] = None) -> str:
|
|
367
|
+
"""Search lessons with grep-style pattern matching - API not yet available"""
|
|
368
|
+
return create_response(False, message="Lesson management not yet available via API. Use local mode.")
|
|
369
|
+
|
|
370
|
+
async def list_lessons(limit: int = 100, brief: bool = False, ctx: Optional[Context] = None) -> str:
|
|
371
|
+
"""List all lessons, sorted by creation date - API not yet available"""
|
|
372
|
+
return create_response(False, message="Lesson management not yet available via API. Use local mode.")
|
|
373
|
+
|
|
374
|
+
async def query_todo_logs(filter_type: str = 'all', project: str = 'all',
|
|
375
|
+
page: int = 1, page_size: int = 20, ctx: Optional[Context] = None) -> str:
|
|
376
|
+
"""Query todo logs - API not yet available"""
|
|
377
|
+
return create_response(False, message="Todo logs not yet available via API. Use local mode.")
|
|
378
|
+
|
|
379
|
+
async def add_explanation(topic: str, content: str, kind: str = "concept", author: str = "system", ctx: Optional[Context] = None) -> str:
|
|
380
|
+
"""Add explanation - API not yet available"""
|
|
381
|
+
return create_response(False, message="Explanations not yet available via API. Use local mode.")
|
|
382
|
+
|
|
383
|
+
async def explain_tool(topic: str, brief: bool = False, ctx: Optional[Context] = None) -> str:
|
|
384
|
+
"""Explain tool - API not yet available"""
|
|
385
|
+
return create_response(False, message="Explanations not yet available via API. Use local mode.")
|
|
386
|
+
|
|
387
|
+
async def point_out_obvious(observation: str, sarcasm_level: int = 5, ctx: Optional[Context] = None) -> str:
|
|
388
|
+
"""Point out obvious - API not yet available"""
|
|
389
|
+
return create_response(False, message="This tool is not yet available via API. Use local mode.")
|
|
390
|
+
|
|
391
|
+
async def bring_your_own(tool_name: str, code: str, runtime: str = "python",
|
|
392
|
+
timeout: int = 30, args: Optional[Dict[str, Any]] = None,
|
|
393
|
+
persist: bool = False, ctx: Optional[Context] = None) -> str:
|
|
394
|
+
"""Bring your own tool - API not yet available"""
|
|
395
|
+
return create_response(False, message="Custom tools not yet available via API. Use local mode.")
|