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.
@@ -0,0 +1,187 @@
1
+ import asyncio
2
+ import inspect
3
+ import logging
4
+ import os
5
+ from typing import Callable, Dict, Any, Optional, Union, List
6
+ import json
7
+
8
+ from dotenv import load_dotenv
9
+ from fastapi import FastAPI, Depends, Request, HTTPException, Response, status
10
+
11
+ from .auth import get_current_user
12
+ from .context import Context
13
+ from .middleware import ConnectionErrorsMiddleware, NoneTypeResponseMiddleware, EnhancedLoggingMiddleware
14
+ from .patches import apply_patches
15
+ from . import tools
16
+ from . import hybrid_tools
17
+ from .hybrid_tools import OmnispindleMode
18
+
19
+ # --- Initializations ---
20
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
21
+ logger = logging.getLogger(__name__)
22
+ apply_patches()
23
+ load_dotenv()
24
+
25
+ # Tool loadout configurations
26
+ TOOL_LOADOUTS = {
27
+ "full": [
28
+ "add_todo", "query_todos", "update_todo", "delete_todo", "get_todo",
29
+ "mark_todo_complete", "list_todos_by_status", "search_todos", "list_project_todos",
30
+ "add_lesson", "get_lesson", "update_lesson", "delete_lesson", "search_lessons",
31
+ "grep_lessons", "list_lessons", "query_todo_logs", "list_projects",
32
+ "explain", "add_explanation", "point_out_obvious", "bring_your_own"
33
+ ],
34
+ "basic": [
35
+ "add_todo", "query_todos", "update_todo", "get_todo", "mark_todo_complete",
36
+ "list_todos_by_status", "list_project_todos"
37
+ ],
38
+ "minimal": [
39
+ "add_todo", "query_todos", "get_todo", "mark_todo_complete"
40
+ ],
41
+ "lessons": [
42
+ "add_lesson", "get_lesson", "update_lesson", "delete_lesson", "search_lessons",
43
+ "grep_lessons", "list_lessons"
44
+ ],
45
+ "admin": [
46
+ "query_todos", "update_todo", "delete_todo", "query_todo_logs",
47
+ "list_projects", "explain", "add_explanation"
48
+ ],
49
+ "hybrid_test": [
50
+ "add_todo", "query_todos", "get_todo", "mark_todo_complete",
51
+ "get_hybrid_status", "test_api_connectivity"
52
+ ]
53
+ }
54
+
55
+
56
+ class Omnispindle:
57
+ """Main Omnispindle server class for FastAPI."""
58
+
59
+ def __init__(self):
60
+ self.tools: Dict[str, Callable] = {}
61
+ logger.info("Omnispindle server class initialized.")
62
+
63
+ def tool(self, name: Optional[str] = None) -> Callable:
64
+ """A decorator to register a function as a tool."""
65
+ def decorator(func: Callable) -> Callable:
66
+ tool_name = name or func.__name__
67
+ self.tools[tool_name] = func
68
+ logger.info(f"Tool '{tool_name}' registered.")
69
+ return func
70
+ return decorator
71
+
72
+ async def dispatch_tool(self, tool_name: str, params: Dict[str, Any], ctx: Context) -> Any:
73
+ """Finds and executes the tool with the given name."""
74
+ if tool_name not in self.tools:
75
+ raise HTTPException(status_code=404, detail=f"Tool '{tool_name}' not found.")
76
+
77
+ tool_func = self.tools[tool_name]
78
+
79
+ # Add ctx to the params if the tool's signature includes it.
80
+ sig = inspect.signature(tool_func)
81
+ if 'ctx' in sig.parameters:
82
+ params['ctx'] = ctx
83
+
84
+ return await tool_func(**params)
85
+
86
+ async def run_server(self) -> FastAPI:
87
+ """Creates and configures the FastAPI application."""
88
+ app = FastAPI(
89
+ title="Omnispindle",
90
+ description="A FastAPI server for managing todos and other tasks, with AI agent integration.",
91
+ version="0.1.0",
92
+ )
93
+
94
+ app.add_middleware(ConnectionErrorsMiddleware)
95
+ app.add_middleware(NoneTypeResponseMiddleware)
96
+ app.add_middleware(EnhancedLoggingMiddleware, logger=logger)
97
+
98
+ @app.get("/auth/logout", tags=["auth"])
99
+ async def logout(response: Response):
100
+ response.delete_cookie(key="ss-tok", httponly=True, samesite="strict", secure=True)
101
+ return {"message": "Successfully logged out."}
102
+
103
+ @app.post("/tools/{tool_name}", tags=["tools"])
104
+ async def run_tool(tool_name: str, request: Request, user: dict = Depends(get_current_user)):
105
+ try:
106
+ params = await request.json()
107
+ except Exception:
108
+ params = {}
109
+
110
+ ctx = Context(user=user)
111
+ result = await self.dispatch_tool(tool_name, params, ctx)
112
+ return {"result": str(result) if not isinstance(result, (dict, list, str, int, float, bool, type(None))) else result}
113
+
114
+
115
+ @app.get("/")
116
+ def read_root():
117
+ return {"message": "Omnispindle is running."}
118
+
119
+ self._register_default_tools()
120
+ return app
121
+
122
+ def _register_default_tools(self):
123
+ """Registers tools based on OMNISPINDLE_TOOL_LOADOUT and OMNISPINDLE_MODE env vars."""
124
+
125
+ loadout = os.getenv("OMNISPINDLE_TOOL_LOADOUT", "full").lower()
126
+ if loadout not in TOOL_LOADOUTS:
127
+ logger.warning(f"Unknown loadout '{loadout}', using 'full'")
128
+ loadout = "full"
129
+
130
+ # Determine which tools module to use based on mode
131
+ mode = os.getenv("OMNISPINDLE_MODE", "hybrid").lower()
132
+ if mode in ["hybrid", "api", "auto"]:
133
+ tools_module = hybrid_tools
134
+ logger.info(f"Using hybrid/API tools module in '{mode}' mode")
135
+ else:
136
+ tools_module = tools
137
+ logger.info(f"Using local tools module in '{mode}' mode")
138
+
139
+ enabled = TOOL_LOADOUTS[loadout]
140
+ logger.info(f"Loading '{loadout}' loadout: {enabled}")
141
+
142
+ # Tool registry - keeps AI docstrings minimal
143
+ tool_registry = {
144
+ "add_todo": (tools_module.add_todo, "Creates a task in the specified project with the given priority and target agent. Returns a compact representation of the created todo with an ID for reference."),
145
+ "query_todos": (tools_module.query_todos, "Query todos with flexible filtering options. Searches the todo database using MongoDB-style query filters and projections."),
146
+ "update_todo": (tools_module.update_todo, "Update a todo with the provided changes. Common fields to update: description, priority, status, metadata."),
147
+ "delete_todo": (tools_module.delete_todo, "Delete a todo by its ID."),
148
+ "get_todo": (tools_module.get_todo, "Get a specific todo by ID."),
149
+ "mark_todo_complete": (tools_module.mark_todo_complete, "Mark a todo as completed. Calculates the duration from creation to completion."),
150
+ "list_todos_by_status": (tools_module.list_todos_by_status, "List todos filtered by status ('initial', 'pending', 'completed'). Results are formatted for efficiency with truncated descriptions."),
151
+ "search_todos": (tools_module.search_todos, "Search todos with text search capabilities across specified fields. Special format: \"project:ProjectName\" to search by project."),
152
+ "list_project_todos": (tools_module.list_project_todos, "List recent active todos for a specific project."),
153
+ "add_lesson": (tools_module.add_lesson, "Add a new lesson learned to the knowledge base."),
154
+ "get_lesson": (tools_module.get_lesson, "Get a specific lesson by ID."),
155
+ "update_lesson": (tools_module.update_lesson, "Update an existing lesson by ID."),
156
+ "delete_lesson": (tools_module.delete_lesson, "Delete a lesson by ID."),
157
+ "search_lessons": (tools_module.search_lessons, "Search lessons with text search capabilities."),
158
+ "grep_lessons": (tools_module.grep_lessons, "Search lessons with grep-style pattern matching across topic and content."),
159
+ "list_lessons": (tools_module.list_lessons, "List all lessons, sorted by creation date."),
160
+ "query_todo_logs": (tools_module.query_todo_logs, "Query todo logs with filtering options."),
161
+ "list_projects": (tools_module.list_projects, "List all valid projects from the centralized project management system. `include_details`: False (names only), True (full metadata), \"filemanager\" (for UI)."),
162
+ "explain": (tools_module.explain_tool, "Provides a detailed explanation for a project or concept. For projects, it dynamically generates a summary with recent activity."),
163
+ "add_explanation": (tools_module.add_explanation, "Add a new static explanation to the knowledge base."),
164
+ "point_out_obvious": (tools_module.point_out_obvious, "Points out something obvious to the human user with humor."),
165
+ "bring_your_own": (tools_module.bring_your_own, "Temporarily hijack the MCP server to run custom tool code."),
166
+ # Hybrid-specific tools
167
+ "get_hybrid_status": (hybrid_tools.get_hybrid_status, "Get current hybrid mode status and performance statistics."),
168
+ "test_api_connectivity": (hybrid_tools.test_api_connectivity, "Test API connectivity and response times.")
169
+ }
170
+
171
+ # Register enabled tools
172
+ for tool_name in enabled:
173
+ if tool_name in tool_registry:
174
+ func, doc = tool_registry[tool_name]
175
+
176
+ # Create closure to capture func properly
177
+ def make_wrapper(f, docstring):
178
+ async def wrapper(*args, ctx: Optional[Context] = None, **kwargs):
179
+ return await f(*args, ctx=ctx, **kwargs)
180
+ wrapper.__doc__ = docstring
181
+ return wrapper
182
+
183
+ self.tool(tool_name)(make_wrapper(func, doc))
184
+
185
+ # --- Server Instantiation ---
186
+ server = Omnispindle()
187
+ app = asyncio.run(server.run_server())
@@ -0,0 +1,121 @@
1
+ import asyncio
2
+ import logging
3
+ import os
4
+ import uvicorn
5
+ from .server import Omnispindle
6
+
7
+ import sys
8
+ import shutil
9
+ import subprocess
10
+ import argparse
11
+
12
+ # Configure logging
13
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
14
+ logger = logging.getLogger(__name__)
15
+
16
+ MOSQUITTO_PUB_AVAILABLE = shutil.which("mosquitto_pub") is not None
17
+
18
+ def main():
19
+ """Main CLI entry point with subcommands."""
20
+ parser = argparse.ArgumentParser(
21
+ description="Omnispindle MCP Server Management",
22
+ prog="python -m src.Omnispindle"
23
+ )
24
+
25
+ subparsers = parser.add_subparsers(dest="command", help="Available commands")
26
+
27
+ # Auth command
28
+ auth_parser = subparsers.add_parser("auth", help="Authentication setup")
29
+ auth_parser.add_argument("--setup", action="store_true", help="Run Auth0 setup flow")
30
+ auth_parser.add_argument("--no-save", action="store_true", help="Don't save config file")
31
+ auth_parser.add_argument("--output", "-o", help="Output path for config file")
32
+
33
+ # Server command (default behavior)
34
+ server_parser = subparsers.add_parser("server", help="Run the web server (default)")
35
+
36
+ # Parse arguments
37
+ args = parser.parse_args()
38
+
39
+ if args.command == "auth":
40
+ if args.setup:
41
+ asyncio.run(run_auth_setup(args))
42
+ else:
43
+ auth_parser.print_help()
44
+ return
45
+
46
+ # Default behavior or explicit server command - run the web server
47
+ run_web_server()
48
+
49
+
50
+ def run_auth_setup(args):
51
+ """Run the Auth0 setup flow."""
52
+ async def setup():
53
+ try:
54
+ from .auth_setup import Auth0CLISetup
55
+
56
+ setup_handler = Auth0CLISetup()
57
+ result = await setup_handler.run_setup(save_config=not args.no_save)
58
+
59
+ if args.output and not args.no_save:
60
+ setup_handler.save_config(result["mcp_config"], args.output)
61
+ print(f"šŸ’¾ Config also saved to: {args.output}")
62
+
63
+ except ImportError as e:
64
+ print(f"āŒ Auth setup requires additional dependencies: {e}")
65
+ print("šŸ’” Try: pip install requests")
66
+ except KeyboardInterrupt:
67
+ print("\nāŒ Setup cancelled by user")
68
+ except Exception as e:
69
+ print(f"āŒ Setup failed: {e}")
70
+ sys.exit(1)
71
+
72
+ return setup()
73
+
74
+
75
+ def run_web_server():
76
+ """Run the web server (original main functionality)."""
77
+ logger.info("Omnispindle beginning spin")
78
+
79
+ # Print a warning if mosquitto_pub is not available
80
+ if not MOSQUITTO_PUB_AVAILABLE:
81
+ print("WARNING: mosquitto_pub command not found. MQTT status publishing will be disabled.")
82
+ print(" To enable MQTT status publishing, install the Mosquitto clients package:")
83
+ print(" Ubuntu/Debian: sudo apt install mosquitto-clients")
84
+ print(" macOS: brew install mosquitto")
85
+ print(" Windows: Download from https://mosquitto.org/download/")
86
+
87
+ try:
88
+ # Get host and port from environment variables with proper defaults for containerization
89
+ # Force host to 0.0.0.0 for Docker compatibility - overriding any existing variables
90
+ host = "0.0.0.0" # Force binding to all interfaces
91
+ port = int(os.getenv("PORT", 8000))
92
+
93
+ # Print binding information for debugging
94
+ logger.info(f"Starting Uvicorn server on {host}:{port}")
95
+
96
+ # Ensure we use asyncio to start the server
97
+ loop = asyncio.new_event_loop()
98
+ asyncio.set_event_loop(loop)
99
+
100
+ # Get the ASGI app by running the server in the event loop
101
+ server = Omnispindle()
102
+ app = loop.run_until_complete(server.run_server())
103
+
104
+ # Run Uvicorn with the ASGI app
105
+ uvicorn.run(
106
+ app,
107
+ host=host,
108
+ port=port,
109
+ log_level="info",
110
+ proxy_headers=True, # Important for proper header handling in Docker
111
+ forwarded_allow_ips="*", # Accept X-Forwarded-* headers from any IP
112
+ interface="asgi3" # Force use of the newer ASGI interface
113
+ )
114
+ except Exception as e:
115
+ logger.exception(f"Error starting Omnispindle: {str(e)}")
116
+ raise
117
+ finally:
118
+ loop.close()
119
+
120
+ if __name__ == "__main__":
121
+ main()