-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanopy_mcp_server.py
More file actions
3038 lines (2784 loc) · 151 KB
/
canopy_mcp_server.py
File metadata and controls
3038 lines (2784 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Canopy HTTP MCP Server
HTTP-based MCP server for Canopy that integrates with MCP Manager.
This allows agents to access Canopy via MCP Manager (port 8000).
Usage:
python canopy_mcp_server.py --port 8030
python canopy_mcp_server.py --host 0.0.0.0 --port 8030 # For WSL/remote access (e.g. OpenClaw)
"""
import argparse
import base64
import json
import logging
import os
import sys
import secrets
from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlencode
try:
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
except ImportError:
Request = urlopen = HTTPError = URLError = None
# Load .env file if python-dotenv is available
try:
from dotenv import load_dotenv
canopy_path = Path(__file__).parent
env_file = canopy_path / ".env"
if env_file.exists():
load_dotenv(env_file)
except ImportError:
pass # python-dotenv not installed, skip
# Add Canopy to path
canopy_path = Path(__file__).parent
sys.path.insert(0, str(canopy_path))
# Import MCP server framework
# 1. Try the vendored copy bundled with Canopy (canopy/mcp/)
# 2. Fall back to a pip-installed or PYTHONPATH copy
# 3. Fall back to MCP_FRAMEWORK_PATH environment variable
try:
from canopy.mcp.mcp_server_framework import MCPHTTPServer
except ImportError:
try:
from mcp_server_framework import MCPHTTPServer
except ImportError:
_fw_path = os.getenv("MCP_FRAMEWORK_PATH")
if _fw_path and Path(_fw_path).is_dir():
sys.path.insert(0, _fw_path)
from mcp_server_framework import MCPHTTPServer
else:
raise ImportError(
"Cannot import mcp_server_framework.\n"
"The vendored copy should be at canopy/mcp/mcp_server_framework.py.\n"
"If missing, try: git pull origin main\n"
"\n"
"Alternatively, set MCP_FRAMEWORK_PATH to a directory containing\n"
"mcp_server_framework.py:\n"
" Linux/macOS: export MCP_FRAMEWORK_PATH=/path/to/infrastructure\n"
" Windows: set MCP_FRAMEWORK_PATH=C:\\path\\to\\infrastructure"
)
# Import Canopy components
from canopy.core.app import create_app
from canopy.core.utils import get_app_components
from canopy.core.messaging import MessageType
from canopy.core.channels import ChannelType
from canopy.core.mentions import build_preview, resolve_mention_targets
from canopy.security.api_keys import Permission
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler(sys.stderr)]
)
logger = logging.getLogger("canopy-mcp-http")
class CanopyMCPHTTPServer(MCPHTTPServer):
"""HTTP-based MCP server for Canopy."""
def __init__(self, port: int = 8030, host: str = "localhost", api_key: Optional[str] = None):
"""Initialize Canopy MCP HTTP server.
Args:
port: Port to run HTTP server on
host: Host to bind to (default localhost; use 0.0.0.0 for WSL/remote access)
api_key: API key for authentication (or use CANOPY_API_KEY env var)
"""
super().__init__("Canopy", "1.0.0", port, host)
# Prefer agent API key if available, otherwise use main API key
self.api_key = api_key or os.getenv('CANOPY_AGENT_API_KEY') or os.getenv('CANOPY_API_KEY')
if not self.api_key:
logger.warning("Warning: CANOPY_API_KEY or CANOPY_AGENT_API_KEY not set. Some tools may not work.")
logger.warning(" Create API key in Canopy UI: http://localhost:7770 → API Keys")
self.user_id = None
self.key_info = None
self.app = None
self._initialize_canopy()
self._register_tools()
def _initialize_canopy(self):
"""Initialize Canopy Flask app and authenticate."""
try:
# Use a different P2P mesh port so MCP server can run alongside Canopy web app (7771)
if not os.getenv('CANOPY_MESH_PORT'):
os.environ['CANOPY_MESH_PORT'] = '7773'
self.app = create_app()
with self.app.app_context():
if self.api_key:
(_, api_key_manager, _, _, _, _, _, _, _, _, _) = get_app_components(self.app)
# --- Diagnostic: show database key inventory ---
try:
with api_key_manager.db.get_connection() as conn:
row = conn.execute(
"SELECT COUNT(*) AS cnt FROM api_keys WHERE revoked = 0"
).fetchone()
total_active = row['cnt'] if row else 0
logger.info(f"API key database: {total_active} active key(s) in {api_key_manager.db.db_path}")
except Exception as diag_err:
logger.warning(f"Could not read key inventory: {diag_err}")
self.key_info = api_key_manager.validate_key(self.api_key)
if self.key_info:
self.user_id = self.key_info.user_id
perms = sorted(p.value for p in self.key_info.permissions)
logger.info(f"Authenticated as user: {self.user_id}")
logger.info(f"Key permissions: {', '.join(perms)}")
else:
logger.warning("API key validation FAILED — tools requiring permissions will not work.")
# Detailed diagnostics to help troubleshoot
try:
import hashlib as _hl
key_hash = _hl.sha256(self.api_key.encode()).hexdigest()
with api_key_manager.db.get_connection() as conn:
row = conn.execute(
"SELECT id, permissions, revoked, expires_at FROM api_keys WHERE key_hash = ?",
(key_hash,),
).fetchone()
if row:
logger.warning(
f" Key hash found (id={row['id']}), "
f"revoked={bool(row['revoked'])}, "
f"expires_at={row['expires_at']}, "
f"permissions={row['permissions']}"
)
else:
logger.warning(
f" Key hash NOT found in database at: "
f"{api_key_manager.db.db_path.absolute()}"
)
logger.warning(
" This usually means the key was created in a "
"different Canopy instance (different database). "
"Make sure the web server and MCP server share "
"the same data directory."
)
# List first few key IDs to help identify the DB
rows = conn.execute(
"SELECT id, user_id FROM api_keys LIMIT 5"
).fetchall()
if rows:
for r in rows:
logger.warning(f" DB key: id={r['id']}, user={r['user_id']}")
else:
logger.warning(" Database has ZERO API keys — is the web server running?")
except Exception as inner_err:
logger.warning(f" Diagnostic query failed: {inner_err}")
else:
logger.warning("No API key configured. Set CANOPY_API_KEY env var.")
except Exception as e:
logger.error(f"Failed to initialize Canopy: {e}")
logger.error(" Make sure Canopy is properly installed and database exists")
def _check_permission(self, required_permission: Permission) -> bool:
"""Check if authenticated key has required permission."""
if not self.key_info:
return False
return self.key_info.has_permission(required_permission)
def _send_channel_message_via_api(
self,
channel_id: str,
content: str,
attachments_list: List[Dict[str, Any]],
ttl_seconds: int = 0,
ttl_mode: str = "",
expires_at: str = "",
parent_message_id: str = "",
) -> Tuple[bool, Optional[str], Optional[str]]:
"""POST channel message to main Canopy API so P2P broadcast runs. Returns (success, message_id, error)."""
if not self.api_key or not (Request and urlopen):
return False, None, "API key or urllib missing"
base = (os.getenv("CANOPY_API_BASE_URL") or "http://127.0.0.1:7770").rstrip("/")
url = f"{base}/api/v1/channels/messages"
body = {
"channel_id": channel_id,
"content": content,
"attachments": attachments_list,
}
if ttl_seconds:
body["ttl_seconds"] = ttl_seconds
if ttl_mode:
body["ttl_mode"] = ttl_mode
if expires_at:
body["expires_at"] = expires_at
if parent_message_id:
body["parent_message_id"] = parent_message_id
try:
req = Request(
url,
data=json.dumps(body).encode("utf-8"),
headers={
"Content-Type": "application/json",
"X-API-Key": self.api_key,
},
method="POST",
)
with urlopen(req, timeout=15) as resp:
if resp.status != 201:
return False, None, f"API returned {resp.status}"
data = json.loads(resp.read().decode("utf-8"))
msg = (data or {}).get("message") or {}
mid = msg.get("id") if isinstance(msg, dict) else None
return True, mid, None
except HTTPError as e:
return False, None, f"API error: {e.code} {e.reason}"
except URLError as e:
return False, None, f"API unreachable: {e.reason}"
except Exception as e:
return False, None, str(e)
def _api_call(self, method: str, path: str, body: Optional[dict] = None) -> Tuple[bool, Optional[dict], Optional[Any]]:
"""Make an HTTP request to the main Canopy web server API.
The MCP server runs its own P2P mesh (port 7773) which is separate
from the web server's mesh (port 7771). Other peers connect to the
web server, not the MCP server — so P2P broadcasts from here never
reach them. By proxying write operations through the web server's
REST API we let *its* P2P mesh handle the broadcast.
Returns (success, response_dict, error_string).
"""
if not self.api_key or not (Request and urlopen):
return False, None, "API key or urllib missing"
base = (os.getenv("CANOPY_API_BASE_URL") or "http://127.0.0.1:7770").rstrip("/")
url = f"{base}{path}"
try:
data = json.dumps(body).encode("utf-8") if body else None
req = Request(
url,
data=data,
headers={
"Content-Type": "application/json",
"X-API-Key": self.api_key,
},
method=method,
)
with urlopen(req, timeout=15) as resp:
resp_data = json.loads(resp.read().decode("utf-8"))
return True, resp_data, None
except HTTPError as e:
body_text = ""
body_json = None
try:
body_text = e.read().decode("utf-8", errors="replace")
try:
body_json = json.loads(body_text)
except Exception:
body_json = None
except Exception:
pass
return False, None, {
"status": e.code,
"reason": e.reason,
"body": body_json if body_json is not None else body_text,
}
except URLError as e:
return False, None, f"API unreachable: {e.reason}"
except Exception as e:
return False, None, str(e)
def _create_task_via_api(self, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""POST task to main Canopy API so the web server handles P2P broadcast."""
return self._api_call("POST", "/api/v1/tasks", body)
def _update_task_via_api(self, task_id: str, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""PATCH task via main Canopy API so the web server handles P2P broadcast."""
return self._api_call("PATCH", f"/api/v1/tasks/{task_id}", body)
def _list_objectives_via_api(self, params: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET objectives via main Canopy API."""
query = urlencode({k: v for k, v in params.items() if v is not None and v != ""})
path = "/api/v1/objectives"
if query:
path = f"{path}?{query}"
return self._api_call("GET", path, None)
def _get_objective_via_api(self, objective_id: str, params: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET objective via main Canopy API."""
query = urlencode({k: v for k, v in params.items() if v is not None and v != ""})
path = f"/api/v1/objectives/{objective_id}"
if query:
path = f"{path}?{query}"
return self._api_call("GET", path, None)
def _create_objective_via_api(self, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""POST objective via main Canopy API."""
return self._api_call("POST", "/api/v1/objectives", body)
def _update_objective_via_api(self, objective_id: str, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""PATCH objective via main Canopy API."""
return self._api_call("PATCH", f"/api/v1/objectives/{objective_id}", body)
def _add_objective_task_via_api(self, objective_id: str, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""POST objective task via main Canopy API."""
return self._api_call("POST", f"/api/v1/objectives/{objective_id}/tasks", body)
def _list_requests_via_api(self, params: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET requests via main Canopy API."""
query = urlencode({k: v for k, v in params.items() if v is not None and v != ""})
path = "/api/v1/requests"
if query:
path = f"{path}?{query}"
return self._api_call("GET", path, None)
def _get_request_via_api(self, request_id: str, params: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET request via main Canopy API."""
query = urlencode({k: v for k, v in params.items() if v is not None and v != ""})
path = f"/api/v1/requests/{request_id}"
if query:
path = f"{path}?{query}"
return self._api_call("GET", path, None)
def _create_request_via_api(self, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""POST request via main Canopy API."""
return self._api_call("POST", "/api/v1/requests", body)
def _update_request_via_api(self, request_id: str, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""PATCH request via main Canopy API."""
return self._api_call("PATCH", f"/api/v1/requests/{request_id}", body)
def _list_signals_via_api(self, params: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET signals via main Canopy API."""
query = urlencode({k: v for k, v in params.items() if v is not None and v != ""})
path = "/api/v1/signals"
if query:
path = f"{path}?{query}"
return self._api_call("GET", path, None)
def _get_signal_via_api(self, signal_id: str, params: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET signal via main Canopy API."""
query = urlencode({k: v for k, v in params.items() if v is not None and v != ""})
path = f"/api/v1/signals/{signal_id}"
if query:
path = f"{path}?{query}"
return self._api_call("GET", path, None)
def _create_signal_via_api(self, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""POST signal via main Canopy API."""
return self._api_call("POST", "/api/v1/signals", body)
def _update_signal_via_api(self, signal_id: str, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""PATCH signal via main Canopy API."""
return self._api_call("PATCH", f"/api/v1/signals/{signal_id}", body)
def _lock_signal_via_api(self, signal_id: str, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""POST signal lock/unlock via main Canopy API."""
return self._api_call("POST", f"/api/v1/signals/{signal_id}/lock", body)
def _update_profile_via_api(self, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""POST profile update via main Canopy API so the web server handles P2P broadcast."""
return self._api_call("POST", "/api/v1/profile", body)
def _extract_content_context_via_api(self, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""POST content-context extraction via main Canopy API."""
return self._api_call("POST", "/api/v1/content-contexts/extract", body)
def _list_content_contexts_via_api(self, params: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET content contexts via main Canopy API."""
query = urlencode({k: v for k, v in params.items() if v is not None and v != ""})
path = "/api/v1/content-contexts"
if query:
path = f"{path}?{query}"
return self._api_call("GET", path, None)
def _get_content_context_via_api(self, context_id: str) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET content context by ID via main Canopy API."""
return self._api_call("GET", f"/api/v1/content-contexts/{context_id}", None)
def _get_content_context_text_via_api(self, context_id: str) -> Tuple[bool, Optional[dict], Optional[str]]:
"""GET content context text endpoint. Falls back to JSON error details if any."""
# _api_call expects JSON response; use raw urllib call to support text/plain response.
if not self.api_key or not (Request and urlopen):
return False, None, "API key or urllib missing"
base = (os.getenv("CANOPY_API_BASE_URL") or "http://127.0.0.1:7770").rstrip("/")
url = f"{base}/api/v1/content-contexts/{context_id}/text"
try:
req = Request(
url,
headers={
"X-API-Key": self.api_key,
},
method="GET",
)
with urlopen(req, timeout=15) as resp:
text = resp.read().decode("utf-8", errors="replace")
return True, {"text": text}, None
except HTTPError as e:
body_text = ""
try:
body_text = e.read().decode("utf-8", errors="replace")
except Exception:
body_text = str(e)
return False, None, f"API error: {e.code} {e.reason} {body_text}".strip()
except URLError as e:
return False, None, f"API unreachable: {e.reason}"
except Exception as e:
return False, None, str(e)
def _update_content_context_note_via_api(self, context_id: str, body: dict) -> Tuple[bool, Optional[dict], Optional[str]]:
"""PATCH owner note for content context via main Canopy API."""
return self._api_call("PATCH", f"/api/v1/content-contexts/{context_id}/note", body)
def _get_app_components(self):
"""Get Canopy app components."""
with self.app.app_context():
return get_app_components(self.app)
def _register_tools(self):
"""Register all Canopy MCP tools."""
@self.tool
def canopy_send_message(
content: str,
recipient_id: str = "",
file_path: str = ""
) -> Dict[str, Any]:
"""Send a DIRECT MESSAGE (DM) only. NOT for channel posts — use canopy_send_channel_message for channels. This stores in the DM table and does NOT broadcast via P2P."""
if not self.key_info or not self._check_permission(Permission.WRITE_MESSAGES):
return {"success": False, "error": "Permission denied: write_messages required"}
try:
with self.app.app_context():
(_, _, _, message_manager, _, file_manager, _, _, _, _, _) = self._get_app_components()
# Handle file attachment
attachments = []
message_type = MessageType.TEXT
if file_path and Path(file_path).exists():
with open(file_path, 'rb') as f:
file_data = f.read()
file_info = file_manager.save_file(
file_data,
Path(file_path).name,
"application/octet-stream",
self.user_id
)
if file_info:
attachments.append({
'id': file_info.id,
'name': file_info.original_name,
'type': file_info.content_type,
'size': file_info.size,
'url': file_info.url
})
message_type = MessageType.FILE
# Create and send message
recipient = recipient_id if recipient_id else None
metadata = {'attachments': attachments} if attachments else None
message = message_manager.create_message(
self.user_id, content, recipient, message_type, metadata
)
if message and message_manager.send_message(message):
return {
"success": True,
"message_id": message.id,
"type": "broadcast" if recipient is None else "direct",
"attachments": len(attachments)
}
else:
return {"success": False, "error": "Failed to send message"}
except Exception as e:
logger.error(f"Error sending message: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_messages(limit: int = 10, recipient_id: str = "") -> Dict[str, Any]:
"""Get recent messages from Canopy."""
if not self.key_info or not self._check_permission(Permission.READ_MESSAGES):
return {"success": False, "error": "Permission denied: read_messages required"}
try:
with self.app.app_context():
(_, _, _, message_manager, _, _, _, _, _, _, _) = self._get_app_components()
# Get messages (broadcast or direct)
messages = message_manager.get_messages(
user_id=self.user_id,
limit=limit
)
# Filter by recipient if specified
if recipient_id:
messages = [m for m in messages if m.recipient_id == recipient_id or m.sender_id == recipient_id]
return {
"success": True,
"messages": [msg.to_dict() for msg in messages],
"count": len(messages)
}
except Exception as e:
logger.error(f"Error getting messages: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_mentions(since: str = "", limit: int = 50, include_acknowledged: bool = False) -> Dict[str, Any]:
"""Get mention events for the authenticated user."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
try:
with self.app.app_context():
mention_manager = self.app.config.get('MENTION_MANAGER')
if not mention_manager:
return {"success": True, "mentions": [], "count": 0}
events = mention_manager.get_mentions(
user_id=self.user_id,
since=since or None,
limit=limit,
include_acknowledged=include_acknowledged,
)
return {"success": True, "mentions": events, "count": len(events)}
except Exception as e:
logger.error(f"Error getting mentions: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_ack_mentions(mention_ids: List[str]) -> Dict[str, Any]:
"""Acknowledge mention events by ID."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
if not isinstance(mention_ids, list) or not mention_ids:
return {"success": False, "error": "mention_ids must be a non-empty list"}
try:
with self.app.app_context():
mention_manager = self.app.config.get('MENTION_MANAGER')
if not mention_manager:
return {"success": True, "acknowledged": 0}
count = mention_manager.acknowledge_mentions(
user_id=self.user_id,
mention_ids=mention_ids,
)
return {"success": True, "acknowledged": count}
except Exception as e:
logger.error(f"Error acknowledging mentions: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_extract_content_context(
source_type: str = "url",
source_id: str = "",
url: str = "",
force_refresh: bool = False,
) -> Dict[str, Any]:
"""
Extract best-effort text context from external content.
source_type: url | feed_post | channel_message | direct_message.
For source_type=url, provide url directly.
For source_type=feed_post/channel_message/direct_message, provide source_id; url is optional override.
"""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
source_type_norm = (source_type or "").strip().lower()
if source_type_norm not in ("url", "feed_post", "channel_message", "direct_message"):
return {"success": False, "error": "source_type must be one of: url, feed_post, channel_message, direct_message"}
if source_type_norm != "url" and not (source_id or "").strip():
return {"success": False, "error": "source_id is required for feed_post/channel_message/direct_message"}
body: Dict[str, Any] = {
"source_type": source_type_norm,
"force_refresh": bool(force_refresh),
}
if source_id:
body["source_id"] = source_id.strip()
if url:
body["url"] = url.strip()
try:
ok, resp, err = self._extract_content_context_via_api(body)
if ok and resp:
return {
"success": True,
"context": (resp or {}).get("context"),
"cached": bool((resp or {}).get("cached")),
"extracted": bool((resp or {}).get("extracted", True)),
}
return {"success": False, "error": err or "Context extraction failed"}
except Exception as e:
logger.error(f"Error extracting content context: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_list_content_contexts(
source_type: str = "",
source_id: str = "",
source_url: str = "",
owner_user_id: str = "",
limit: int = 50,
) -> Dict[str, Any]:
"""List stored content-context rows (owner-scoped by default)."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
params: Dict[str, Any] = {"limit": max(1, min(int(limit or 50), 200))}
if source_type:
params["source_type"] = source_type.strip().lower()
if source_id:
params["source_id"] = source_id.strip()
if source_url:
params["source_url"] = source_url.strip()
if owner_user_id:
params["owner_user_id"] = owner_user_id.strip()
try:
ok, resp, err = self._list_content_contexts_via_api(params)
if ok and resp:
contexts = (resp or {}).get("contexts") or []
return {"success": True, "contexts": contexts, "count": len(contexts)}
return {"success": False, "error": err or "Failed to list content contexts"}
except Exception as e:
logger.error(f"Error listing content contexts: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_content_context(context_id: str, as_text: bool = False) -> Dict[str, Any]:
"""Get one content-context row by ID. Set as_text=true to return the text blob directly."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
if not (context_id or "").strip():
return {"success": False, "error": "context_id required"}
try:
context_id = context_id.strip()
if as_text:
ok_txt, resp_txt, err_txt = self._get_content_context_text_via_api(context_id)
if ok_txt and resp_txt:
return {"success": True, "context_id": context_id, "text": (resp_txt or {}).get("text", "")}
return {"success": False, "error": err_txt or "Failed to get context text"}
ok, resp, err = self._get_content_context_via_api(context_id)
if ok and resp:
return {"success": True, "context": (resp or {}).get("context")}
return {"success": False, "error": err or "Failed to get content context"}
except Exception as e:
logger.error(f"Error getting content context: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_update_content_context_note(context_id: str, owner_note: str) -> Dict[str, Any]:
"""Update the owner note for a content-context row (owner/admin only)."""
if not self.key_info or not self._check_permission(Permission.WRITE_FEED):
return {"success": False, "error": "Permission denied: write_feed required"}
if not (context_id or "").strip():
return {"success": False, "error": "context_id required"}
body = {"owner_note": (owner_note or "").strip()}
try:
ok, resp, err = self._update_content_context_note_via_api(context_id.strip(), body)
if ok and resp:
return {"success": True, "context": (resp or {}).get("context")}
return {"success": False, "error": err or "Failed to update content context note"}
except Exception as e:
logger.error(f"Error updating content context note: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_inbox(status: str = "", limit: int = 50, since: str = "", include_handled: bool = False) -> Dict[str, Any]:
"""Get agent inbox items (pull-first triggers)."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
try:
with self.app.app_context():
inbox_manager = self.app.config.get('INBOX_MANAGER')
if not inbox_manager:
return {"success": True, "items": [], "count": 0}
items = inbox_manager.list_items(
user_id=self.user_id,
status=status or None,
limit=limit,
since=since or None,
include_handled=include_handled,
)
return {"success": True, "items": items, "count": len(items)}
except Exception as e:
logger.error(f"Error getting inbox: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_inbox_count(status: str = "") -> Dict[str, Any]:
"""Get count of agent inbox items."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
try:
with self.app.app_context():
inbox_manager = self.app.config.get('INBOX_MANAGER')
if not inbox_manager:
return {"success": True, "count": 0}
count = inbox_manager.count_items(
user_id=self.user_id,
status=status or None,
)
return {"success": True, "count": count}
except Exception as e:
logger.error(f"Error getting inbox count: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_inbox_stats(window_hours: int = 24) -> Dict[str, Any]:
"""Get inbox stats (status counts + rejection reasons)."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
try:
with self.app.app_context():
inbox_manager = self.app.config.get('INBOX_MANAGER')
if not inbox_manager:
return {"success": True, "stats": {}}
stats = inbox_manager.get_stats(
user_id=self.user_id,
window_hours=window_hours,
)
return {"success": True, "stats": stats}
except Exception as e:
logger.error(f"Error getting inbox stats: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_inbox_audit(limit: int = 50, since: str = "") -> Dict[str, Any]:
"""List recent inbox rejection audit entries."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
try:
with self.app.app_context():
inbox_manager = self.app.config.get('INBOX_MANAGER')
if not inbox_manager:
return {"success": True, "items": [], "count": 0}
items = inbox_manager.list_audit(
user_id=self.user_id,
limit=limit,
since=since or None,
)
return {"success": True, "items": items, "count": len(items)}
except Exception as e:
logger.error(f"Error getting inbox audit: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_ack_inbox(ids: List[str], status: str = "handled") -> Dict[str, Any]:
"""Update agent inbox items (mark handled/skipped/pending)."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
if not isinstance(ids, list) or not ids:
return {"success": False, "error": "ids must be a non-empty list"}
try:
with self.app.app_context():
inbox_manager = self.app.config.get('INBOX_MANAGER')
if not inbox_manager:
return {"success": True, "updated": 0}
updated = inbox_manager.update_items(
user_id=self.user_id,
ids=ids,
status=status,
)
return {"success": True, "updated": updated}
except Exception as e:
logger.error(f"Error updating inbox: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_inbox_config() -> Dict[str, Any]:
"""Get agent inbox configuration."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
try:
with self.app.app_context():
inbox_manager = self.app.config.get('INBOX_MANAGER')
if not inbox_manager:
return {"success": True, "config": {}}
config = inbox_manager.get_config(self.user_id)
return {"success": True, "config": config}
except Exception as e:
logger.error(f"Error getting inbox config: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_set_inbox_config(config: Dict[str, Any]) -> Dict[str, Any]:
"""Update agent inbox configuration."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
if not isinstance(config, dict) or not config:
return {"success": False, "error": "config must be a non-empty object"}
try:
with self.app.app_context():
inbox_manager = self.app.config.get('INBOX_MANAGER')
if not inbox_manager:
return {"success": True, "config": {}}
updated = inbox_manager.set_config(self.user_id, config)
return {"success": True, "config": updated}
except Exception as e:
logger.error(f"Error updating inbox config: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_catchup(since: str = "", window_hours: int = 24, limit: int = 25) -> Dict[str, Any]:
"""Get a catch-up digest (feed, channels, mentions, inbox, tasks, circles, handoffs)."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
try:
with self.app.app_context():
(_, _, _, message_manager, channel_manager,
_, feed_manager, _, _, _, _) = get_app_components(self.app)
mention_manager = self.app.config.get('MENTION_MANAGER')
inbox_manager = self.app.config.get('INBOX_MANAGER')
task_manager = self.app.config.get('TASK_MANAGER')
circle_manager = self.app.config.get('CIRCLE_MANAGER')
handoff_manager = self.app.config.get('HANDOFF_MANAGER')
def _parse_since(raw: str, hours: int) -> datetime:
now = datetime.now(timezone.utc)
if raw:
s = str(raw).strip()
if s:
try:
if s.isdigit():
return datetime.fromtimestamp(float(s), tz=timezone.utc)
dt_val = datetime.fromisoformat(s.replace('Z', '+00:00'))
if dt_val.tzinfo is None:
dt_val = dt_val.replace(tzinfo=timezone.utc)
return dt_val
except Exception:
pass
return now - timedelta(hours=max(1, int(hours or 24)))
since_dt = _parse_since(since, window_hours)
since_iso = since_dt.isoformat()
channels_activity = []
if channel_manager:
try:
channels_activity = channel_manager.get_channel_activity_since(self.user_id, since_dt, limit=limit)
except Exception:
channels_activity = []
feed_items = []
if feed_manager:
try:
posts = feed_manager.get_posts_since(self.user_id, since_dt, limit=limit)
for post in posts:
feed_items.append({
'post_id': post.id,
'author_id': post.author_id,
'created_at': post.created_at.isoformat() if post.created_at else None,
'visibility': post.visibility.value if hasattr(post.visibility, 'value') else str(post.visibility),
'expires_at': post.expires_at.isoformat() if getattr(post, 'expires_at', None) else None,
'preview': build_preview(post.content or ''),
})
except Exception:
feed_items = []
dm_items = []
if message_manager and self._check_permission(Permission.READ_MESSAGES):
try:
messages = message_manager.get_messages(self.user_id, limit=limit, since=since_dt)
for msg in messages:
dm_items.append({
'message_id': msg.id,
'sender_id': msg.sender_id,
'recipient_id': msg.recipient_id,
'created_at': msg.created_at.isoformat() if msg.created_at else None,
'preview': build_preview(msg.content or ''),
'message_type': msg.message_type.value if hasattr(msg.message_type, 'value') else str(msg.message_type),
})
except Exception:
dm_items = []
mention_items = mention_manager.get_mentions(self.user_id, since=since_iso, limit=limit, include_acknowledged=False) if mention_manager else []
inbox_items = inbox_manager.list_items(self.user_id, status='pending', limit=limit, since=since_iso, include_handled=False) if inbox_manager else []
task_items = task_manager.get_tasks_since(since_iso, limit=limit) if task_manager else []
circle_items = [c.to_dict() for c in circle_manager.list_circles_since(since_iso, limit=limit)] if circle_manager else []
handoff_items = [h.to_dict() for h in handoff_manager.list_handoffs_since(since_dt, limit=limit, viewer_id=self.user_id)] if handoff_manager else []
channel_total = 0
for ch in channels_activity:
try:
channel_total += int(ch.get('new_messages') or 0)
except Exception:
continue
return {
"success": True,
"since": since_iso,
"generated_at": datetime.now(timezone.utc).isoformat(),
"channels": {"count": len(channels_activity), "messages_total": channel_total, "items": channels_activity},
"feed": {"count": len(feed_items), "items": feed_items},
"messages": {"count": len(dm_items), "items": dm_items},
"mentions": {"count": len(mention_items), "items": mention_items},
"inbox": {"count": len(inbox_items), "items": inbox_items},
"tasks": {"count": len(task_items), "items": task_items},
"circles": {"count": len(circle_items), "items": circle_items},
"handoffs": {"count": len(handoff_items), "items": handoff_items},
}
except Exception as e:
logger.error(f"Error getting catchup: {e}")
return {"success": False, "error": str(e)}
@self.tool
def canopy_get_session_catchup(since: str = "", window_hours: int = 24, limit: int = 25) -> Dict[str, Any]:
"""Get a session digest (channels, mentions, inbox, circles, tasks, peers)."""
if not self.key_info or not self._check_permission(Permission.READ_FEED):
return {"success": False, "error": "Permission denied: read_feed required"}
try:
with self.app.app_context():
(_, _, _, message_manager, channel_manager,
_, feed_manager, _, _, _, p2p_manager) = get_app_components(self.app)
mention_manager = self.app.config.get('MENTION_MANAGER')
inbox_manager = self.app.config.get('INBOX_MANAGER')
task_manager = self.app.config.get('TASK_MANAGER')
circle_manager = self.app.config.get('CIRCLE_MANAGER')
def _parse_since(raw: str, hours: int) -> datetime:
now = datetime.now(timezone.utc)
if raw:
s = str(raw).strip()
if s:
try:
if s.isdigit():
return datetime.fromtimestamp(float(s), tz=timezone.utc)
dt_val = datetime.fromisoformat(s.replace('Z', '+00:00'))
if dt_val.tzinfo is None:
dt_val = dt_val.replace(tzinfo=timezone.utc)
return dt_val
except Exception:
pass
return now - timedelta(hours=max(1, int(hours or 24)))
since_dt = _parse_since(since, window_hours)
since_iso = since_dt.isoformat()
channels_activity = []
if channel_manager:
try:
channels_activity = channel_manager.get_channel_activity_since(self.user_id, since_dt, limit=limit)
except Exception:
channels_activity = []
session_channels = []
for ch in channels_activity:
session_channels.append({
'channel_id': ch.get('channel_id'),
'channel_name': ch.get('channel_name'),
'new_message_count': ch.get('new_messages'),
'latest_message_preview': ch.get('latest_preview') or '',
})
mention_items = mention_manager.get_mentions(self.user_id, since=since_iso, limit=limit, include_acknowledged=False) if mention_manager else []
inbox_items = []
inbox_count = 0
if inbox_manager:
try:
stats = inbox_manager.get_stats(self.user_id, window_hours=window_hours)
inbox_count = int((stats.get('status_counts') or {}).get('pending', 0))
except Exception:
inbox_count = 0
try: