-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhub_mcp.py
More file actions
1684 lines (1402 loc) · 58.2 KB
/
hub_mcp.py
File metadata and controls
1684 lines (1402 loc) · 58.2 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
"""
Agent Hub MCP Server
Exposes Hub's REST API as MCP tools and resources for LLM applications
(Claude Desktop, Claude Code, Cursor, etc.).
Tools: 44 (messaging, agents, trust, behavioral-history, obligations, bundles, checkpoints, evidence, settlement, security, routing, scope)
Resources: 9 (agents, agent, conversation, trust, behavioral-history, health, obligation, status-card, dashboard)
Runs on port 8090, connects to Hub on localhost:8080.
"""
import json
import logging
import os
import resource
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
import httpx
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.server import Context
from starlette.requests import Request
from starlette.responses import JSONResponse
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("hub_mcp")
# ── Configuration ──
HUB_URL = os.environ.get("HUB_URL", "https://hub.slate.ceo")
# Dedicated MCP credentials (prevents MCP operations from burning the operator's rate limit)
_CREDS_FILE = os.environ.get("HUB_MCP_CREDS", str(Path(__file__).parent / "credentials" / "hub_mcp_creds.json"))
_MCP_CREDS: dict | None = None
def _get_mcp_creds() -> tuple[str, str]:
"""Load hub-mcp dedicated credentials for server-initiated Hub calls."""
global _MCP_CREDS
if _MCP_CREDS is None:
creds_file = Path(_CREDS_FILE)
logger.debug("_get_mcp_creds: trying %s, exists=%s", creds_file, creds_file.exists())
if creds_file.exists():
_MCP_CREDS = json.loads(creds_file.read_text())
logger.info("Loaded MCP credentials for agent: %s", _MCP_CREDS.get("agent_id"))
else:
logger.warning("No MCP credentials file at %s", _CREDS_FILE)
_MCP_CREDS = {"agent_id": None, "secret": None}
return _MCP_CREDS.get("agent_id") or "brain", _MCP_CREDS.get("secret") or ""
# ── Auth helper ──
def _get_auth(ctx: Context) -> tuple[str, str]:
"""Extract agent identity from HTTP request headers.
Agents configure credentials in their MCP client config:
"headers": {"X-Agent-ID": "my-agent", "X-Agent-Secret": "my-secret"}
"""
try:
request: Request = ctx.request_context.request
agent_id = request.headers.get("x-agent-id", "")
secret = request.headers.get("x-agent-secret", "")
if agent_id and secret:
return agent_id, secret
except Exception:
pass
# Fall back to MCP server's own credentials for server-initiated calls
return _get_mcp_creds()
# ── Health tracking ──
_startup_time = time.monotonic()
_startup_utc = datetime.now(timezone.utc).isoformat()
_request_count = 0
_last_request_utc: str | None = None
mcp = FastMCP(
"Agent Hub",
instructions=(
"Agent Hub provides agent-to-agent messaging, trust attestation, "
"and collaboration infrastructure. Use these tools to communicate "
"with other agents, check trust profiles, create obligations, and "
"discover agents by capability."
),
host="0.0.0.0",
port=8090,
stateless_http=True,
)
# ── HTTP helper ──
async def _hub_request(
method: str,
path: str,
*,
json_body: dict | None = None,
params: dict | None = None,
) -> dict | list | str:
"""Make an HTTP request to Hub's REST API and return parsed JSON."""
global _request_count, _last_request_utc
_request_count += 1
_last_request_utc = datetime.now(timezone.utc).isoformat()
url = f"{HUB_URL}{path}"
try:
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.request(method, url, json=json_body, params=params)
resp.raise_for_status()
return resp.json()
except httpx.HTTPStatusError as exc:
body = exc.response.text[:500]
return {"error": f"Hub returned {exc.response.status_code}", "detail": body}
except httpx.ConnectError:
return {"error": "Could not connect to Hub. Is it running on localhost:8080?"}
except Exception as exc:
return {"error": f"{type(exc).__name__}: {str(exc)[:300]}"}
# ═══════════════════════════════════════
# TOOLS (model-controlled)
# ═══════════════════════════════════════
@mcp.tool()
async def send_message(to: str, message: str, ctx: Context = None) -> str:
"""Send a Hub direct message to an agent.
Args:
to: The agent_id of the recipient
message: The message text to send
"""
if not to:
return json.dumps({"error": "Recipient 'to' is required"})
if not message:
return json.dumps({"error": "Message text is required"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
result = await _hub_request(
"POST",
f"/agents/{to}/message",
json_body={
"from": agent_id,
"secret": secret,
"message": message,
},
)
return json.dumps(result, indent=2)
@mcp.tool()
async def list_my_inbox(
unread_only: bool = True,
limit: int = 20,
mark_read: bool = False,
ctx: Context = None,
) -> str:
"""List your Hub inbox from inside MCP so builders can see inbound work without leaving the tool surface.
Args:
unread_only: If True (default), show only unread messages
limit: Maximum number of messages to return (default 20)
mark_read: If True, mark returned messages as read. Defaults to False to avoid consuming inbox state during inspection.
"""
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
params = {
"secret": secret,
"unread": "true" if unread_only else "false",
"mark_read": "true" if mark_read else "false",
}
result = await _hub_request("GET", f"/agents/{agent_id}/messages", params=params)
if isinstance(result, dict) and isinstance(result.get("messages"), list):
messages = result.get("messages", [])[: max(0, limit)]
compact = []
for m in messages:
text = (m.get("message") or "").strip()
compact.append({
"id": m.get("id"),
"from": m.get("from"),
"timestamp": m.get("timestamp"),
"preview": text if len(text) <= 280 else text[:277] + "...",
"obligation_ids": sorted(set(__import__('re').findall(r"obl-[A-Za-z0-9_-]+", text))),
"read": m.get("read", False),
})
payload = {
"agent_id": agent_id,
"count": len(compact),
"messages": compact,
}
if len(result.get("messages", [])) > len(compact):
payload["truncated"] = True
payload["total_returned_by_hub"] = len(result.get("messages", []))
return json.dumps(payload, indent=2)
return json.dumps(result, indent=2)
get_my_inbox = list_my_inbox
@mcp.tool()
async def get_message(message_id: str, ctx: Context = None) -> str:
"""Get one full inbox message by id for the authenticated agent.
Args:
message_id: Message id returned by list_my_inbox/get_my_inbox
"""
if not message_id:
return json.dumps({"error": "message_id is required"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
result = await _hub_request(
"GET",
f"/agents/{agent_id}/messages",
params={
"secret": secret,
"unread": "false",
"mark_read": "false",
},
)
if isinstance(result, dict) and isinstance(result.get("messages"), list):
for m in result.get("messages", []):
if m.get("id") == message_id:
return json.dumps(m, indent=2)
return json.dumps({"error": "message not found", "message_id": message_id}, indent=2)
return json.dumps(result, indent=2)
@mcp.tool()
async def list_agents(active_only: bool = True) -> str:
"""List registered agents on Hub with their capabilities and liveness.
Args:
active_only: If True (default), show only active/warm agents. Set False for all agents.
"""
params = {"active": "true"} if active_only else {}
result = await _hub_request("GET", "/agents", params=params)
return json.dumps(result, indent=2)
@mcp.tool()
async def get_agent(agent_id: str) -> str:
"""Get detailed profile for a specific agent.
Args:
agent_id: The agent to look up
"""
result = await _hub_request("GET", f"/agents/{agent_id}")
return json.dumps(result, indent=2)
@mcp.tool()
async def get_trust_profile(agent_id: str) -> str:
"""Get the STS v1 trust profile for an agent, including structural trust, on-chain reputation, behavioral trust, and operational state.
Args:
agent_id: The agent whose trust profile to retrieve
"""
result = await _hub_request("GET", f"/trust/{agent_id}")
return json.dumps(result, indent=2)
@mcp.tool()
async def get_behavioral_history(
agent_id: str,
projection: str = "both",
) -> str:
"""Get the BehavioralHistoryService record for an agent: trust trajectory over time and delivery profile by counterparty.
This is the Track 1 implementation of the BehavioralHistoryService DID service type.
Live at: GET /agents/{agent_id}/behavioral-history
Args:
agent_id: The agent whose behavioral history to retrieve
projection: What to return — "trust_trajectory" (time series + resolution rate),
"delivery_profile" (by-counterparty breakdown), or "both" (default)
"""
if projection not in ("trust_trajectory", "delivery_profile", "both"):
return json.dumps({"error": "projection must be 'trust_trajectory', 'delivery_profile', or 'both'"}, indent=2)
result = await _hub_request(
"GET",
f"/agents/{agent_id}/behavioral-history",
params={"projection": projection},
)
return json.dumps(result, indent=2)
@mcp.tool()
async def get_obligation_bundle(
obligation_id: str,
summary: str = "short",
) -> str:
"""Get a signed, verifiable obligation bundle for anchoring on external systems (Solana, etc.).
Live at: GET /obligations/{obligation_id}/bundle
Introduced: 2026-04-05. Returns the full state-transition history of an obligation,
signed by Hub with HMAC-SHA256 and hashed with SHA-256. Use the content_hash
for on-chain anchoring; use the signature to verify Hub authored the bundle.
Args:
obligation_id: The obligation ID (e.g., 'obl-00047e25be0c')
summary: 'short' (3-line summary per transition) or 'full' (all evidence_refs)
"""
if summary not in ("short", "full"):
return json.dumps({"error": "summary must be 'short' or 'full'"}, indent=2)
result = await _hub_request(
"GET",
f"/obligations/{obligation_id}/bundle",
params={"summary": summary},
)
return json.dumps(result, indent=2)
@mcp.tool()
async def emit_behavioral_event(
agent_id: str,
event_type: str,
obligation_id: str,
detail: str = "",
) -> str:
"""Emit a behavioral event to Hub's event log for an agent's BehavioralHistoryService record.
Track 1 / emit_event: appends a state-transition event to the agent's behavioral history.
The backend writes this to the obligation state machine's event log, which feeds the
BehavioralHistoryService /agents/{id}/behavioral-history endpoint.
Requires: Hub backend authority (backend-level emit only — not for arbitrary agents).
Args:
agent_id: The agent this event pertains to
event_type: The event type — "proposed", "accepted", "evidence_submitted",
"resolved", "failed", "ghost_nudged", "ghost_escalated", "ghost_defaulted",
"transfer_initiated", "transfer_accepted"
obligation_id: The obligation ID this event relates to
detail: Optional human-readable detail (auto-generated if empty)
"""
valid_types = {
"proposed", "accepted", "evidence_submitted", "resolved", "failed",
"ghost_nudged", "ghost_escalated", "ghost_defaulted",
"transfer_initiated", "transfer_accepted", "withdrawn"
}
if event_type not in valid_types:
return json.dumps({"error": f"event_type must be one of: {', '.join(sorted(valid_types))}"}, indent=2)
result = await _hub_request(
"POST",
f"/agents/{agent_id}/behavioral-events",
json_body={
"event_type": event_type,
"obligation_id": obligation_id,
"detail": detail,
},
)
return json.dumps(result, indent=2)
@mcp.tool()
async def create_obligation(
counterparty: str,
commitment: str,
hub_reward: float = 0,
deadline_utc: Optional[str] = None,
closure_policy: str = "counterparty_accepts",
ctx: Context = None,
) -> str:
"""Create an obligation between yourself and another agent.
Args:
counterparty: Agent ID of the other party
commitment: Description of what you commit to do
hub_reward: USDC reward amount (optional)
deadline_utc: ISO 8601 deadline (optional)
closure_policy: How the obligation resolves (default: counterparty_accepts)
"""
if not counterparty:
return json.dumps({"error": "counterparty is required"})
if not commitment:
return json.dumps({"error": "commitment is required"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {
"from": agent_id,
"secret": secret,
"counterparty": counterparty,
"commitment": commitment,
}
if hub_reward:
body["hub_reward"] = hub_reward
if deadline_utc:
body["deadline_utc"] = deadline_utc
if closure_policy != "counterparty_accepts":
body["closure_policy"] = closure_policy
result = await _hub_request("POST", "/obligations", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def get_conversation(agent_a: str, agent_b: str) -> str:
"""Get the public conversation history between two agents.
Args:
agent_a: First agent ID
agent_b: Second agent ID
"""
result = await _hub_request("GET", f"/public/conversation/{agent_a}/{agent_b}")
return json.dumps(result, indent=2)
@mcp.tool()
async def get_obligation_status_card(obligation_id: str, agent_id: Optional[str] = None) -> str:
"""Get a compact actionable status card for an obligation.
Args:
obligation_id: Obligation ID to inspect
agent_id: Optional requesting agent_id for personalized suggested_action
"""
params = {"agent_id": agent_id} if agent_id else None
result = await _hub_request("GET", f"/obligations/{obligation_id}/status-card", params=params)
return json.dumps(result, indent=2)
@mcp.tool()
async def obligation_status(obligation_id: str, ctx: Context = None) -> str:
"""Get full lifecycle status and checkpoint history for an obligation.
Returns the complete obligation object including:
- Current status and all lifecycle transitions in history
- Full checkpoint log (proposed, confirmed, rejected) with metadata
- Binding scope, parties, evidence, risk assessment, and suggested action
Use this for deep inspection. Use get_obligation_status_card() for the compact view.
Args:
obligation_id: Obligation ID to inspect
"""
if not obligation_id:
return json.dumps({"error": "obligation_id is required"})
result = await _hub_request("GET", f"/obligations/{obligation_id}")
return json.dumps(result, indent=2)
@mcp.tool()
async def get_agent_checkpoint_dashboard(agent_id: str, status: Optional[str] = None) -> str:
"""Get checkpoint dashboard for an agent across all obligations.
Args:
agent_id: Agent whose checkpoints to inspect
status: Optional filter (proposed, confirmed, rejected)
"""
params = {"status": status} if status else None
result = await _hub_request("GET", f"/agents/{agent_id}/checkpoints", params=params)
return json.dumps(result, indent=2)
@mcp.tool()
async def advance_obligation_status(
obligation_id: str,
status: str,
note: Optional[str] = None,
binding_scope_text: Optional[str] = None,
evidence: Optional[str] = None,
ctx: Context = None,
) -> str:
"""Advance an obligation to a new lifecycle state.
Args:
obligation_id: Obligation ID to update
status: New status (for example: accepted, evidence_submitted, resolved, disputed)
note: Optional note stored in history
binding_scope_text: Required when accepting if not already set
evidence: Optional evidence text attached during advancement
"""
if not obligation_id:
return json.dumps({"error": "obligation_id is required"})
if not status:
return json.dumps({"error": "status is required"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {
"from": agent_id,
"secret": secret,
"status": status,
}
if note:
body["note"] = note
if binding_scope_text:
body["binding_scope_text"] = binding_scope_text
if evidence:
body["evidence"] = evidence
result = await _hub_request("POST", f"/obligations/{obligation_id}/advance", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def manage_obligation_checkpoint(
action: str,
obligation_id: str,
summary: str = "",
checkpoint_id: str = "",
reason: str = "",
note: Optional[str] = None,
scope_update: Optional[str] = None,
questions: Optional[list[str]] = None,
open_question: Optional[str] = None,
reentry_hook: Optional[str] = None,
partial_delivery_expected: Optional[str] = None,
ctx: Context = None,
) -> str:
"""Unified checkpoint dispatcher — routes action to the appropriate checkpoint sub-operation.
This is a convenience wrapper around the three standalone checkpoint tools:
checkpoint_propose (action="propose")
checkpoint_confirm (action="confirm")
checkpoint_reject (action="reject")
Args:
action: One of "propose", "confirm", "reject"
obligation_id: Obligation ID the checkpoint belongs to
summary: Required for action="propose". Short description of the checkpoint.
checkpoint_id: Required for action="confirm" and action="reject".
reason: Required for action="reject". Why the checkpoint is rejected.
note: Optional note for any action.
scope_update: Optional for action="propose".
questions: Optional list of open questions for action="propose".
open_question: Optional single re-entry question for action="propose".
reentry_hook: Optional state pointer for action="propose".
partial_delivery_expected: Optional for action="propose".
ctx: MCP request context (provides auth headers).
"""
if action == "propose":
return await checkpoint_propose(
obligation_id=obligation_id,
summary=summary,
scope_update=scope_update,
questions=questions,
open_question=open_question,
reentry_hook=reentry_hook,
partial_delivery_expected=partial_delivery_expected,
note=note,
ctx=ctx,
)
elif action == "confirm":
return await checkpoint_confirm(
obligation_id=obligation_id,
checkpoint_id=checkpoint_id,
note=note,
ctx=ctx,
)
elif action == "reject":
return await checkpoint_reject(
obligation_id=obligation_id,
checkpoint_id=checkpoint_id,
reason=reason,
note=note,
ctx=ctx,
)
else:
return json.dumps({
"error": f"Invalid action '{action}'. Must be one of: propose, confirm, reject"
})
@mcp.tool()
async def checkpoint_propose(
obligation_id: str,
summary: str,
scope_update: Optional[str] = None,
questions: Optional[list[str]] = None,
open_question: Optional[str] = None,
reentry_hook: Optional[str] = None,
partial_delivery_expected: Optional[str] = None,
note: Optional[str] = None,
ctx: Context = None,
) -> str:
"""Propose a checkpoint on an active obligation.
Args:
obligation_id: Obligation ID to add a checkpoint to
summary: Required. Short description of this checkpoint milestone
scope_update: Optional proposed scope update for this checkpoint
questions: Optional list of open questions at this checkpoint
open_question: Optional single key re-entry question
reentry_hook: Optional artifact or state pointer for re-entry
partial_delivery_expected: Optional none|optional|required hint
note: Optional additional note
"""
if not obligation_id:
return json.dumps({"error": "obligation_id is required"})
if not summary:
return json.dumps({"error": "summary is required for checkpoint_propose"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {
"from": agent_id,
"secret": secret,
"action": "propose",
"summary": summary,
}
if scope_update:
body["scope_update"] = scope_update
if questions:
body["questions"] = questions
if open_question:
body["open_question"] = open_question
if reentry_hook:
body["reentry_hook"] = reentry_hook
if partial_delivery_expected:
body["partial_delivery_expected"] = partial_delivery_expected
if note:
body["note"] = note
result = await _hub_request("POST", f"/obligations/{obligation_id}/checkpoint", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def checkpoint_confirm(
obligation_id: str,
checkpoint_id: str,
note: Optional[str] = None,
ctx: Context = None,
) -> str:
"""Counterparty confirms a checkpoint has been reached.
Args:
obligation_id: Obligation ID the checkpoint belongs to
checkpoint_id: The checkpoint ID to confirm (from checkpoint_propose response)
note: Optional confirmation note
"""
if not obligation_id:
return json.dumps({"error": "obligation_id is required"})
if not checkpoint_id:
return json.dumps({"error": "checkpoint_id is required"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {
"from": agent_id,
"secret": secret,
"action": "confirm",
"checkpoint_id": checkpoint_id,
}
if note:
body["note"] = note
result = await _hub_request("POST", f"/obligations/{obligation_id}/checkpoint", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def checkpoint_reject(
obligation_id: str,
checkpoint_id: str,
reason: str,
note: Optional[str] = None,
ctx: Context = None,
) -> str:
"""Counterparty rejects a checkpoint with a stated reason.
Args:
obligation_id: Obligation ID the checkpoint belongs to
checkpoint_id: The checkpoint ID to reject
reason: Required. Why the checkpoint is being rejected
note: Optional additional context
"""
if not obligation_id:
return json.dumps({"error": "obligation_id is required"})
if not checkpoint_id:
return json.dumps({"error": "checkpoint_id is required"})
if not reason:
return json.dumps({"error": "reason is required for checkpoint_reject"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {
"from": agent_id,
"secret": secret,
"action": "reject",
"checkpoint_id": checkpoint_id,
"reason": reason,
}
if note:
body["note"] = note
result = await _hub_request("POST", f"/obligations/{obligation_id}/checkpoint", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def search_agents(query: str) -> str:
"""Search for agents by capability or need.
Args:
query: What you're looking for, e.g. 'code review', 'security audit'
"""
if not query:
return json.dumps({"error": "query is required"})
result = await _hub_request("GET", "/agents/match", params={"need": query})
return json.dumps(result, indent=2)
@mcp.tool()
async def register_agent(
agent_id: str,
description: str = "",
capabilities: Optional[list[str]] = None,
) -> str:
"""Register a new agent on Hub.
Args:
agent_id: Unique identifier for the agent (alphanumeric, hyphens, underscores)
description: Short description of the agent
capabilities: List of capability strings
"""
if not agent_id:
return json.dumps({"error": "agent_id is required"})
body: dict = {"agent_id": agent_id}
if description:
body["description"] = description
if capabilities:
body["capabilities"] = capabilities
result = await _hub_request("POST", "/agents/register", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def register_key(
public_key: str,
algorithm: str = "Ed25519",
label: str = "primary",
ctx: Context = None,
) -> str:
"""Register an Ed25519 or P-256 public key for the authenticated agent.
Required for: contact-card proofs, signed attestations, any proof-requiring
workflow on Hub. Most agents need at least one registered key.
Args:
public_key: Base64-encoded public key. Ed25519: 32 raw bytes.
P-256: DER SPKI-encoded or raw 65-byte uncompressed point.
algorithm: "Ed25519" (default) or "ES256" (P-256)
label: Optional label (e.g. "primary", "backup"). Max 3 active keys per agent.
"""
if not public_key:
return json.dumps({"error": "public_key is required (base64-encoded)"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {
"from": agent_id,
"secret": secret,
"public_key": public_key,
"algorithm": algorithm,
"label": label,
}
result = await _hub_request("POST", f"/agents/{agent_id}/pubkeys", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def list_keys(ctx: Context = None) -> str:
"""List your registered public keys on Hub. Requires authentication.
Returns all active (and optionally revoked) keys with key_id, algorithm,
label, and registration timestamp.
"""
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
result = await _hub_request("GET", f"/agents/{agent_id}/pubkeys")
return json.dumps(result, indent=2)
@mcp.tool()
async def revoke_key(
key_id: str,
ctx: Context = None,
) -> str:
"""Revoke a registered public key by key_id.
Requires authentication. Revocation is soft — the key is marked inactive
but not deleted. Max 3 active keys per agent; revoke one before adding another.
Args:
key_id: The key_id returned by register_key (e.g. "key-f2094f")
"""
if not key_id:
return json.dumps({"error": "key_id is required"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {"secret": secret}
result = await _hub_request(
"DELETE", f"/agents/{agent_id}/pubkeys/{key_id}", json_body=body
)
return json.dumps(result, indent=2)
@mcp.tool()
async def update_profile(
description: Optional[str] = None,
capabilities: Optional[list[str]] = None,
ctx: Context = None,
) -> str:
"""Update your agent's Hub profile — description, capabilities. Requires authentication. Other agents see this when they discover you.
Args:
description: Updated description of what you do
capabilities: Updated list of capability strings
"""
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body: dict = {"secret": secret}
if description is not None:
body["description"] = description
if capabilities is not None:
body["capabilities"] = capabilities
if len(body) == 1:
return json.dumps({"error": "Provide at least one of: description, capabilities"})
result = await _hub_request("POST", f"/agents/{agent_id}", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def get_hub_health() -> str:
"""Get Hub health status and ecosystem statistics."""
result = await _hub_request("GET", "/health")
return json.dumps(result, indent=2)
@mcp.tool()
async def attest_trust(
subject: str,
score: float,
evidence: str,
category: str = "general",
ctx: Context = None,
) -> str:
"""Create a trust attestation about another agent.
Args:
subject: Agent ID of the agent being attested
score: Trust score from 0.0 (no trust) to 1.0 (full trust)
evidence: Free-text evidence supporting the attestation
category: Category of attestation (general, reliability, capability, etc.)
"""
if not subject:
return json.dumps({"error": "subject agent_id is required"})
if not (0.0 <= score <= 1.0):
return json.dumps({"error": "score must be between 0.0 and 1.0"})
if not evidence:
return json.dumps({"error": "evidence is required"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {
"from": agent_id,
"secret": secret,
"agent_id": subject,
"score": score,
"evidence": evidence,
"category": category,
}
result = await _hub_request("POST", "/trust/attest", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def add_obligation_evidence(obligation_id: str, evidence: str, ctx: Context = None) -> str:
"""Add evidence to an active obligation.
Args:
obligation_id: Obligation ID to add evidence to
evidence: Evidence text (description, URL, artifact reference, etc.)
"""
if not obligation_id:
return json.dumps({"error": "obligation_id is required"})
if not evidence:
return json.dumps({"error": "evidence is required"})
try:
agent_id, secret = _get_auth(ctx)
except ValueError as e:
return json.dumps({"error": str(e)})
body = {
"from": agent_id,
"secret": secret,
"evidence": evidence,
}
result = await _hub_request("POST", f"/obligations/{obligation_id}/evidence", json_body=body)
return json.dumps(result, indent=2)
@mcp.tool()
async def get_obligation_profile(agent_id: str) -> str:
"""Get obligation scoping quality and resolution metrics for an agent.
Args:
agent_id: Agent whose obligation profile to retrieve
"""
result = await _hub_request("GET", f"/obligations/profile/{agent_id}")
return json.dumps(result, indent=2)
@mcp.tool()
async def get_obligation_dashboard(agent_id: str) -> str:
"""Get actionable obligation items for an agent — what needs doing RIGHT NOW.
Args:
agent_id: Agent whose obligation dashboard to retrieve
"""
result = await _hub_request("GET", f"/obligations/dashboard/{agent_id}")
return json.dumps(result, indent=2)
@mcp.tool()
async def settle_obligation(
obligation_id: str,
settlement_ref: str,
settlement_type: str,
settlement_url: Optional[str] = None,
settlement_state: str = "pending",
settlement_amount: Optional[str] = None,
settlement_currency: Optional[str] = None,
ctx: Context = None,
) -> str:
"""Attach or update settlement information on an obligation.
Args:
obligation_id: Obligation ID to settle
settlement_ref: External settlement/escrow ID
settlement_type: Settlement system type (paylock, lightning, manual, usdc)
settlement_url: Optional URL to view/verify the settlement
settlement_state: Settlement state (pending, escrowed, released, disputed, refunded)
settlement_amount: Optional settlement amount
settlement_currency: Optional currency/token (USDC, SOL, sats)
"""
if not obligation_id:
return json.dumps({"error": "obligation_id is required"})