-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatgpt_rest_api_v2.py
More file actions
1857 lines (1575 loc) · 71.1 KB
/
Copy pathchatgpt_rest_api_v2.py
File metadata and controls
1857 lines (1575 loc) · 71.1 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
"""Consolidated REST API v2 for ChatGPT - Full functionality in 25 endpoints.
This version uses smart query parameters and comprehensive responses to provide
ALL functionality from the original 45+ endpoints while staying under ChatGPT's
30 endpoint limit.
Key consolidations:
- Marketplace orders: 4 endpoints -> 1 (query params for id/batch/seller)
- Bank balances: 3 endpoints -> 1 (query params for denom/spendable)
- Distribution validator: 3 endpoints -> 1 (returns rewards+commission+slashes)
- Distribution delegator: 4 endpoints -> 1 (returns all delegation info)
- Governance params: 3 endpoints -> 1 (query param for type)
- Governance proposal: 5 endpoints -> 1 (comprehensive response)
"""
import sys
import asyncio
import logging
import json
import time
from pathlib import Path
from typing import Optional, List, Dict, Any
from enum import Enum
sys.path.insert(0, str(Path(__file__).parent / "src"))
from fastapi import FastAPI, HTTPException, Query, Path as PathParam, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
import uvicorn
import httpx
import os
from mcp_server.tools import (
bank_tools,
distribution_tools,
governance_tools,
marketplace_tools,
basket_tools,
credit_tools,
analytics_tools,
)
from mcp_server.middleware import (
RequestIDMiddleware,
TransientError,
GovernanceUnavailableError,
get_request_id,
add_tool_trace,
create_envelope,
create_error_envelope,
extract_pagination_from_response,
is_transient_error,
)
from mcp_server.models.response_envelope import (
DataSource,
create_tool_trace,
)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# =============================================================================
# Off-chain Metadata Enrichment Configuration (Session E)
# =============================================================================
KOI_API_ENDPOINT = os.environ.get("KOI_API_ENDPOINT", "https://regen.gaiaai.xyz/api/koi")
KOI_INTERNAL_API_KEY = os.environ.get("KOI_INTERNAL_API_KEY", "")
ENRICHMENT_MAX_ITEMS = 10 # Cap enriched items per response
ENRICHMENT_TIMEOUT_SECONDS = 5.0 # Strict timeout per enrichment
METADATA_IRI_PREFIX = "regen:" # Only enrich Regen IRIs
# =============================================================================
# Supply Enrichment Configuration (Batch Summary Mode)
# =============================================================================
# Caps for batch supply fetching to avoid N+1 explosions
MAX_BATCH_PAGES = 50 # Max pages to fetch when fetch_all=true
MAX_SUPPLY_BATCHES = 500 # Max batches for which to fetch supply data
SUPPLY_FETCH_TIMEOUT_SECONDS = 25.0 # Time budget for supply fetching
SUPPLY_MAX_CONCURRENT = 20 # Max concurrent supply requests
async def derive_hectares_for_iri(
iri: str,
client: httpx.AsyncClient,
force_refresh: bool = False
) -> Optional[Dict[str, Any]]:
"""
Derive hectares from a metadata IRI via the KOI API.
Enforces "no citation, no metric" policy.
Returns None if derivation fails (metric should not be reported).
"""
if not iri or not iri.startswith(METADATA_IRI_PREFIX):
return None
if not KOI_INTERNAL_API_KEY:
logger.warning("KOI_INTERNAL_API_KEY not configured - skipping enrichment")
return None
try:
response = await client.post(
f"{KOI_API_ENDPOINT}/metadata/hectares",
json={"iri": iri, "force_refresh": force_refresh},
headers={"X-Internal-API-Key": KOI_INTERNAL_API_KEY},
timeout=ENRICHMENT_TIMEOUT_SECONDS
)
if response.status_code != 200:
# Blocked or failed - no metric
logger.debug(f"Hectares derivation blocked for {iri}: {response.status_code}")
return None
data = response.json()
# Unwrap KOI envelope if present
if "data" in data and "request_id" in data:
data = data["data"]
return {
"hectares": data.get("hectares"),
"unit": data.get("unit", "ha"),
"derivation": data.get("derivation", {}),
"citation": data.get("citations", [{}])[0] if data.get("citations") else None
}
except httpx.TimeoutException:
logger.warning(f"Timeout deriving hectares for {iri}")
return None
except Exception as e:
logger.warning(f"Error deriving hectares for {iri}: {e}")
return None
async def enrich_projects_with_offchain_metrics(
projects: List[Dict[str, Any]],
force_refresh: bool = False
) -> tuple[List[Dict[str, Any]], List[str]]:
"""
Enrich projects with off-chain hectares metrics.
Only enriches the first N projects to prevent long loops.
Returns:
tuple: (enriched_projects, warnings)
"""
warnings: List[str] = []
enriched_count = 0
async with httpx.AsyncClient() as client:
for i, project in enumerate(projects):
# Cap enrichment to prevent long loops
if enriched_count >= ENRICHMENT_MAX_ITEMS:
warnings.append(
f"ENRICHMENT_CAPPED: Only first {ENRICHMENT_MAX_ITEMS} projects enriched"
)
break
metadata = project.get("metadata", "")
if not metadata or not metadata.startswith(METADATA_IRI_PREFIX):
continue
hectares_data = await derive_hectares_for_iri(
metadata, client, force_refresh
)
if hectares_data:
# Add offchain_metrics to project
project["offchain_metrics"] = {
"hectares": hectares_data["hectares"],
"unit": hectares_data["unit"],
"derivation": {
"iri": metadata,
"rid": hectares_data["derivation"].get("rid"),
"resolver_url": hectares_data["derivation"].get("resolver_url"),
"content_hash": hectares_data["derivation"].get("content_hash"),
"json_pointer": hectares_data["derivation"].get("json_pointer"),
"expected_unit": hectares_data["derivation"].get("expected_unit"),
}
}
if hectares_data["citation"]:
project["offchain_citations"] = [hectares_data["citation"]]
enriched_count += 1
else:
# No valid derivation available (blocked)
# Do NOT add any metric - "no citation, no metric"
pass
if enriched_count > 0:
logger.info(f"Enriched {enriched_count} projects with offchain metrics")
return projects, warnings
# ============================================================================
# Enums for query parameters
# ============================================================================
class GovParamsType(str, Enum):
voting = "voting"
deposit = "deposit"
tally = "tally"
all = "all"
class ProposalStatus(str, Enum):
unspecified = "PROPOSAL_STATUS_UNSPECIFIED"
deposit_period = "PROPOSAL_STATUS_DEPOSIT_PERIOD"
voting_period = "PROPOSAL_STATUS_VOTING_PERIOD"
passed = "PROPOSAL_STATUS_PASSED"
rejected = "PROPOSAL_STATUS_REJECTED"
failed = "PROPOSAL_STATUS_FAILED"
# ============================================================================
# FastAPI App
# ============================================================================
app = FastAPI(
title="Regen Network API v2",
description="""Query Regen Network blockchain for ecological credits, carbon markets, governance, and staking.
## Full Functionality in 25 Endpoints
This API consolidates 45+ queries into 26 smart endpoints using query parameters:
### Modules
- **Ecocredits** (5): Credit types, classes, projects, batches, class supply/retirement
- **Marketplace** (2): Sell orders (flexible filtering), allowed denoms
- **Baskets** (3): Basket tokens with optional balance inclusion
- **Bank** (5): Accounts, balances, supply, metadata, params
- **Distribution** (4): Staking rewards, validator info, delegator info
- **Governance** (4): Proposals, voting, params, community pool
- **Analytics** (3): Portfolio analysis, market trends, methodology comparison
### Smart Query Parameters
Many endpoints accept optional parameters to filter or expand results:
- `?id=` - Get specific item instead of list
- `?include_X=true` - Include related data in response
- `?denom=` / `?batch=` / `?seller=` - Filter by specific values
All queries access public blockchain data (read-only).
""",
version="2.0.0",
servers=[
{"url": "https://regen.gaiaai.xyz/regen-api", "description": "Production API"}
],
)
app.add_middleware(
CORSMiddleware,
allow_origins=["https://chat.openai.com", "https://chatgpt.com", "*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Add Request ID middleware for X-Request-ID header support
app.add_middleware(RequestIDMiddleware)
# ============================================================================
# Exception Handlers
# ============================================================================
@app.exception_handler(TransientError)
async def transient_error_handler(request: Request, exc: TransientError):
"""Handle transient errors with 503 status and retryable flag."""
request_id = getattr(request.state, "request_id", get_request_id())
error_response = create_error_envelope(
request_id=request_id,
code=exc.code,
message=exc.message,
retryable=True,
retry_after_ms=exc.retry_after_ms,
details=exc.details,
warnings=["This is a transient error. Please retry after the suggested delay."]
)
# Keep error responses consistent with the standard envelope fields used for metrics.
error_response["data_source"] = DataSource.ON_CHAIN
response = JSONResponse(
status_code=503,
content=error_response,
)
response.headers["X-Request-ID"] = request_id
response.headers["Retry-After"] = str(exc.retry_after_ms // 1000) # seconds
return response
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""Handle HTTP exceptions with structured error response."""
request_id = getattr(request.state, "request_id", get_request_id())
# Determine if this might be a transient error based on status code
retryable = exc.status_code in (502, 503, 504)
error_response = create_error_envelope(
request_id=request_id,
code=f"HTTP_{exc.status_code}",
message=str(exc.detail),
retryable=retryable,
retry_after_ms=5000 if retryable else None,
)
# Keep error responses consistent with the standard envelope fields used for metrics.
error_response["data_source"] = DataSource.ON_CHAIN
response = JSONResponse(
status_code=exc.status_code,
content=error_response,
)
response.headers["X-Request-ID"] = request_id
return response
# ============================================================================
# ROOT (1 endpoint)
# ============================================================================
@app.get("/", summary="API Info", tags=["Info"])
async def api_info():
"""Get API information and available endpoints."""
return {
"name": "Regen Network API v2",
"version": "2.0.0",
"description": "Full Regen Network blockchain access - 45 queries consolidated into 26 endpoints",
"endpoints": 26,
"modules": {
"ecocredits": 5,
"marketplace": 2,
"baskets": 3,
"bank": 5,
"distribution": 4,
"governance": 4,
"analytics": 3,
}
}
@app.get("/unified-openapi.json", summary="Combined OpenAPI Schema", tags=["Info"], include_in_schema=False)
async def get_combined_openapi():
"""Get combined OpenAPI schema for both Ledger API and KOI Knowledge API.
Use this schema when you need a single ChatGPT Action that can access both:
- Regen Ledger API (/regen-api/*) - blockchain data
- KOI Knowledge API (/api/koi/*) - semantic search
"""
schema_path = Path(__file__).parent / "openapi-combined.json"
if not schema_path.exists():
raise HTTPException(status_code=404, detail="Combined schema not found")
with open(schema_path) as f:
return json.load(f)
@app.get("/summary", summary="API capabilities summary", tags=["Discovery"])
async def get_api_summary():
"""Get a complete summary of all API capabilities.
CALL THIS FIRST to understand what information is available.
Returns organized list of all endpoints grouped by function.
"""
summary = {
"name": "Regen Network Unified API",
"description": "Query Regen Network blockchain data AND search 6,500+ documents about regenerative agriculture",
"tip": "For questions about concepts, history, or 'what is X', use Knowledge Search. For live blockchain data, use Ledger endpoints. For 'this week', 'past week', or 'recent news', use Weekly Digest.",
"capabilities": {
"weekly_digest": {
"description": "Curated weekly summary of Regen Network ecosystem activity",
"when_to_use": "ALWAYS use for: 'this week', 'past week', 'this past week', 'recent news', 'recent activity', 'what's happening', 'summarize the week', 'weekly update', any time-based summary",
"endpoints": {
"GET /api/koi/weekly-digest": "Weekly summary - USE THIS for any 'week' or 'recent' questions"
}
},
"knowledge_search": {
"description": "Search 6,500+ documents about Regen Network, regenerative agriculture, carbon credits, and ecological finance",
"when_to_use": "Questions about concepts, explanations, history, 'what is', 'how does', background information",
"endpoints": {
"POST /api/koi/query": "Semantic search - ask any question in natural language",
"POST /api/koi/entity": "Entity queries - resolve entity names, get relationships, find related documents (use query_type: resolve|neighborhood|documents)"
}
},
"ecological_credits": {
"description": "Query live blockchain data about carbon credits, biodiversity credits, and ecological assets",
"when_to_use": "Questions about current credit types, classes, projects, batches, prices, supply",
"endpoints": {
"GET /regen-api/ecocredits/types": "List all credit types (Carbon, Biodiversity, etc.)",
"GET /regen-api/ecocredits/classes": "List credit classes (methodologies)",
"GET /regen-api/ecocredits/projects": "List registered ecological projects",
"GET /regen-api/ecocredits/batches": "List issued credit batches with supply info",
"GET /regen-api/ecocredits/classes/{class_id}/supply": "Retirement & supply stats for a credit class (total_retired, retirement_rate_pct)"
}
},
"marketplace": {
"description": "Query carbon credit marketplace - sell orders, prices, trading",
"when_to_use": "Questions about buying credits, current prices, sell orders, market activity",
"endpoints": {
"GET /regen-api/marketplace/orders": "Query sell orders (filter by id, batch, seller)",
"GET /regen-api/marketplace/denoms": "Accepted payment tokens"
}
},
"baskets": {
"description": "Query basket tokens - pooled ecological credits",
"when_to_use": "Questions about NCT, basket tokens, pooled credits",
"endpoints": {
"GET /regen-api/baskets": "List all basket tokens",
"GET /regen-api/baskets/{denom}": "Get basket details and contents",
"GET /regen-api/baskets/fee": "Basket creation fee"
}
},
"accounts_and_balances": {
"description": "Query Regen accounts, token balances, and supply",
"when_to_use": "Questions about specific addresses, holdings, token supply",
"endpoints": {
"GET /regen-api/bank/balances/{address}": "Get account token balances",
"GET /regen-api/bank/accounts": "Query accounts",
"GET /regen-api/bank/supply": "Total token supply",
"GET /regen-api/bank/metadata": "Token metadata"
}
},
"staking_and_rewards": {
"description": "Query staking rewards, validators, delegations",
"when_to_use": "Questions about staking, validators, rewards, delegations",
"endpoints": {
"GET /regen-api/distribution/pool": "Community pool balance",
"GET /regen-api/distribution/validator/{address}": "Validator rewards and commission",
"GET /regen-api/distribution/delegator/{address}": "Delegator staking rewards"
}
},
"governance": {
"description": "Query governance proposals, voting, community decisions",
"when_to_use": "Questions about proposals, voting, governance decisions",
"endpoints": {
"GET /regen-api/governance/proposals": "List/filter proposals",
"GET /regen-api/governance/proposal/{id}/full": "Full proposal with votes and deposits",
"GET /regen-api/governance/params": "Governance parameters"
}
},
"analytics": {
"description": "Analyze portfolios, market trends, and compare methodologies",
"when_to_use": "Questions about trends, portfolio analysis, methodology comparison",
"endpoints": {
"GET /regen-api/analytics/trends": "Market trends by credit type",
"GET /regen-api/analytics/portfolio/{address}": "Portfolio ecological impact",
"POST /regen-api/analytics/compare": "Compare credit methodologies"
}
}
}
}
add_tool_trace(create_tool_trace(
tool="get_api_summary",
params={},
data_source=DataSource.CACHED,
duration_ms=0,
allowlisted_params=[],
))
return create_envelope(
data=summary,
request_id=get_request_id(),
data_source=DataSource.CACHED,
)
# ============================================================================
# ECOCREDITS (4 endpoints) - With response envelope
# ============================================================================
@app.get("/ecocredits/types", summary="List credit types", tags=["Ecocredits"])
async def list_credit_types(request: Request):
"""List all ecological credit types enabled on Regen (Carbon, Biodiversity, etc.)."""
start_time = time.time()
result = await credit_tools.list_credit_types()
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
# Add tool trace
trace = create_tool_trace(
tool="list_credit_types",
params={},
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
return create_envelope(
data=result,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN,
)
@app.get("/ecocredits/classes", summary="List credit classes", tags=["Ecocredits"])
async def list_credit_classes(
request: Request,
limit: int = Query(100, ge=1, le=500, description="Max results to return"),
offset: int = Query(0, ge=0, description="Number of results to skip"),
):
"""List credit classes (methodologies for measuring ecological benefits)."""
start_time = time.time()
result = await credit_tools.list_credit_classes(limit, offset)
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
trace = create_tool_trace(
tool="list_credit_classes",
params={"limit": limit, "offset": offset},
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
pagination = extract_pagination_from_response(result, offset, limit)
return create_envelope(
data=result,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN,
pagination=pagination,
)
@app.get("/ecocredits/projects", summary="List projects", tags=["Ecocredits"])
async def list_projects(
request: Request,
limit: int = Query(100, ge=1, le=500, description="Max results to return"),
offset: int = Query(0, ge=0, description="Number of results to skip"),
include_offchain_metrics: bool = Query(
False,
description="Enrich projects with off-chain hectares from metadata IRIs. Enforces 'no citation, no metric' policy."
),
):
"""List ecological projects registered on Regen that generate credits.
When include_offchain_metrics=true, projects with Regen metadata IRIs will be
enriched with hectares derived from off-chain metadata. Enforces 'no citation,
no metric' - hectares only appear with full provenance.
"""
start_time = time.time()
result = await credit_tools.list_projects(limit, offset)
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
# Optional off-chain enrichment
enrichment_warnings: List[str] = []
if include_offchain_metrics and result.get("projects"):
projects = result["projects"]
enriched_projects, enrichment_warnings = await enrich_projects_with_offchain_metrics(projects)
result["projects"] = enriched_projects
trace = create_tool_trace(
tool="list_projects",
params={"limit": limit, "offset": offset, "include_offchain_metrics": include_offchain_metrics},
data_source=DataSource.ON_CHAIN if not include_offchain_metrics else DataSource.METADATA,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
pagination = extract_pagination_from_response(result, offset, limit)
envelope = create_envelope(
data=result,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN if not include_offchain_metrics else DataSource.METADATA,
pagination=pagination,
)
# Add enrichment warnings to envelope if any
if enrichment_warnings:
envelope["warnings"] = enrichment_warnings
return envelope
@app.get("/ecocredits/batches", summary="List credit batches", tags=["Ecocredits"])
async def list_credit_batches(
request: Request,
limit: int = Query(100, ge=1, le=500, description="Max results to return"),
offset: int = Query(0, ge=0, description="Number of results to skip"),
summary: bool = Query(
False,
description="Return aggregate summary by credit type instead of individual batches. "
"Reduces pagination loops for analytics use cases."
),
fetch_all: bool = Query(
False,
description="When summary=true, fetch all pages to compute complete totals. "
"Without this, summary is computed from first page only. Max 50 pages."
),
):
"""List issued credit batches with vintage dates and supply info.
Options:
- Default: Returns paginated list of individual batches
- ?summary=true: Returns aggregate summary by credit type (totals for issued/tradable/retired)
- ?summary=true&fetch_all=true: Fetches all pages to compute complete summary totals
The summary mode is designed to reduce agent-side pagination loops for common analytics.
"""
start_time = time.time()
warnings: List[str] = []
if summary:
# Summary mode: aggregate batches by credit type with real supply data
from mcp_server.client.regen_client import get_regen_client
client = get_regen_client()
if fetch_all:
# Fetch all pages using the pagination helper
fetch_result = await client.fetch_all_pages(
path="/regen/ecocredit/v1/batches",
page_size=100,
max_pages=MAX_BATCH_PAGES, # Safety cap
item_key="batches",
)
batches = fetch_result["items"]
warnings.extend(fetch_result.get("warnings", []))
if not fetch_result["exhausted"]:
warnings.append(
f"PAGINATION_NOT_EXHAUSTED: Summary computed from {fetch_result['pages_fetched']} pages "
f"({len(batches)} batches). Total may be higher."
)
total_batches = fetch_result.get("total") or len(batches)
else:
# Single page only
result = await credit_tools.list_credit_batches(limit, offset)
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
batches = result.get("batches", [])
total_batches = len(batches)
warnings.append(
f"PARTIAL_SUMMARY: Summary computed from first page only ({len(batches)} batches). "
"Use fetch_all=true for complete totals."
)
# === SUPPLY ENRICHMENT: Fetch real supply data for batches ===
# Extract batch denoms for supply lookup
batch_denoms = [b.get("denom") for b in batches if b.get("denom")]
# Apply MAX_SUPPLY_BATCHES cap
supply_capped = False
if len(batch_denoms) > MAX_SUPPLY_BATCHES:
supply_capped = True
batch_denoms = batch_denoms[:MAX_SUPPLY_BATCHES]
warnings.append(
f"SUPPLY_BATCHES_CAPPED: Supply data fetched for first {MAX_SUPPLY_BATCHES} batches only. "
f"Total batches: {len(batches)}. Supply totals are partial."
)
# Fetch supply data in bulk with concurrency control
supplies_by_denom: Dict[str, Dict[str, Any]] = {}
supply_fetch_warnings: List[str] = []
if batch_denoms:
supply_result = await client.query_batch_supplies_bulk(
batch_denoms=batch_denoms,
max_concurrent=SUPPLY_MAX_CONCURRENT,
timeout_seconds=SUPPLY_FETCH_TIMEOUT_SECONDS,
)
supplies_by_denom = supply_result.get("supplies", {})
supply_fetch_warnings = supply_result.get("warnings", [])
warnings.extend(supply_fetch_warnings)
if supply_result.get("timed_out"):
warnings.append(
f"SUPPLY_TIMEOUT: Supply fetching timed out. "
f"Only {supply_result['fetched_count']} of {len(batch_denoms)} batches have supply data."
)
# Track how many batches have supply data
batches_with_supply = len(supplies_by_denom)
# Compute summary by credit type using real supply data
summary_by_type: Dict[str, Dict[str, Any]] = {}
def parse_amount(val: Any) -> float:
"""Parse supply amounts (they come as strings)."""
if val is None:
return 0.0
try:
return float(val)
except (ValueError, TypeError):
return 0.0
for batch in batches:
batch_denom = batch.get("denom", "")
# Extract credit type from project_id or denom (e.g., "C01-001" -> "C", "BT01-002" -> "BT")
project_id = batch.get("project_id", "") or batch_denom.split("-")[0] if batch_denom else ""
class_id = project_id.split("-")[0] if project_id else ""
credit_type = "".join(c for c in class_id if c.isalpha())
if not credit_type:
credit_type = "UNKNOWN"
if credit_type not in summary_by_type:
summary_by_type[credit_type] = {
"credit_type": credit_type,
"batch_count": 0,
"total_issued": 0.0,
"total_tradable": 0.0,
"total_retired": 0.0,
"total_cancelled": 0.0,
"class_ids": set(),
"project_ids": set(),
}
summary_by_type[credit_type]["batch_count"] += 1
# Get supply info from the bulk fetch results
supply = supplies_by_denom.get(batch_denom, {})
tradable = parse_amount(supply.get("tradable_amount"))
retired = parse_amount(supply.get("retired_amount"))
cancelled = parse_amount(supply.get("cancelled_amount"))
# Total issued = tradable + retired + cancelled (conservation of credits)
total_issued = tradable + retired + cancelled
summary_by_type[credit_type]["total_issued"] += total_issued
summary_by_type[credit_type]["total_tradable"] += tradable
summary_by_type[credit_type]["total_retired"] += retired
summary_by_type[credit_type]["total_cancelled"] += cancelled
if class_id:
summary_by_type[credit_type]["class_ids"].add(class_id)
if batch.get("project_id"):
summary_by_type[credit_type]["project_ids"].add(batch["project_id"])
# Convert sets to counts for JSON serialization
summary_list = []
for type_data in summary_by_type.values():
type_data["unique_classes"] = len(type_data.pop("class_ids"))
type_data["unique_projects"] = len(type_data.pop("project_ids"))
summary_list.append(type_data)
# Sort by total issued descending
summary_list.sort(key=lambda x: x["total_issued"], reverse=True)
# Add warning if supply totals are incomplete
if batches_with_supply < len(batches) and not supply_capped:
warnings.append(
f"PARTIAL_SUPPLY_DATA: Supply data available for {batches_with_supply} of {len(batches)} batches. "
"Totals may be understated."
)
response_data = {
"summary": summary_list,
"batches_analyzed": len(batches),
"batches_with_supply_data": batches_with_supply,
"total_batches": total_batches,
"aggregation": {
"method": "by_credit_type",
"metrics": ["total_issued", "total_tradable", "total_retired", "total_cancelled"],
"supply_source": "on-chain per-batch supply query",
},
"caps": {
"max_batch_pages": MAX_BATCH_PAGES,
"max_supply_batches": MAX_SUPPLY_BATCHES,
"supply_timeout_seconds": SUPPLY_FETCH_TIMEOUT_SECONDS,
},
}
trace = create_tool_trace(
tool="list_credit_batches_summary",
params={"summary": True, "fetch_all": fetch_all, "batches_with_supply": batches_with_supply},
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
return create_envelope(
data=response_data,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN,
warnings=warnings if warnings else None,
)
# Standard mode: return paginated batches
result = await credit_tools.list_credit_batches(limit, offset)
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
trace = create_tool_trace(
tool="list_credit_batches",
params={"limit": limit, "offset": offset},
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
pagination = extract_pagination_from_response(result, offset, limit)
return create_envelope(
data=result,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN,
pagination=pagination,
)
@app.get(
"/ecocredits/classes/{class_id}/supply",
summary="Get supply and retirement data for a credit class",
tags=["Ecocredits"],
)
async def get_credit_class_supply(class_id: str):
"""Get aggregated supply, tradable, and retired amounts for all batches in a credit class.
Use this to answer questions like:
- "How many MBS01 credits have been retired?"
- "What is the retirement rate for C01?"
- "How many credits are tradable vs retired for MBS01?"
Returns total_issued, total_tradable, total_retired, retirement_rate_pct,
and a per-batch breakdown.
"""
start_time = time.time()
result = await credit_tools.get_credit_class_supply(class_id)
if "error" in result:
raise HTTPException(status_code=404, detail=result["error"])
trace = create_tool_trace(
tool="get_credit_class_supply",
params={"class_id": class_id},
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
return create_envelope(
data=result,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN,
)
# ============================================================================
# MARKETPLACE (2 endpoints) - Consolidated from 5, with response envelope
# ============================================================================
@app.get("/marketplace/orders", summary="Query sell orders", tags=["Marketplace"])
async def query_marketplace_orders(
request: Request,
id: Optional[int] = Query(None, description="Get specific order by ID"),
batch: Optional[str] = Query(None, description="Filter orders by credit batch denom"),
seller: Optional[str] = Query(None, description="Filter orders by seller address"),
page: int = Query(1, ge=1, description="Page number"),
limit: int = Query(100, ge=1, le=200, description="Results per page"),
):
"""Query marketplace sell orders. Use query params to filter:
- No params: List all active orders
- ?id=123: Get specific order by ID
- ?batch=C01-001-...: Filter orders for a credit batch
- ?seller=regen1...: Filter orders by seller address
"""
start_time = time.time()
offset = (page - 1) * limit
if id is not None:
result = await marketplace_tools.get_sell_order(id)
tool_name = "get_sell_order"
params = {"id": id}
elif batch is not None:
result = await marketplace_tools.list_sell_orders_by_batch(batch, limit=limit, offset=offset)
tool_name = "list_sell_orders_by_batch"
params = {"batch": batch, "limit": limit, "offset": offset}
elif seller is not None:
result = await marketplace_tools.list_sell_orders_by_seller(seller, limit=limit, offset=offset)
tool_name = "list_sell_orders_by_seller"
params = {"seller": seller, "limit": limit, "offset": offset}
else:
result = await marketplace_tools.list_sell_orders(limit=limit, offset=offset)
tool_name = "list_sell_orders"
params = {"limit": limit, "offset": offset}
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
trace = create_tool_trace(
tool=tool_name,
params=params,
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
pagination = extract_pagination_from_response(result, offset, limit) if id is None else None
return create_envelope(
data=result,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN,
pagination=pagination,
)
@app.get("/marketplace/denoms", summary="Allowed payment tokens", tags=["Marketplace"])
async def list_allowed_denoms(request: Request):
"""List token denominations accepted for marketplace payments."""
start_time = time.time()
result = await marketplace_tools.list_allowed_denoms()
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
trace = create_tool_trace(
tool="list_allowed_denoms",
params={},
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
return create_envelope(
data=result,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN,
)
# ============================================================================
# BASKETS (3 endpoints) - Consolidated from 5, with response envelope
# ============================================================================
@app.get("/baskets", summary="List baskets", tags=["Baskets"])
async def list_baskets(
request: Request,
limit: int = Query(100, ge=1, le=500, description="Max results to return"),
offset: int = Query(0, ge=0, description="Number of results to skip"),
):
"""List ecocredit baskets (pooled credits represented as fungible tokens)."""
start_time = time.time()
result = await basket_tools.list_baskets(limit, offset)
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
trace = create_tool_trace(
tool="list_baskets",
params={"limit": limit, "offset": offset},
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
pagination = extract_pagination_from_response(result, offset, limit)
return create_envelope(
data=result,
request_id=get_request_id(),
data_source=DataSource.ON_CHAIN,
pagination=pagination,
)
@app.get("/baskets/fee", summary="Basket creation fee", tags=["Baskets"])
async def get_basket_fee(request: Request):
"""Get the fee required to create a new ecocredit basket."""
start_time = time.time()
result = await basket_tools.get_basket_fee()
if "error" in result:
if is_transient_error(result["error"]):
raise TransientError(message=result["error"], code="UPSTREAM_ERROR")
raise HTTPException(status_code=400, detail=result["error"])
trace = create_tool_trace(
tool="get_basket_fee",
params={},
data_source=DataSource.ON_CHAIN,
duration_ms=(time.time() - start_time) * 1000
)
add_tool_trace(trace)
return create_envelope(