comet-mcp 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.
- comet_mcp/__init__.py +0 -0
- comet_mcp/cache.py +257 -0
- comet_mcp/server.py +207 -0
- comet_mcp/session.py +73 -0
- comet_mcp/tool_loader.py +38 -0
- comet_mcp/tools.py +797 -0
- comet_mcp/utils.py +247 -0
- comet_mcp-1.0.0.dist-info/METADATA +480 -0
- comet_mcp-1.0.0.dist-info/RECORD +13 -0
- comet_mcp-1.0.0.dist-info/WHEEL +5 -0
- comet_mcp-1.0.0.dist-info/entry_points.txt +2 -0
- comet_mcp-1.0.0.dist-info/licenses/LICENSE +203 -0
- comet_mcp-1.0.0.dist-info/top_level.txt +1 -0
comet_mcp/__init__.py
ADDED
|
File without changes
|
comet_mcp/cache.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Session-aware caching system for Comet ML MCP server.
|
|
4
|
+
Provides caching decorators that respect different sessions and allow cache invalidation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import time
|
|
10
|
+
from functools import wraps
|
|
11
|
+
from typing import Any, Callable, Dict, Optional, Union
|
|
12
|
+
from datetime import datetime, timedelta
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CacheEntry:
|
|
16
|
+
"""Represents a cached value with metadata."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, value: Any, created_at: datetime, ttl_seconds: Optional[int] = None):
|
|
19
|
+
self.value = value
|
|
20
|
+
self.created_at = created_at
|
|
21
|
+
self.ttl_seconds = ttl_seconds
|
|
22
|
+
|
|
23
|
+
def is_expired(self) -> bool:
|
|
24
|
+
"""Check if the cache entry has expired."""
|
|
25
|
+
if self.ttl_seconds is None:
|
|
26
|
+
return False
|
|
27
|
+
return datetime.now() - self.created_at > timedelta(seconds=self.ttl_seconds)
|
|
28
|
+
|
|
29
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
30
|
+
"""Convert to dictionary for serialization."""
|
|
31
|
+
return {
|
|
32
|
+
'value': self.value,
|
|
33
|
+
'created_at': self.created_at.isoformat(),
|
|
34
|
+
'ttl_seconds': self.ttl_seconds
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def from_dict(cls, data: Dict[str, Any]) -> 'CacheEntry':
|
|
39
|
+
"""Create from dictionary."""
|
|
40
|
+
return cls(
|
|
41
|
+
value=data['value'],
|
|
42
|
+
created_at=datetime.fromisoformat(data['created_at']),
|
|
43
|
+
ttl_seconds=data.get('ttl_seconds')
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SessionCache:
|
|
48
|
+
"""Session-aware cache that maintains separate caches per session."""
|
|
49
|
+
|
|
50
|
+
def __init__(self):
|
|
51
|
+
self._caches: Dict[str, Dict[str, CacheEntry]] = {}
|
|
52
|
+
self._session_metadata: Dict[str, Dict[str, Any]] = {}
|
|
53
|
+
|
|
54
|
+
def _get_session_id(self) -> str:
|
|
55
|
+
"""Get the current session ID."""
|
|
56
|
+
from .session import get_session_context
|
|
57
|
+
session_context = get_session_context()
|
|
58
|
+
|
|
59
|
+
# Create a unique session ID based on the API instance
|
|
60
|
+
if session_context.is_initialized():
|
|
61
|
+
# Use the API instance's identity as session ID
|
|
62
|
+
api = session_context.api
|
|
63
|
+
session_id = f"session_{id(api)}_{hash(str(api))}"
|
|
64
|
+
else:
|
|
65
|
+
# Fallback to a default session
|
|
66
|
+
session_id = "default_session"
|
|
67
|
+
|
|
68
|
+
return session_id
|
|
69
|
+
|
|
70
|
+
def _generate_cache_key(self, func_name: str, args: tuple, kwargs: dict) -> str:
|
|
71
|
+
"""Generate a unique cache key for a function call."""
|
|
72
|
+
# Create a deterministic key from function name and arguments
|
|
73
|
+
key_data = {
|
|
74
|
+
'func': func_name,
|
|
75
|
+
'args': args,
|
|
76
|
+
'kwargs': sorted(kwargs.items()) if kwargs else {}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
# Create a hash of the key data
|
|
80
|
+
key_str = json.dumps(key_data, sort_keys=True, default=str)
|
|
81
|
+
return hashlib.md5(key_str.encode()).hexdigest()
|
|
82
|
+
|
|
83
|
+
def get(self, func_name: str, args: tuple, kwargs: dict) -> Optional[Any]:
|
|
84
|
+
"""Get a cached value for a function call."""
|
|
85
|
+
session_id = self._get_session_id()
|
|
86
|
+
cache_key = self._generate_cache_key(func_name, args, kwargs)
|
|
87
|
+
|
|
88
|
+
if session_id not in self._caches:
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
if cache_key not in self._caches[session_id]:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
entry = self._caches[session_id][cache_key]
|
|
95
|
+
|
|
96
|
+
# Check if expired
|
|
97
|
+
if entry.is_expired():
|
|
98
|
+
del self._caches[session_id][cache_key]
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
return entry.value
|
|
102
|
+
|
|
103
|
+
def set(self, func_name: str, args: tuple, kwargs: dict, value: Any, ttl_seconds: Optional[int] = None):
|
|
104
|
+
"""Set a cached value for a function call."""
|
|
105
|
+
session_id = self._get_session_id()
|
|
106
|
+
cache_key = self._generate_cache_key(func_name, args, kwargs)
|
|
107
|
+
|
|
108
|
+
if session_id not in self._caches:
|
|
109
|
+
self._caches[session_id] = {}
|
|
110
|
+
self._session_metadata[session_id] = {
|
|
111
|
+
'created_at': datetime.now(),
|
|
112
|
+
'last_accessed': datetime.now()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
entry = CacheEntry(value, datetime.now(), ttl_seconds)
|
|
116
|
+
self._caches[session_id][cache_key] = entry
|
|
117
|
+
self._session_metadata[session_id]['last_accessed'] = datetime.now()
|
|
118
|
+
|
|
119
|
+
def invalidate(self, func_name: Optional[str] = None, session_id: Optional[str] = None):
|
|
120
|
+
"""Invalidate cache entries.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
func_name: If provided, only invalidate entries for this function
|
|
124
|
+
session_id: If provided, only invalidate entries for this session
|
|
125
|
+
"""
|
|
126
|
+
if session_id:
|
|
127
|
+
# Invalidate specific session
|
|
128
|
+
if session_id in self._caches:
|
|
129
|
+
if func_name:
|
|
130
|
+
# Remove only entries for this function
|
|
131
|
+
keys_to_remove = [
|
|
132
|
+
key for key in self._caches[session_id].keys()
|
|
133
|
+
if key.startswith(f"{func_name}_")
|
|
134
|
+
]
|
|
135
|
+
for key in keys_to_remove:
|
|
136
|
+
del self._caches[session_id][key]
|
|
137
|
+
else:
|
|
138
|
+
# Remove all entries for this session
|
|
139
|
+
del self._caches[session_id]
|
|
140
|
+
del self._session_metadata[session_id]
|
|
141
|
+
else:
|
|
142
|
+
# Invalidate all sessions
|
|
143
|
+
if func_name:
|
|
144
|
+
# Remove entries for this function from all sessions
|
|
145
|
+
for session in self._caches:
|
|
146
|
+
keys_to_remove = [
|
|
147
|
+
key for key in self._caches[session].keys()
|
|
148
|
+
if key.startswith(f"{func_name}_")
|
|
149
|
+
]
|
|
150
|
+
for key in keys_to_remove:
|
|
151
|
+
del self._caches[session][key]
|
|
152
|
+
else:
|
|
153
|
+
# Clear all caches
|
|
154
|
+
self._caches.clear()
|
|
155
|
+
self._session_metadata.clear()
|
|
156
|
+
|
|
157
|
+
def get_session_info(self) -> Dict[str, Any]:
|
|
158
|
+
"""Get information about cached sessions."""
|
|
159
|
+
info = {}
|
|
160
|
+
for session_id, metadata in self._session_metadata.items():
|
|
161
|
+
cache_size = len(self._caches.get(session_id, {}))
|
|
162
|
+
info[session_id] = {
|
|
163
|
+
'created_at': metadata['created_at'].isoformat(),
|
|
164
|
+
'last_accessed': metadata['last_accessed'].isoformat(),
|
|
165
|
+
'cache_size': cache_size
|
|
166
|
+
}
|
|
167
|
+
return info
|
|
168
|
+
|
|
169
|
+
def cleanup_expired(self):
|
|
170
|
+
"""Remove expired entries from all sessions."""
|
|
171
|
+
for session_id in list(self._caches.keys()):
|
|
172
|
+
expired_keys = []
|
|
173
|
+
for key, entry in self._caches[session_id].items():
|
|
174
|
+
if entry.is_expired():
|
|
175
|
+
expired_keys.append(key)
|
|
176
|
+
|
|
177
|
+
for key in expired_keys:
|
|
178
|
+
del self._caches[session_id][key]
|
|
179
|
+
|
|
180
|
+
# Remove empty sessions
|
|
181
|
+
if not self._caches[session_id]:
|
|
182
|
+
del self._caches[session_id]
|
|
183
|
+
if session_id in self._session_metadata:
|
|
184
|
+
del self._session_metadata[session_id]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# Global cache instance
|
|
188
|
+
_cache = SessionCache()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def cached(ttl_seconds: Optional[int] = None, key_func: Optional[Callable] = None):
|
|
192
|
+
"""
|
|
193
|
+
Decorator for caching function results with session awareness.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
ttl_seconds: Time-to-live in seconds. None means no expiration.
|
|
197
|
+
key_func: Optional function to generate custom cache keys.
|
|
198
|
+
Should take (args, kwargs) and return a string.
|
|
199
|
+
|
|
200
|
+
Example:
|
|
201
|
+
@cached(ttl_seconds=300) # Cache for 5 minutes
|
|
202
|
+
def expensive_function(param1, param2):
|
|
203
|
+
# ... expensive computation
|
|
204
|
+
return result
|
|
205
|
+
"""
|
|
206
|
+
def decorator(func: Callable) -> Callable:
|
|
207
|
+
@wraps(func)
|
|
208
|
+
def wrapper(*args, **kwargs):
|
|
209
|
+
# Generate cache key
|
|
210
|
+
if key_func:
|
|
211
|
+
cache_key = key_func(args, kwargs)
|
|
212
|
+
else:
|
|
213
|
+
cache_key = _cache._generate_cache_key(func.__name__, args, kwargs)
|
|
214
|
+
|
|
215
|
+
# Try to get from cache
|
|
216
|
+
cached_result = _cache.get(func.__name__, args, kwargs)
|
|
217
|
+
if cached_result is not None:
|
|
218
|
+
return cached_result
|
|
219
|
+
|
|
220
|
+
# Execute function and cache result
|
|
221
|
+
result = func(*args, **kwargs)
|
|
222
|
+
_cache.set(func.__name__, args, kwargs, result, ttl_seconds)
|
|
223
|
+
|
|
224
|
+
return result
|
|
225
|
+
|
|
226
|
+
# Add cache management methods to the wrapper
|
|
227
|
+
wrapper.cache_invalidate = lambda: _cache.invalidate(func.__name__)
|
|
228
|
+
wrapper.cache_clear = lambda: _cache.invalidate(func.__name__)
|
|
229
|
+
|
|
230
|
+
return wrapper
|
|
231
|
+
return decorator
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def cache_invalidate(func_name: Optional[str] = None, session_id: Optional[str] = None):
|
|
235
|
+
"""Invalidate cache entries.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
func_name: Function name to invalidate (optional)
|
|
239
|
+
session_id: Session ID to invalidate (optional)
|
|
240
|
+
"""
|
|
241
|
+
_cache.invalidate(func_name, session_id)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def cache_clear():
|
|
245
|
+
"""Clear all cache entries."""
|
|
246
|
+
_cache.invalidate()
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def get_cache_info() -> Dict[str, Any]:
|
|
250
|
+
"""Get information about the current cache state."""
|
|
251
|
+
_cache.cleanup_expired()
|
|
252
|
+
return _cache.get_session_info()
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def cache_cleanup():
|
|
256
|
+
"""Clean up expired cache entries."""
|
|
257
|
+
_cache.cleanup_expired()
|
comet_mcp/server.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Simple demo MCP server for testing the multi-server client.
|
|
4
|
+
This server provides basic math operations as tools.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import asyncio
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import signal
|
|
12
|
+
import sys
|
|
13
|
+
from typing import Any, Dict, List
|
|
14
|
+
|
|
15
|
+
from mcp import Tool
|
|
16
|
+
from mcp.server import Server
|
|
17
|
+
from mcp.server.stdio import stdio_server
|
|
18
|
+
|
|
19
|
+
# Import our tools module and registry
|
|
20
|
+
from . import tool_loader # This ensures tools are registered
|
|
21
|
+
from .utils import registry
|
|
22
|
+
from .session import initialize_session
|
|
23
|
+
|
|
24
|
+
# SSE transport imports
|
|
25
|
+
from fastapi import FastAPI, Request
|
|
26
|
+
from fastapi.responses import StreamingResponse
|
|
27
|
+
import uvicorn
|
|
28
|
+
|
|
29
|
+
# Create the server
|
|
30
|
+
server = Server("comet-mcp")
|
|
31
|
+
|
|
32
|
+
# Global variable to track server state for clean shutdown
|
|
33
|
+
_server_task = None
|
|
34
|
+
|
|
35
|
+
def parse_args():
|
|
36
|
+
"""Parse command line arguments."""
|
|
37
|
+
parser = argparse.ArgumentParser(description="Comet ML MCP Server")
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"--transport",
|
|
40
|
+
choices=["stdio", "sse"],
|
|
41
|
+
default="stdio",
|
|
42
|
+
help="Transport method to use (default: stdio)",
|
|
43
|
+
)
|
|
44
|
+
parser.add_argument(
|
|
45
|
+
"--host",
|
|
46
|
+
default="localhost",
|
|
47
|
+
help="Host for SSE transport (default: localhost)",
|
|
48
|
+
)
|
|
49
|
+
parser.add_argument(
|
|
50
|
+
"--port",
|
|
51
|
+
type=int,
|
|
52
|
+
default=8000,
|
|
53
|
+
help="Port for SSE transport (default: 8000)",
|
|
54
|
+
)
|
|
55
|
+
return parser.parse_args()
|
|
56
|
+
|
|
57
|
+
@server.list_tools()
|
|
58
|
+
async def list_tools() -> List[Tool]:
|
|
59
|
+
"""List available tools."""
|
|
60
|
+
return registry.get_tools()
|
|
61
|
+
|
|
62
|
+
@server.call_tool()
|
|
63
|
+
async def call_tool(name: str, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
64
|
+
"""Handle tool calls."""
|
|
65
|
+
return registry.call_tool(name, arguments)
|
|
66
|
+
|
|
67
|
+
# SSE transport implementation
|
|
68
|
+
app = FastAPI(title="Comet ML MCP Server", version="1.0.0")
|
|
69
|
+
|
|
70
|
+
# Global variables for SSE communication
|
|
71
|
+
_sse_clients = set()
|
|
72
|
+
_message_queue = asyncio.Queue()
|
|
73
|
+
|
|
74
|
+
@app.get("/sse")
|
|
75
|
+
async def sse_endpoint():
|
|
76
|
+
"""SSE endpoint for server-to-client communication."""
|
|
77
|
+
async def event_generator():
|
|
78
|
+
# Add client to the set
|
|
79
|
+
client_id = id(asyncio.current_task())
|
|
80
|
+
_sse_clients.add(client_id)
|
|
81
|
+
print(f"š SSE client connected: {client_id}")
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
while True:
|
|
85
|
+
# Wait for messages from the message queue
|
|
86
|
+
try:
|
|
87
|
+
message = await asyncio.wait_for(_message_queue.get(), timeout=1.0)
|
|
88
|
+
yield f"data: {json.dumps(message)}\n\n"
|
|
89
|
+
except asyncio.TimeoutError:
|
|
90
|
+
# Send keepalive
|
|
91
|
+
yield f"data: {json.dumps({'type': 'keepalive'})}\n\n"
|
|
92
|
+
except asyncio.CancelledError:
|
|
93
|
+
print(f"š SSE client disconnected: {client_id}")
|
|
94
|
+
finally:
|
|
95
|
+
_sse_clients.discard(client_id)
|
|
96
|
+
|
|
97
|
+
return StreamingResponse(
|
|
98
|
+
event_generator(),
|
|
99
|
+
media_type="text/event-stream",
|
|
100
|
+
headers={
|
|
101
|
+
"Cache-Control": "no-cache",
|
|
102
|
+
"Connection": "keep-alive",
|
|
103
|
+
"Access-Control-Allow-Origin": "*",
|
|
104
|
+
"Access-Control-Allow-Headers": "Cache-Control",
|
|
105
|
+
}
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
@app.post("/messages")
|
|
109
|
+
async def message_endpoint(request: Request):
|
|
110
|
+
"""HTTP POST endpoint for client-to-server communication."""
|
|
111
|
+
try:
|
|
112
|
+
data = await request.json()
|
|
113
|
+
print(f"šØ Received message: {data}")
|
|
114
|
+
|
|
115
|
+
# Process the message through the MCP server
|
|
116
|
+
# This is a simplified implementation - in a real scenario,
|
|
117
|
+
# you'd need to properly handle MCP protocol messages
|
|
118
|
+
response = {"status": "received", "data": data}
|
|
119
|
+
|
|
120
|
+
# Send response back via SSE
|
|
121
|
+
await _message_queue.put(response)
|
|
122
|
+
|
|
123
|
+
return {"status": "success", "message": "Message processed"}
|
|
124
|
+
except Exception as e:
|
|
125
|
+
print(f"ā Error processing message: {e}")
|
|
126
|
+
return {"status": "error", "message": str(e)}
|
|
127
|
+
|
|
128
|
+
@app.get("/health")
|
|
129
|
+
async def health_check():
|
|
130
|
+
"""Health check endpoint."""
|
|
131
|
+
return {"status": "healthy", "transport": "sse"}
|
|
132
|
+
|
|
133
|
+
async def start_sse_server(host: str, port: int):
|
|
134
|
+
"""Start the SSE server."""
|
|
135
|
+
print(f"š Starting SSE server on {host}:{port}")
|
|
136
|
+
print(f"š” SSE endpoint: http://{host}:{port}/sse")
|
|
137
|
+
print(f"šØ Messages endpoint: http://{host}:{port}/messages")
|
|
138
|
+
print(f"š„ Health check: http://{host}:{port}/health")
|
|
139
|
+
|
|
140
|
+
config = uvicorn.Config(app, host=host, port=port, log_level="info")
|
|
141
|
+
server_instance = uvicorn.Server(config)
|
|
142
|
+
await server_instance.serve()
|
|
143
|
+
|
|
144
|
+
def signal_handler(signum, frame):
|
|
145
|
+
"""Handle shutdown signals gracefully."""
|
|
146
|
+
print("\nš Received shutdown signal, cleaning up...")
|
|
147
|
+
if _server_task and not _server_task.done():
|
|
148
|
+
_server_task.cancel()
|
|
149
|
+
# Force immediate exit to avoid waiting for stdin
|
|
150
|
+
os._exit(0)
|
|
151
|
+
|
|
152
|
+
async def main():
|
|
153
|
+
"""Run the server."""
|
|
154
|
+
global _server_task
|
|
155
|
+
|
|
156
|
+
# Parse command line arguments
|
|
157
|
+
args = parse_args()
|
|
158
|
+
|
|
159
|
+
print("š Comet MCP Server Starting...")
|
|
160
|
+
print(f"š Transport: {args.transport}")
|
|
161
|
+
|
|
162
|
+
# Set up signal handlers for clean shutdown
|
|
163
|
+
signal.signal(signal.SIGINT, signal_handler)
|
|
164
|
+
signal.signal(signal.SIGTERM, signal_handler)
|
|
165
|
+
|
|
166
|
+
# Initialize comet_ml session context
|
|
167
|
+
try:
|
|
168
|
+
initialize_session()
|
|
169
|
+
print("ā Comet ML session initialized")
|
|
170
|
+
except Exception as e:
|
|
171
|
+
print(f"ā ļø Comet ML session initialization failed: {e}")
|
|
172
|
+
print(" Tools requiring comet_ml.API() will not be available")
|
|
173
|
+
|
|
174
|
+
print(f"š§ Available Comet ML tools: {[tool.name for tool in registry.get_tools()]}")
|
|
175
|
+
|
|
176
|
+
try:
|
|
177
|
+
if args.transport == "stdio":
|
|
178
|
+
# Use stdio transport (default)
|
|
179
|
+
async with stdio_server() as (read_stream, write_stream):
|
|
180
|
+
_server_task = asyncio.create_task(
|
|
181
|
+
server.run(read_stream, write_stream, server.create_initialization_options())
|
|
182
|
+
)
|
|
183
|
+
await _server_task
|
|
184
|
+
elif args.transport == "sse":
|
|
185
|
+
# Use SSE transport
|
|
186
|
+
await start_sse_server(args.host, args.port)
|
|
187
|
+
else:
|
|
188
|
+
print(f"ā Unknown transport: {args.transport}")
|
|
189
|
+
sys.exit(1)
|
|
190
|
+
except asyncio.CancelledError:
|
|
191
|
+
print("š Server shutdown completed")
|
|
192
|
+
# Force immediate exit to avoid waiting for stdin
|
|
193
|
+
os._exit(0)
|
|
194
|
+
except KeyboardInterrupt:
|
|
195
|
+
print("\nš Received keyboard interrupt, shutting down...")
|
|
196
|
+
# Force immediate exit to avoid waiting for stdin
|
|
197
|
+
os._exit(0)
|
|
198
|
+
except Exception as e:
|
|
199
|
+
print(f"ā Server error: {e}")
|
|
200
|
+
raise
|
|
201
|
+
|
|
202
|
+
def main_sync():
|
|
203
|
+
"""Synchronous entry point for the comet-mcp command."""
|
|
204
|
+
asyncio.run(main())
|
|
205
|
+
|
|
206
|
+
if __name__ == "__main__":
|
|
207
|
+
main_sync()
|
comet_mcp/session.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Session management for MCP server with comet_ml.API() singleton access.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
from typing import Optional, Generator
|
|
9
|
+
import comet_ml
|
|
10
|
+
from comet_ml import API
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SessionContext:
|
|
14
|
+
"""Context manager for comet_ml.API() singleton access."""
|
|
15
|
+
|
|
16
|
+
def __init__(self):
|
|
17
|
+
self._api: Optional[API] = None
|
|
18
|
+
self._initialized = False
|
|
19
|
+
|
|
20
|
+
def initialize(self):
|
|
21
|
+
"""Initialize the comet_ml.API() instance with configuration."""
|
|
22
|
+
if self._initialized:
|
|
23
|
+
return
|
|
24
|
+
|
|
25
|
+
# Get API key from parameter or environment
|
|
26
|
+
self._api = API()
|
|
27
|
+
self._initialized = True
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def api(self) -> API:
|
|
31
|
+
"""Get the comet_ml.API() instance."""
|
|
32
|
+
if not self._initialized or self._api is None:
|
|
33
|
+
raise RuntimeError("Session not initialized. Call initialize() first.")
|
|
34
|
+
return self._api
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def is_initialized(self) -> bool:
|
|
38
|
+
"""Check if the session is initialized."""
|
|
39
|
+
return self._initialized
|
|
40
|
+
|
|
41
|
+
def reset(self):
|
|
42
|
+
"""Reset the session (useful for testing or reconfiguration)."""
|
|
43
|
+
self._api = None
|
|
44
|
+
self._initialized = False
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# Global session context instance
|
|
48
|
+
session_context = SessionContext()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@contextmanager
|
|
52
|
+
def get_comet_api() -> Generator[API, None, None]:
|
|
53
|
+
"""
|
|
54
|
+
Context manager to get the comet_ml.API() instance.
|
|
55
|
+
|
|
56
|
+
Usage:
|
|
57
|
+
with get_comet_api() as api:
|
|
58
|
+
experiments = api.get_experiments()
|
|
59
|
+
"""
|
|
60
|
+
if not session_context.is_initialized():
|
|
61
|
+
raise RuntimeError("Session not initialized. Call session_context.initialize() first.")
|
|
62
|
+
|
|
63
|
+
yield session_context.api
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def initialize_session():
|
|
67
|
+
"""Initialize the global session context."""
|
|
68
|
+
session_context.initialize()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def get_session_context() -> SessionContext:
|
|
72
|
+
"""Get the global session context instance."""
|
|
73
|
+
return session_context
|
comet_mcp/tool_loader.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Tool loader for Comet ML MCP server.
|
|
4
|
+
Dynamically loads and decorates functions from tools.py.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import inspect
|
|
8
|
+
import importlib.util
|
|
9
|
+
import importlib
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Dict, List, Optional
|
|
13
|
+
from .utils import tool
|
|
14
|
+
from . import tools
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _load_tools():
|
|
18
|
+
"""Dynamically load and decorate all functions from tools module."""
|
|
19
|
+
# Get all functions from the tools module
|
|
20
|
+
for name, obj in inspect.getmembers(tools):
|
|
21
|
+
if inspect.isfunction(obj) and not name.startswith('_'):
|
|
22
|
+
# Check if this function should be decorated as a tool
|
|
23
|
+
# Criteria:
|
|
24
|
+
# 1. Has a docstring (indicates it's a user-facing function)
|
|
25
|
+
# 2. Is not a private function (doesn't start with _)
|
|
26
|
+
# 3. Is not a built-in type or import (check module name)
|
|
27
|
+
# 4. Is not a utility function (check if it's from a different module)
|
|
28
|
+
if (obj.__doc__ and
|
|
29
|
+
not name.startswith('_') and
|
|
30
|
+
obj.__module__ == tools.__name__):
|
|
31
|
+
# Apply the @tool decorator to the function
|
|
32
|
+
decorated_func = tool(obj)
|
|
33
|
+
# Make the decorated function available in this module's namespace
|
|
34
|
+
globals()[name] = decorated_func
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# Load all tools when this module is imported
|
|
38
|
+
_load_tools()
|