m2mcent-crewai 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: m2mcent-crewai
3
+ Version: 1.0.0
4
+ Summary: Herramientas oficiales de M2MCent (x402) nativas para CrewAI.
5
+ Author: M2MCent
6
+ Author-email: dev@m2mcent.com
7
+ Requires-Python: >=3.9
8
+ Requires-Dist: crewai>=0.20.0
9
+ Requires-Dist: requests>=2.25.1
10
+ Requires-Dist: eth-account>=0.9.0
11
+ Requires-Dist: pydantic>=2.0.0
12
+ Dynamic: author
13
+ Dynamic: author-email
14
+ Dynamic: requires-dist
15
+ Dynamic: requires-python
16
+ Dynamic: summary
@@ -0,0 +1,3 @@
1
+ from .tools import M2MCentBaseTool
2
+
3
+ __all__ = ["M2MCentBaseTool"]
@@ -0,0 +1,147 @@
1
+ import os
2
+ import re
3
+ import time
4
+ import json
5
+ import base64
6
+ import secrets
7
+ import requests
8
+ from typing import Any, Optional
9
+ from pydantic import Field
10
+ from crewai.tools import BaseTool
11
+ from eth_account import Account
12
+ from eth_account.messages import encode_typed_data
13
+
14
+ class M2MCentBaseTool(BaseTool):
15
+ """
16
+ Herramienta base para interactuar con el ecosistema de Nodos de M2MCent.
17
+ Abstrae completamente el pago x402 (EIP-3009) en Base L2, con soporte dual:
18
+ Web2 (API Key Custodial para empresas SOC2) o Web3 (Private Key Soberana).
19
+ """
20
+
21
+ api_url: str = Field(..., description="Endpoint del nodo M2MCent")
22
+ api_key: Optional[str] = Field(default=None, description="API Key para clientes corporativos Web2")
23
+ private_key: Optional[str] = Field(default=None, description="Llave privada para Agentes Web3")
24
+
25
+ def _run(self, **kwargs) -> Any:
26
+ try:
27
+ # Recuperar credenciales (Prioridad: Atributos de clase -> Variables de entorno)
28
+ resolved_api_key = self.api_key or os.environ.get("M2MCENT_API_KEY")
29
+
30
+ headers = {}
31
+ if resolved_api_key:
32
+ # MODO WEB2: Backend gestiona el x402 invisiblemente.
33
+ headers["Authorization"] = f"Bearer {resolved_api_key}"
34
+
35
+ # 1. Petición inicial (Descubrimiento o Ejecución Autorizada)
36
+ response = requests.post(self.api_url, json=kwargs, headers=headers)
37
+
38
+ if response.status_code == 200:
39
+ return self._extract_useful_data(response.json())
40
+
41
+ elif response.status_code == 402:
42
+ # 2. Atrapa el muro de pago (Requiere firma Web3 Local)
43
+ return self._handle_x402_payment_and_retry(response, kwargs)
44
+
45
+ else:
46
+ raise Exception(f"HTTP {response.status_code}: {response.text}")
47
+
48
+ except Exception as e:
49
+ # PARCHE 3: Empatía de errores y Bloqueo de Tracebacks al LLM
50
+ return (
51
+ "M2MCent Error: Fondos insuficientes o credenciales inválidas. "
52
+ "Por favor, recarga tu saldo USDC o tu API Key en https://m2mcent.com"
53
+ )
54
+
55
+ def _handle_x402_payment_and_retry(self, response: requests.Response, original_payload: dict) -> str:
56
+ resolved_private_key = self.private_key or os.environ.get("M2MCENT_WALLET_PRIVATE_KEY")
57
+ if not resolved_private_key:
58
+ raise Exception("No API Key or Private Key provided for payment.")
59
+
60
+ payment_header = response.headers.get("Payment-Required", "")
61
+
62
+ # PARCHE 1: Parseo Robusto del Base64 (Defensa contra binascii.Error)
63
+ match = re.search(r'schema="([^"]+)"', payment_header)
64
+ if not match:
65
+ raise Exception("Schema x402 no encontrado en la cabecera HTTP 402.")
66
+
67
+ raw_b64 = match.group(1)
68
+ raw_b64 += "=" * ((4 - len(raw_b64) % 4) % 4) # Corregir padding
69
+
70
+ schema = json.loads(base64.b64decode(raw_b64).decode('utf-8'))
71
+ verifying_contract = schema["contract"]
72
+ pay_to = schema["payTo"]
73
+ amount_raw = int(schema["amountRaw"])
74
+
75
+ # Formatear y firmar EIP-3009 (Delegación sin Gas)
76
+ payment_signature = self._sign_eip3009(
77
+ resolved_private_key,
78
+ verifying_contract,
79
+ pay_to,
80
+ amount_raw
81
+ )
82
+
83
+ # Inyectar cabecera de liquidación y reintentar
84
+ headers = {"Payment-Signature": payment_signature}
85
+ retry_response = requests.post(self.api_url, json=original_payload, headers=headers)
86
+
87
+ if retry_response.status_code == 200:
88
+ return self._extract_useful_data(retry_response.json())
89
+ else:
90
+ raise Exception("La liquidación x402 falló en el Relayer.")
91
+
92
+ def _sign_eip3009(self, private_key: str, verifying_contract: str, pay_to: str, amount_raw: int) -> str:
93
+ """Crea la firma criptográfica para gastar USDC sin necesitar ETH para gas."""
94
+ account = Account.from_key(private_key)
95
+
96
+ # PARCHE 2: Blindaje Criptográfico (Clock Drift, Ventana de Riesgo y CSRNG)
97
+ valid_after = 0
98
+ valid_before = int(time.time()) + 180 # Expiración máxima: 3 minutos
99
+ nonce = "0x" + secrets.token_hex(32) # Hex string seguro
100
+
101
+ # Dominio EIP-712 de USDC en Base L2
102
+ domain = {
103
+ "name": "USD Coin",
104
+ "version": "2",
105
+ "chainId": 8453,
106
+ "verifyingContract": verifying_contract
107
+ }
108
+
109
+ # PARCHE 2: TransferWithAuthorization (Soporte Relayer Tercero)
110
+ types = {
111
+ "TransferWithAuthorization": [
112
+ {"name": "from", "type": "address"},
113
+ {"name": "to", "type": "address"},
114
+ {"name": "value", "type": "uint256"},
115
+ {"name": "validAfter", "type": "uint256"},
116
+ {"name": "validBefore", "type": "uint256"},
117
+ {"name": "nonce", "type": "bytes32"},
118
+ ]
119
+ }
120
+
121
+ message = {
122
+ "from": account.address,
123
+ "to": pay_to,
124
+ "value": amount_raw,
125
+ "validAfter": valid_after,
126
+ "validBefore": valid_before,
127
+ "nonce": nonce
128
+ }
129
+
130
+ # Firmar atómicamente
131
+ signable_message = encode_typed_data(domain_data=domain, message_types=types, message_data=message)
132
+ signed_message = account.sign_message(signable_message)
133
+
134
+ # Retornar envoltorio Base64 estándar esperado por el Gateway M2MCent
135
+ payload = {
136
+ "authorization": message,
137
+ "signature": signed_message.signature.hex()
138
+ }
139
+ return base64.b64encode(json.dumps(payload).encode()).decode()
140
+
141
+ def _extract_useful_data(self, json_response: dict) -> str:
142
+ """Filtra metadatos transaccionales y devuelve solo la carnaza útil para CrewAI."""
143
+ if "data" in json_response:
144
+ return json.dumps(json_response["data"], indent=2)
145
+ if "result" in json_response:
146
+ return str(json_response["result"])
147
+ return json.dumps(json_response, indent=2)
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: m2mcent-crewai
3
+ Version: 1.0.0
4
+ Summary: Herramientas oficiales de M2MCent (x402) nativas para CrewAI.
5
+ Author: M2MCent
6
+ Author-email: dev@m2mcent.com
7
+ Requires-Python: >=3.9
8
+ Requires-Dist: crewai>=0.20.0
9
+ Requires-Dist: requests>=2.25.1
10
+ Requires-Dist: eth-account>=0.9.0
11
+ Requires-Dist: pydantic>=2.0.0
12
+ Dynamic: author
13
+ Dynamic: author-email
14
+ Dynamic: requires-dist
15
+ Dynamic: requires-python
16
+ Dynamic: summary
@@ -0,0 +1,8 @@
1
+ setup.py
2
+ m2mcent_crewai/__init__.py
3
+ m2mcent_crewai/tools.py
4
+ m2mcent_crewai.egg-info/PKG-INFO
5
+ m2mcent_crewai.egg-info/SOURCES.txt
6
+ m2mcent_crewai.egg-info/dependency_links.txt
7
+ m2mcent_crewai.egg-info/requires.txt
8
+ m2mcent_crewai.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ crewai>=0.20.0
2
+ requests>=2.25.1
3
+ eth-account>=0.9.0
4
+ pydantic>=2.0.0
@@ -0,0 +1 @@
1
+ m2mcent_crewai
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,17 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="m2mcent-crewai",
5
+ version="1.0.0",
6
+ description="Herramientas oficiales de M2MCent (x402) nativas para CrewAI.",
7
+ author="M2MCent",
8
+ author_email="dev@m2mcent.com",
9
+ packages=find_packages(),
10
+ install_requires=[
11
+ "crewai>=0.20.0",
12
+ "requests>=2.25.1",
13
+ "eth-account>=0.9.0",
14
+ "pydantic>=2.0.0"
15
+ ],
16
+ python_requires=">=3.9",
17
+ )