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/context.py ADDED
@@ -0,0 +1,16 @@
1
+ from typing import Any, Dict, Optional
2
+ from dataclasses import dataclass, field
3
+ from pymongo import MongoClient
4
+
5
+
6
+ @dataclass
7
+ class Context:
8
+ """
9
+ A context object to hold request-specific state that can be passed through the system.
10
+ This helps avoid passing multiple arguments through function calls and provides a consistent
11
+ way to access common objects like database connections or user information.
12
+ """
13
+ user: Optional[Dict[str, Any]] = None
14
+ database: Optional[MongoClient] = None
15
+ # You can add other request-scoped objects here, e.g., logger, settings
16
+ metadata: Dict[str, Any] = field(default_factory=dict)
@@ -0,0 +1,164 @@
1
+ import os
2
+ import re
3
+ from typing import Optional, Dict, Any
4
+ from pymongo import MongoClient
5
+ from dotenv import load_dotenv
6
+ from pymongo.collection import Collection
7
+ from pymongo.database import Database as MongoDatabase
8
+
9
+ # Load environment variables from .env file
10
+ load_dotenv()
11
+
12
+ # MongoDB configuration
13
+ MONGODB_URI = os.getenv("MONGODB_URI", "mongodb://localhost:27017")
14
+ MONGODB_DB_NAME = os.getenv("MONGODB_DB", "swarmonomicon") # Fallback/shared database
15
+
16
+
17
+ def sanitize_database_name(user_context: Dict[str, Any]) -> str:
18
+ """
19
+ Convert user context to a valid MongoDB database name.
20
+ REQUIRES Auth0 'sub' field - no email fallbacks to prevent database fragmentation.
21
+ MongoDB database names cannot contain certain characters.
22
+ """
23
+ # REQUIRE Auth0 'sub' - the canonical, immutable user identifier
24
+ if 'sub' in user_context and user_context['sub']:
25
+ user_id = user_context['sub']
26
+ sanitized = re.sub(r'[^a-zA-Z0-9_]', '_', user_id)
27
+ database_name = f"user_{sanitized}"
28
+ print(f"✅ Database naming: Using Auth0 sub: {user_id} -> {database_name}")
29
+ else:
30
+ # NO FALLBACKS - this prevents database fragmentation
31
+ # If there's no Auth0 sub, use shared database instead of creating user-specific one
32
+ database_name = "swarmonomicon"
33
+ user_info = user_context.get('email', user_context.get('id', 'unknown'))
34
+ print(f"⚠️ Database naming: No Auth0 sub found for user {user_info}")
35
+ print(f"⚠️ Database naming: Using shared database to prevent fragmentation: {database_name}")
36
+ print(f"⚠️ Database naming: User should authenticate via Auth0 for private database")
37
+
38
+ # MongoDB database names are limited to 64 characters
39
+ if len(database_name) > 64:
40
+ database_name = database_name[:64]
41
+
42
+ return database_name
43
+
44
+
45
+ class Database:
46
+ """A singleton class to manage MongoDB connections with user-scoped databases."""
47
+ _instance = None
48
+ client: MongoClient | None = None
49
+ shared_db: MongoDatabase | None = None # The original swarmonomicon database
50
+ _user_databases: Dict[str, MongoDatabase] = {} # Cache of user databases
51
+
52
+ def __new__(cls):
53
+ if cls._instance is None:
54
+ cls._instance = super(Database, cls).__new__(cls)
55
+ cls._instance._user_databases = {}
56
+ try:
57
+ cls._instance.client = MongoClient(MONGODB_URI)
58
+ # Ping the server to verify the connection
59
+ cls._instance.client.admin.command('ping')
60
+ print("MongoDB connection successful.")
61
+ except Exception as e:
62
+ print(f"Error connecting to MongoDB: {e}")
63
+ cls._instance.client = None
64
+
65
+ # Initialize shared database (legacy swarmonomicon)
66
+ if cls._instance.client is not None:
67
+ cls._instance.shared_db = cls._instance.client[MONGODB_DB_NAME]
68
+ else:
69
+ cls._instance.shared_db = None
70
+
71
+ return cls._instance
72
+
73
+ def get_user_database(self, user_context: Optional[Dict[str, Any]] = None) -> MongoDatabase:
74
+ """
75
+ Get the appropriate database for a user context.
76
+ Returns user-specific database if user is authenticated, otherwise shared database.
77
+ """
78
+ if self.client is None:
79
+ raise RuntimeError("MongoDB client not initialized")
80
+
81
+ # If no user context, return shared database
82
+ if not user_context or not user_context.get('sub'):
83
+ return self.shared_db
84
+
85
+ db_name = sanitize_database_name(user_context)
86
+
87
+ # Return cached database if we have it
88
+ if db_name in self._user_databases:
89
+ return self._user_databases[db_name]
90
+
91
+ # Create and cache new user database
92
+ user_db = self.client[db_name]
93
+ self._user_databases[db_name] = user_db
94
+
95
+ user_id = user_context.get('sub', user_context.get('email', 'unknown'))
96
+ print(f"Initialized user database: {db_name} for user {user_id}")
97
+ return user_db
98
+
99
+ def get_collections(self, user_context: Optional[Dict[str, Any]] = None) -> Dict[str, Collection]:
100
+ """
101
+ Get all collections for the appropriate database (user-scoped or shared).
102
+ """
103
+ db = self.get_user_database(user_context)
104
+ collections_dict = {
105
+ 'todos': db["todos"],
106
+ 'lessons': db["lessons_learned"],
107
+ 'tags_cache': db["tags_cache"],
108
+ 'projects': db["projects"],
109
+ 'explanations': db["explanations"],
110
+ 'logs': db["todo_logs"]
111
+ }
112
+ # Add database reference for custom collection access
113
+ collections_dict['database'] = db
114
+ return collections_dict
115
+
116
+ # Legacy properties for backward compatibility (use shared database)
117
+ @property
118
+ def db(self) -> MongoDatabase:
119
+ """Legacy property - returns shared database"""
120
+ return self.shared_db
121
+
122
+ @property
123
+ def todos(self) -> Collection:
124
+ """
125
+ Legacy property for todos collection from shared database
126
+ """
127
+ return self.shared_db["todos"] if self.shared_db is not None else None
128
+
129
+ @property
130
+ def lessons(self) -> Collection:
131
+ """
132
+ Legacy property for lessons_learned collection from shared database
133
+ """
134
+ return self.shared_db["lessons_learned"] if self.shared_db is not None else None
135
+
136
+ @property
137
+ def tags_cache(self) -> Collection:
138
+ """
139
+ Legacy property for tags_cache collection from shared database
140
+ """
141
+ return self.shared_db["tags_cache"] if self.shared_db is not None else None
142
+
143
+ @property
144
+ def projects(self) -> Collection:
145
+ """
146
+ Legacy property for projects collection from shared database
147
+ """
148
+ return self.shared_db["projects"] if self.shared_db is not None else None
149
+
150
+ @property
151
+ def explanations(self) -> Collection:
152
+ """
153
+ Legacy property for explanations collection from shared database
154
+ """
155
+ return self.shared_db["explanations"] if self.shared_db is not None else None
156
+
157
+ @property
158
+ def logs(self) -> Collection:
159
+
160
+ return self.shared_db["todo_logs"] if self.shared_db is not None else None
161
+
162
+
163
+ # Export a single instance for the application to use
164
+ db_connection = Database()
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ FastMCP HTTP Server for Omnispindle with user-scoped databases.
4
+
5
+ This server uses the recommended FastMCP HTTP transport for remote deployments.
6
+ Run with: fastmcp run src/Omnispindle/http_server.py
7
+ """
8
+
9
+ import asyncio
10
+ import logging
11
+ import os
12
+ from typing import Dict, Any, Optional, Union, List
13
+
14
+ from fastmcp import FastMCP
15
+ from dotenv import load_dotenv
16
+
17
+ from src.Omnispindle.context import Context
18
+ from src.Omnispindle.patches import apply_patches
19
+ from src.Omnispindle.auth_utils import verify_auth0_token
20
+ from src.Omnispindle.auth_flow import ensure_authenticated, run_async_in_thread
21
+ from src.Omnispindle import tools
22
+
23
+ # Initialize
24
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
25
+ logger = logging.getLogger(__name__)
26
+ apply_patches()
27
+ load_dotenv()
28
+
29
+ # Tool loadout configurations
30
+ TOOL_LOADOUTS = {
31
+ "full": [
32
+ "add_todo", "query_todos", "update_todo", "delete_todo", "get_todo",
33
+ "mark_todo_complete", "list_todos_by_status", "search_todos", "list_project_todos",
34
+ "add_lesson", "get_lesson", "update_lesson", "delete_lesson", "search_lessons",
35
+ "grep_lessons", "list_lessons", "query_todo_logs", "list_projects",
36
+ "explain", "add_explanation", "point_out_obvious", "bring_your_own"
37
+ ],
38
+ "basic": [
39
+ "add_todo", "query_todos", "update_todo", "get_todo", "mark_todo_complete",
40
+ "list_todos_by_status", "list_project_todos"
41
+ ],
42
+ "minimal": [
43
+ "add_todo", "query_todos", "get_todo", "mark_todo_complete"
44
+ ],
45
+ "lessons": [
46
+ "add_lesson", "get_lesson", "update_lesson", "delete_lesson", "search_lessons",
47
+ "grep_lessons", "list_lessons"
48
+ ],
49
+ "admin": [
50
+ "query_todos", "update_todo", "delete_todo", "query_todo_logs",
51
+ "list_projects", "explain", "add_explanation"
52
+ ]
53
+ }
54
+
55
+ # Create the FastMCP instance that fastmcp run will use
56
+ mcp = FastMCP("Omnispindle 🌪️")
57
+
58
+
59
+ # Get tool loadout from environment
60
+ loadout_name = os.getenv("OMNISPINDLE_TOOL_LOADOUT", "full")
61
+ if loadout_name not in TOOL_LOADOUTS:
62
+ logger.warning(f"Unknown loadout '{loadout_name}', using 'full'")
63
+ loadout_name = "full"
64
+
65
+ selected_tools = TOOL_LOADOUTS[loadout_name]
66
+ logger.info(f"Loading '{loadout_name}' loadout: {selected_tools}")
67
+
68
+ # Register specific tools manually for HTTP transport compatibility
69
+ if "add_todo" in selected_tools:
70
+ @mcp.tool()
71
+ async def add_todo(description: str, project: str, priority: str = "Medium", target_agent: str = "user", metadata: Optional[Dict[str, Any]] = None):
72
+ """Creates a task in the specified project with the given priority and target agent."""
73
+ ctx = Context(user=None)
74
+ return await tools.add_todo(description, project, priority, target_agent, metadata, ctx)
75
+
76
+ if "query_todos" in selected_tools:
77
+ @mcp.tool()
78
+ async def query_todos(filter: Optional[Dict[str, Any]] = None, projection: Optional[Dict[str, Any]] = None, limit: int = 100):
79
+ """Query todos with flexible filtering options from user's database."""
80
+ ctx = Context(user=None)
81
+ return await tools.query_todos(filter, projection, limit, ctx)
82
+
83
+ if "get_todo" in selected_tools:
84
+ @mcp.tool()
85
+ async def get_todo(todo_id: str):
86
+ """Get a specific todo item by its ID."""
87
+ ctx = Context(user=None)
88
+ return await tools.get_todo(todo_id, ctx)
89
+
90
+ if "mark_todo_complete" in selected_tools:
91
+ @mcp.tool()
92
+ async def mark_todo_complete(todo_id: str, comment: Optional[str] = None):
93
+ """Mark a todo as completed."""
94
+ ctx = Context(user=None)
95
+ return await tools.mark_todo_complete(todo_id, comment, ctx)
96
+
97
+ logger.info(f"Registered {len([t for t in selected_tools if t in ['add_todo', 'query_todos', 'get_todo', 'mark_todo_complete']])} tools for HTTP transport")
98
+
99
+ # The mcp instance is now ready for fastmcp run command
@@ -0,0 +1,407 @@
1
+ """
2
+ Hybrid tools module that can switch between API and local database modes.
3
+ Provides graceful degradation and performance comparison capabilities.
4
+ """
5
+ import os
6
+ import asyncio
7
+ import logging
8
+ from typing import Dict, Any, Optional, Union, List
9
+ from enum import Enum
10
+ from datetime import datetime, timezone
11
+
12
+ from .context import Context
13
+ from .utils import create_response
14
+ from . import tools as local_tools
15
+ from . import api_tools
16
+ from .api_client import MadnessAPIClient
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ class OmnispindleMode(Enum):
21
+ """Available operation modes for Omnispindle"""
22
+ LOCAL = "local" # Direct MongoDB access
23
+ API = "api" # HTTP API calls only
24
+ HYBRID = "hybrid" # Try API first, fallback to local
25
+ AUTO = "auto" # Automatically choose best mode
26
+
27
+ class HybridConfig:
28
+ """Configuration for hybrid mode operations"""
29
+
30
+ def __init__(self):
31
+ self.mode = self._get_mode_from_env()
32
+ self.api_timeout = float(os.getenv("OMNISPINDLE_API_TIMEOUT", "10.0"))
33
+ self.fallback_enabled = os.getenv("OMNISPINDLE_FALLBACK_ENABLED", "true").lower() == "true"
34
+ self.performance_logging = os.getenv("OMNISPINDLE_PERFORMANCE_LOGGING", "false").lower() == "true"
35
+
36
+ # Performance thresholds
37
+ self.api_failure_threshold = int(os.getenv("OMNISPINDLE_API_FAILURE_THRESHOLD", "3"))
38
+ self.api_timeout_threshold = float(os.getenv("OMNISPINDLE_API_TIMEOUT_THRESHOLD", "5.0"))
39
+
40
+ # Performance tracking
41
+ self.api_failures = 0
42
+ self.local_failures = 0
43
+ self.api_response_times = []
44
+ self.local_response_times = []
45
+
46
+ def _get_mode_from_env(self) -> OmnispindleMode:
47
+ """Get operation mode from environment variable"""
48
+ mode_str = os.getenv("OMNISPINDLE_MODE", "hybrid").lower()
49
+ try:
50
+ return OmnispindleMode(mode_str)
51
+ except ValueError:
52
+ logger.warning(f"Invalid OMNISPINDLE_MODE '{mode_str}', defaulting to hybrid")
53
+ return OmnispindleMode.HYBRID
54
+
55
+ def should_use_api(self) -> bool:
56
+ """Determine if API should be used based on current state"""
57
+ if self.mode == OmnispindleMode.LOCAL:
58
+ return False
59
+ elif self.mode == OmnispindleMode.API:
60
+ return True
61
+ elif self.mode in [OmnispindleMode.HYBRID, OmnispindleMode.AUTO]:
62
+ # Use API unless it's consistently failing
63
+ return self.api_failures < self.api_failure_threshold
64
+ return True
65
+
66
+ def record_api_success(self, response_time: float):
67
+ """Record successful API operation"""
68
+ self.api_failures = 0 # Reset failure count on success
69
+ if self.performance_logging:
70
+ self.api_response_times.append(response_time)
71
+ # Keep only recent measurements
72
+ if len(self.api_response_times) > 100:
73
+ self.api_response_times = self.api_response_times[-50:]
74
+
75
+ def record_api_failure(self):
76
+ """Record failed API operation"""
77
+ self.api_failures += 1
78
+ logger.warning(f"API failure count: {self.api_failures}/{self.api_failure_threshold}")
79
+
80
+ def record_local_success(self, response_time: float):
81
+ """Record successful local operation"""
82
+ self.local_failures = 0
83
+ if self.performance_logging:
84
+ self.local_response_times.append(response_time)
85
+ if len(self.local_response_times) > 100:
86
+ self.local_response_times = self.local_response_times[-50:]
87
+
88
+ def record_local_failure(self):
89
+ """Record failed local operation"""
90
+ self.local_failures += 1
91
+ logger.warning(f"Local failure count: {self.local_failures}")
92
+
93
+ def get_performance_stats(self) -> Dict[str, Any]:
94
+ """Get performance statistics"""
95
+ stats = {
96
+ "mode": self.mode.value,
97
+ "api_failures": self.api_failures,
98
+ "local_failures": self.local_failures,
99
+ "should_use_api": self.should_use_api()
100
+ }
101
+
102
+ if self.api_response_times:
103
+ stats["api_avg_response_time"] = sum(self.api_response_times) / len(self.api_response_times)
104
+ stats["api_recent_calls"] = len(self.api_response_times)
105
+
106
+ if self.local_response_times:
107
+ stats["local_avg_response_time"] = sum(self.local_response_times) / len(self.local_response_times)
108
+ stats["local_recent_calls"] = len(self.local_response_times)
109
+
110
+ return stats
111
+
112
+ # Global configuration instance
113
+ _hybrid_config = HybridConfig()
114
+
115
+ def get_hybrid_config() -> HybridConfig:
116
+ """Get the global hybrid configuration"""
117
+ return _hybrid_config
118
+
119
+ async def _execute_with_fallback(operation_name: str, api_func, local_func, *args, ctx: Optional[Context] = None, **kwargs):
120
+ """
121
+ Execute a function with hybrid mode support - API first, fallback to local if needed.
122
+ """
123
+ config = get_hybrid_config()
124
+
125
+ # Record start time for performance tracking
126
+ start_time = datetime.now(timezone.utc)
127
+
128
+ # Determine primary and fallback methods
129
+ use_api_first = config.should_use_api()
130
+
131
+ if use_api_first:
132
+ primary_func = api_func
133
+ fallback_func = local_func
134
+ primary_name = "API"
135
+ fallback_name = "Local"
136
+ else:
137
+ primary_func = local_func
138
+ fallback_func = api_func
139
+ primary_name = "Local"
140
+ fallback_name = "API"
141
+
142
+ # Try primary method
143
+ try:
144
+ logger.debug(f"Executing {operation_name} via {primary_name}")
145
+ result = await primary_func(*args, ctx=ctx, **kwargs)
146
+
147
+ # Record success
148
+ response_time = (datetime.now(timezone.utc) - start_time).total_seconds()
149
+ if use_api_first:
150
+ config.record_api_success(response_time)
151
+ else:
152
+ config.record_local_success(response_time)
153
+
154
+ # Check if result indicates failure
155
+ if isinstance(result, str) and '"success": false' in result:
156
+ raise Exception(f"{primary_name} returned failure response")
157
+
158
+ logger.debug(f"{operation_name} succeeded via {primary_name} in {response_time:.2f}s")
159
+ return result
160
+
161
+ except Exception as primary_error:
162
+ logger.warning(f"{operation_name} failed via {primary_name}: {str(primary_error)}")
163
+
164
+ # Record failure
165
+ if use_api_first:
166
+ config.record_api_failure()
167
+ else:
168
+ config.record_local_failure()
169
+
170
+ # Try fallback if enabled and in hybrid/auto mode
171
+ if config.fallback_enabled and config.mode in [OmnispindleMode.HYBRID, OmnispindleMode.AUTO]:
172
+ try:
173
+ logger.info(f"Falling back to {fallback_name} for {operation_name}")
174
+ fallback_start = datetime.now(timezone.utc)
175
+
176
+ result = await fallback_func(*args, ctx=ctx, **kwargs)
177
+
178
+ # Record fallback success
179
+ response_time = (datetime.now(timezone.utc) - fallback_start).total_seconds()
180
+ if not use_api_first:
181
+ config.record_api_success(response_time)
182
+ else:
183
+ config.record_local_success(response_time)
184
+
185
+ logger.info(f"{operation_name} succeeded via {fallback_name} fallback in {response_time:.2f}s")
186
+ return result
187
+
188
+ except Exception as fallback_error:
189
+ logger.error(f"{operation_name} failed via both {primary_name} and {fallback_name}")
190
+ logger.error(f"Primary error: {str(primary_error)}")
191
+ logger.error(f"Fallback error: {str(fallback_error)}")
192
+
193
+ # Record fallback failure
194
+ if not use_api_first:
195
+ config.record_api_failure()
196
+ else:
197
+ config.record_local_failure()
198
+
199
+ return create_response(False, message=f"Both {primary_name} and {fallback_name} failed. Primary: {str(primary_error)}, Fallback: {str(fallback_error)}")
200
+ else:
201
+ # No fallback, return primary error
202
+ return create_response(False, message=f"{primary_name} failed: {str(primary_error)}")
203
+
204
+ # Hybrid tool implementations
205
+
206
+ async def add_todo(description: str, project: str, priority: str = "Medium",
207
+ target_agent: str = "user", metadata: Optional[Dict[str, Any]] = None,
208
+ ctx: Optional[Context] = None) -> str:
209
+ """Create a todo using hybrid mode"""
210
+ return await _execute_with_fallback(
211
+ "add_todo",
212
+ api_tools.add_todo,
213
+ local_tools.add_todo,
214
+ description, project, priority, target_agent, metadata,
215
+ ctx=ctx
216
+ )
217
+
218
+ async def query_todos(filter: Optional[Dict[str, Any]] = None, projection: Optional[Dict[str, Any]] = None,
219
+ limit: int = 100, ctx: Optional[Context] = None) -> str:
220
+ """Query todos using hybrid mode"""
221
+ return await _execute_with_fallback(
222
+ "query_todos",
223
+ api_tools.query_todos,
224
+ local_tools.query_todos,
225
+ filter, projection, limit,
226
+ ctx=ctx
227
+ )
228
+
229
+ async def update_todo(todo_id: str, updates: dict, ctx: Optional[Context] = None) -> str:
230
+ """Update todo using hybrid mode"""
231
+ return await _execute_with_fallback(
232
+ "update_todo",
233
+ api_tools.update_todo,
234
+ local_tools.update_todo,
235
+ todo_id, updates,
236
+ ctx=ctx
237
+ )
238
+
239
+ async def delete_todo(todo_id: str, ctx: Optional[Context] = None) -> str:
240
+ """Delete todo using hybrid mode"""
241
+ return await _execute_with_fallback(
242
+ "delete_todo",
243
+ api_tools.delete_todo,
244
+ local_tools.delete_todo,
245
+ todo_id,
246
+ ctx=ctx
247
+ )
248
+
249
+ async def get_todo(todo_id: str, ctx: Optional[Context] = None) -> str:
250
+ """Get todo using hybrid mode"""
251
+ return await _execute_with_fallback(
252
+ "get_todo",
253
+ api_tools.get_todo,
254
+ local_tools.get_todo,
255
+ todo_id,
256
+ ctx=ctx
257
+ )
258
+
259
+ async def mark_todo_complete(todo_id: str, comment: Optional[str] = None, ctx: Optional[Context] = None) -> str:
260
+ """Complete todo using hybrid mode"""
261
+ return await _execute_with_fallback(
262
+ "mark_todo_complete",
263
+ api_tools.mark_todo_complete,
264
+ local_tools.mark_todo_complete,
265
+ todo_id, comment,
266
+ ctx=ctx
267
+ )
268
+
269
+ async def list_todos_by_status(status: str, limit: int = 100, ctx: Optional[Context] = None) -> str:
270
+ """List todos by status using hybrid mode"""
271
+ return await _execute_with_fallback(
272
+ "list_todos_by_status",
273
+ api_tools.list_todos_by_status,
274
+ local_tools.list_todos_by_status,
275
+ status, limit,
276
+ ctx=ctx
277
+ )
278
+
279
+ async def search_todos(query: str, fields: Optional[list] = None, limit: int = 100, ctx: Optional[Context] = None) -> str:
280
+ """Search todos using hybrid mode"""
281
+ return await _execute_with_fallback(
282
+ "search_todos",
283
+ api_tools.search_todos,
284
+ local_tools.search_todos,
285
+ query, fields, limit,
286
+ ctx=ctx
287
+ )
288
+
289
+ async def list_project_todos(project: str, limit: int = 5, ctx: Optional[Context] = None) -> str:
290
+ """List project todos using hybrid mode"""
291
+ return await _execute_with_fallback(
292
+ "list_project_todos",
293
+ api_tools.list_project_todos,
294
+ local_tools.list_project_todos,
295
+ project, limit,
296
+ ctx=ctx
297
+ )
298
+
299
+ async def list_projects(include_details: Union[bool, str] = False, madness_root: str = "/Users/d.edens/lab/madness_interactive", ctx: Optional[Context] = None) -> str:
300
+ """List projects using hybrid mode"""
301
+ return await _execute_with_fallback(
302
+ "list_projects",
303
+ api_tools.list_projects,
304
+ local_tools.list_projects,
305
+ include_details, madness_root,
306
+ ctx=ctx
307
+ )
308
+
309
+ # For non-todo operations, prefer local mode since they're not yet available via API
310
+
311
+ async def add_lesson(language: str, topic: str, lesson_learned: str, tags: Optional[list] = None, ctx: Optional[Context] = None) -> str:
312
+ """Add lesson - local only for now"""
313
+ return await local_tools.add_lesson(language, topic, lesson_learned, tags, ctx=ctx)
314
+
315
+ async def get_lesson(lesson_id: str, ctx: Optional[Context] = None) -> str:
316
+ """Get lesson - local only for now"""
317
+ return await local_tools.get_lesson(lesson_id, ctx=ctx)
318
+
319
+ async def update_lesson(lesson_id: str, updates: dict, ctx: Optional[Context] = None) -> str:
320
+ """Update lesson - local only for now"""
321
+ return await local_tools.update_lesson(lesson_id, updates, ctx=ctx)
322
+
323
+ async def delete_lesson(lesson_id: str, ctx: Optional[Context] = None) -> str:
324
+ """Delete lesson - local only for now"""
325
+ return await local_tools.delete_lesson(lesson_id, ctx=ctx)
326
+
327
+ async def search_lessons(query: str, fields: Optional[list] = None, limit: int = 100, brief: bool = False, ctx: Optional[Context] = None) -> str:
328
+ """Search lessons - local only for now"""
329
+ return await local_tools.search_lessons(query, fields, limit, brief, ctx=ctx)
330
+
331
+ async def grep_lessons(pattern: str, limit: int = 20, ctx: Optional[Context] = None) -> str:
332
+ """Grep lessons - local only for now"""
333
+ return await local_tools.grep_lessons(pattern, limit, ctx=ctx)
334
+
335
+ async def list_lessons(limit: int = 100, brief: bool = False, ctx: Optional[Context] = None) -> str:
336
+ """List lessons - local only for now"""
337
+ return await local_tools.list_lessons(limit, brief, ctx=ctx)
338
+
339
+ async def query_todo_logs(filter_type: str = 'all', project: str = 'all',
340
+ page: int = 1, page_size: int = 20, ctx: Optional[Context] = None) -> str:
341
+ """Query todo logs - local only for now"""
342
+ return await local_tools.query_todo_logs(filter_type, project, page, page_size, ctx=ctx)
343
+
344
+ async def add_explanation(topic: str, content: str, kind: str = "concept", author: str = "system", ctx: Optional[Context] = None) -> str:
345
+ """Add explanation - local only for now"""
346
+ return await local_tools.add_explanation(topic, content, kind, author, ctx=ctx)
347
+
348
+ async def explain_tool(topic: str, brief: bool = False, ctx: Optional[Context] = None) -> str:
349
+ """Explain tool - local only for now"""
350
+ return await local_tools.explain_tool(topic, brief, ctx=ctx)
351
+
352
+ async def point_out_obvious(observation: str, sarcasm_level: int = 5, ctx: Optional[Context] = None) -> str:
353
+ """Point out obvious - local only for now"""
354
+ return await local_tools.point_out_obvious(observation, sarcasm_level, ctx=ctx)
355
+
356
+ async def bring_your_own(tool_name: str, code: str, runtime: str = "python",
357
+ timeout: int = 30, args: Optional[Dict[str, Any]] = None,
358
+ persist: bool = False, ctx: Optional[Context] = None) -> str:
359
+ """Bring your own tool - local only for now"""
360
+ return await local_tools.bring_your_own(tool_name, code, runtime, timeout, args, persist, ctx=ctx)
361
+
362
+ # Utility functions for monitoring and configuration
363
+
364
+ async def get_hybrid_status(ctx: Optional[Context] = None) -> str:
365
+ """Get current hybrid mode status and performance stats"""
366
+ config = get_hybrid_config()
367
+ stats = config.get_performance_stats()
368
+
369
+ return create_response(True, {
370
+ "hybrid_status": stats,
371
+ "configuration": {
372
+ "mode": config.mode.value,
373
+ "api_timeout": config.api_timeout,
374
+ "fallback_enabled": config.fallback_enabled,
375
+ "performance_logging": config.performance_logging,
376
+ "api_failure_threshold": config.api_failure_threshold
377
+ }
378
+ }, message=f"Hybrid mode: {config.mode.value}, API preferred: {config.should_use_api()}")
379
+
380
+ async def test_api_connectivity(ctx: Optional[Context] = None) -> str:
381
+ """Test API connectivity and response times"""
382
+ try:
383
+ auth_token, api_key = api_tools._get_auth_from_context(ctx)
384
+
385
+ start_time = datetime.now(timezone.utc)
386
+ async with MadnessAPIClient(auth_token=auth_token, api_key=api_key) as client:
387
+ health_response = await client.health_check()
388
+ response_time = (datetime.now(timezone.utc) - start_time).total_seconds()
389
+
390
+ if health_response.success:
391
+ return create_response(True, {
392
+ "api_status": "healthy",
393
+ "response_time": response_time,
394
+ "api_data": health_response.data
395
+ }, message=f"API connectivity OK ({response_time:.2f}s)")
396
+ else:
397
+ return create_response(False, {
398
+ "api_status": "unhealthy",
399
+ "response_time": response_time,
400
+ "error": health_response.error
401
+ }, message=f"API connectivity failed: {health_response.error}")
402
+
403
+ except Exception as e:
404
+ return create_response(False, {
405
+ "api_status": "error",
406
+ "error": str(e)
407
+ }, message=f"API connectivity test failed: {str(e)}")