agent0-sdk 0.2.2__py3-none-any.whl → 0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tests/test_models.py DELETED
@@ -1,224 +0,0 @@
1
- """
2
- Tests for core models.
3
- """
4
-
5
- import pytest
6
- from datetime import datetime
7
-
8
- from agent0_sdk.core.models import (
9
- EndpointType, TrustModel, Endpoint, RegistrationFile,
10
- AgentSummary, Feedback, SearchParams
11
- )
12
-
13
-
14
- class TestEndpointType:
15
- """Test EndpointType enum."""
16
-
17
- def test_endpoint_types(self):
18
- """Test endpoint type values."""
19
- assert EndpointType.MCP.value == "MCP"
20
- assert EndpointType.A2A.value == "A2A"
21
- assert EndpointType.ENS.value == "ENS"
22
- assert EndpointType.DID.value == "DID"
23
-
24
-
25
- class TestTrustModel:
26
- """Test TrustModel enum."""
27
-
28
- def test_trust_models(self):
29
- """Test trust model values."""
30
- assert TrustModel.REPUTATION.value == "reputation"
31
- assert TrustModel.CRYPTO_ECONOMIC.value == "crypto-economic"
32
- assert TrustModel.TEE_ATTESTATION.value == "tee-attestation"
33
-
34
-
35
- class TestEndpoint:
36
- """Test Endpoint class."""
37
-
38
- def test_endpoint_creation(self):
39
- """Test endpoint creation."""
40
- endpoint = Endpoint(
41
- type=EndpointType.MCP,
42
- value="https://mcp.example.com/",
43
- meta={"version": "1.0"}
44
- )
45
-
46
- assert endpoint.type == EndpointType.MCP
47
- assert endpoint.value == "https://mcp.example.com/"
48
- assert endpoint.meta == {"version": "1.0"}
49
-
50
- def test_endpoint_default_meta(self):
51
- """Test endpoint with default meta."""
52
- endpoint = Endpoint(type=EndpointType.A2A, value="https://a2a.example.com/")
53
- assert endpoint.meta == {}
54
-
55
-
56
- class TestRegistrationFile:
57
- """Test RegistrationFile class."""
58
-
59
- def test_registration_file_creation(self):
60
- """Test registration file creation."""
61
- rf = RegistrationFile(
62
- name="Test Agent",
63
- description="A test agent",
64
- image="https://example.com/image.png"
65
- )
66
-
67
- assert rf.name == "Test Agent"
68
- assert rf.description == "A test agent"
69
- assert rf.image == "https://example.com/image.png"
70
- assert rf.active is False
71
- assert rf.x402support is False
72
- assert rf.endpoints == []
73
- assert rf.trustModels == []
74
-
75
- def test_registration_file_to_dict(self):
76
- """Test conversion to dictionary."""
77
- rf = RegistrationFile(
78
- name="Test Agent",
79
- description="A test agent",
80
- image="https://example.com/image.png",
81
- agentId="1:123",
82
- endpoints=[
83
- Endpoint(type=EndpointType.MCP, value="https://mcp.example.com/")
84
- ],
85
- trustModels=[TrustModel.REPUTATION]
86
- )
87
-
88
- data = rf.to_dict()
89
-
90
- assert data["name"] == "Test Agent"
91
- assert data["description"] == "A test agent"
92
- assert data["image"] == "https://example.com/image.png"
93
- assert data["type"] == "https://eips.ethereum.org/EIPS/eip-8004#registration-v1"
94
- assert data["x402support"] is False
95
- assert len(data["endpoints"]) == 1
96
- assert data["endpoints"][0]["name"] == "MCP"
97
- assert data["endpoints"][0]["endpoint"] == "https://mcp.example.com/"
98
- assert data["supportedTrust"] == ["reputation"]
99
-
100
- def test_registration_file_from_dict(self):
101
- """Test creation from dictionary."""
102
- data = {
103
- "name": "Test Agent",
104
- "description": "A test agent",
105
- "image": "https://example.com/image.png",
106
- "endpoints": [
107
- {
108
- "name": "MCP",
109
- "endpoint": "https://mcp.example.com/",
110
- "version": "1.0"
111
- }
112
- ],
113
- "supportedTrust": ["reputation"],
114
- "x402support": True
115
- }
116
-
117
- rf = RegistrationFile.from_dict(data)
118
-
119
- assert rf.name == "Test Agent"
120
- assert rf.description == "A test agent"
121
- assert rf.image == "https://example.com/image.png"
122
- assert rf.x402support is True
123
- assert len(rf.endpoints) == 1
124
- assert rf.endpoints[0].type == EndpointType.MCP
125
- assert rf.endpoints[0].value == "https://mcp.example.com/"
126
- assert rf.endpoints[0].meta == {"version": "1.0"}
127
- assert len(rf.trustModels) == 1
128
- assert rf.trustModels[0] == TrustModel.REPUTATION
129
-
130
-
131
- class TestAgentSummary:
132
- """Test AgentSummary class."""
133
-
134
- def test_agent_summary_creation(self):
135
- """Test agent summary creation."""
136
- summary = AgentSummary(
137
- chainId=1,
138
- agentId="1:123",
139
- name="Test Agent",
140
- image="https://example.com/image.png",
141
- description="A test agent",
142
- owners=["0x123"],
143
- operators=["0x456"],
144
- mcp=True,
145
- a2a=False,
146
- ens="test.eth",
147
- did=None,
148
- walletAddress="0x789",
149
- supportedTrusts=["onchain_feedback_v1"],
150
- a2aSkills=[],
151
- mcpTools=["tool1"],
152
- mcpPrompts=[],
153
- mcpResources=[],
154
- active=True
155
- )
156
-
157
- assert summary.chainId == 1
158
- assert summary.agentId == "1:123"
159
- assert summary.name == "Test Agent"
160
- assert summary.mcp is True
161
- assert summary.a2a is False
162
- assert summary.ens == "test.eth"
163
- assert summary.did is None
164
-
165
-
166
- class TestFeedback:
167
- """Test Feedback class."""
168
-
169
- def test_feedback_creation(self):
170
- """Test feedback creation."""
171
- feedback = Feedback(
172
- id=("1:123", "0x456", 1),
173
- agentId="1:123",
174
- reviewer="0x456",
175
- score=4.5,
176
- tags=["quality", "speed"],
177
- text="Great service!",
178
- capability="tools"
179
- )
180
-
181
- assert feedback.id == ("1:123", "0x456", 1)
182
- assert feedback.id_string == "1:123:0x456:1"
183
- assert feedback.agentId == "1:123"
184
- assert feedback.reviewer == "0x456"
185
- assert feedback.score == 4.5
186
- assert feedback.tags == ["quality", "speed"]
187
- assert feedback.text == "Great service!"
188
- assert feedback.capability == "tools"
189
-
190
-
191
- class TestSearchParams:
192
- """Test SearchParams class."""
193
-
194
- def test_search_params_creation(self):
195
- """Test search params creation."""
196
- params = SearchParams(
197
- name="test",
198
- mcp=True,
199
- a2a=False,
200
- active=True,
201
- x402support=True
202
- )
203
-
204
- assert params.name == "test"
205
- assert params.mcp is True
206
- assert params.a2a is False
207
- assert params.active is True
208
- assert params.x402support is True
209
- assert params.chains is None
210
-
211
- def test_search_params_to_dict(self):
212
- """Test conversion to dictionary."""
213
- params = SearchParams(
214
- name="test",
215
- mcp=True,
216
- chains=[1, 8453]
217
- )
218
-
219
- data = params.to_dict()
220
-
221
- assert data["name"] == "test"
222
- assert data["mcp"] is True
223
- assert data["chains"] == [1, 8453]
224
- assert "a2a" not in data # None values should be excluded
@@ -1,103 +0,0 @@
1
- """
2
- Test Endpoint Crawler with Real Public MCP and A2A Servers
3
- Tests against actual public servers provided by the user.
4
- """
5
-
6
- import logging
7
- import sys
8
- import os
9
-
10
- # Configure logging: root logger at WARNING to suppress noisy dependencies
11
- logging.basicConfig(
12
- level=logging.WARNING,
13
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
14
- datefmt='%Y-%m-%d %H:%M:%S',
15
- handlers=[logging.StreamHandler(sys.stdout)]
16
- )
17
-
18
- # Set debug level ONLY for agent0_sdk
19
- logging.getLogger('agent0_sdk').setLevel(logging.DEBUG)
20
- logging.getLogger('agent0_sdk.core').setLevel(logging.DEBUG)
21
-
22
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
23
-
24
- from agent0_sdk.core.endpoint_crawler import EndpointCrawler
25
- import json
26
-
27
- def main():
28
- print("🧪 Testing Endpoint Crawler with Real Public Servers")
29
- print("=" * 70)
30
-
31
- crawler = EndpointCrawler(timeout=10) # Longer timeout for real servers
32
-
33
- # Real public endpoints
34
- test_cases = [
35
- {
36
- "type": "A2A",
37
- "endpoint": "https://hello-world-gxfr.onrender.com",
38
- "description": "Real A2A Hello World Server"
39
- },
40
- {
41
- "type": "MCP",
42
- "endpoint": "https://mcp.atlassian.com/v1/forge/mcp",
43
- "description": "Atlassian MCP Server (requires authentication, will fail gracefully)"
44
- }
45
- ]
46
-
47
- successful_tests = []
48
- failed_tests = []
49
-
50
- for i, test_case in enumerate(test_cases, 1):
51
- print(f"\n📍 Test {i}: {test_case['type']} Endpoint")
52
- print("-" * 70)
53
- print(f"URL: {test_case['endpoint']}")
54
- print(f"Description: {test_case['description']}")
55
- print()
56
-
57
- if test_case['type'] == 'A2A':
58
- capabilities = crawler.fetch_a2a_capabilities(test_case['endpoint'])
59
- if capabilities:
60
- print("✅ SUCCESS! Fetched A2A capabilities:")
61
- print(json.dumps(capabilities, indent=2))
62
- successful_tests.append(test_case)
63
- else:
64
- print("❌ Failed to fetch A2A capabilities")
65
- failed_tests.append(test_case)
66
-
67
- elif test_case['type'] == 'MCP':
68
- capabilities = crawler.fetch_mcp_capabilities(test_case['endpoint'])
69
- if capabilities:
70
- print("✅ SUCCESS! Fetched MCP capabilities:")
71
- print(json.dumps(capabilities, indent=2))
72
- successful_tests.append(test_case)
73
- else:
74
- print("❌ Failed to fetch MCP capabilities")
75
- failed_tests.append(test_case)
76
-
77
- # Summary
78
- print("\n" + "=" * 70)
79
- print("📊 Summary")
80
- print("-" * 70)
81
- print(f"✅ Successful: {len(successful_tests)}")
82
- print(f"❌ Failed: {len(failed_tests)}")
83
-
84
- if successful_tests:
85
- print("\n✅ Successfully tested endpoints:")
86
- for test in successful_tests:
87
- print(f" - {test['type']}: {test['endpoint']}")
88
-
89
- if failed_tests:
90
- print("\n⚠️ Failed endpoints:")
91
- for test in failed_tests:
92
- print(f" - {test['type']}: {test['endpoint']}")
93
-
94
- print("\n" + "=" * 70)
95
- if successful_tests:
96
- print("🎉 Endpoint crawler is working with real public servers!")
97
- else:
98
- print("⚠️ No capabilities fetched. Check endpoints or network connection.")
99
- print("=" * 70)
100
-
101
- if __name__ == "__main__":
102
- main()
103
-
@@ -1,267 +0,0 @@
1
- """
2
- Test for Agent Registration with HTTP URI
3
- Creates an agent, registers it with a mock HTTP URI, updates it, and verifies data integrity.
4
-
5
- Flow:
6
- 1. Register agent on-chain with mock URI (obtain agentId)
7
- 2. Prepare registration file with obtained agentId
8
- 3. Print registration file JSON for developer to host
9
- 4. Update agent and verify consistency
10
- """
11
-
12
- import logging
13
- import time
14
- import random
15
- import json
16
- import sys
17
-
18
- # Configure logging: root logger at WARNING to suppress noisy dependencies
19
- logging.basicConfig(
20
- level=logging.WARNING,
21
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
22
- datefmt='%Y-%m-%d %H:%M:%S',
23
- handlers=[logging.StreamHandler(sys.stdout)]
24
- )
25
-
26
- # Set debug level ONLY for agent0_sdk
27
- logging.getLogger('agent0_sdk').setLevel(logging.DEBUG)
28
- logging.getLogger('agent0_sdk.core').setLevel(logging.DEBUG)
29
-
30
- from agent0_sdk import SDK
31
- from config import CHAIN_ID, RPC_URL, AGENT_PRIVATE_KEY, print_config
32
-
33
-
34
- def generateRandomData():
35
- """Generate random test data for the agent."""
36
- randomSuffix = random.randint(1000, 9999)
37
- timestamp = int(time.time())
38
-
39
- return {
40
- 'name': f"Test Agent {randomSuffix}",
41
- 'description': f"Created at {timestamp}",
42
- 'image': f"https://example.com/image_{randomSuffix}.png",
43
- 'mcpEndpoint': f"https://api.example.com/mcp/{randomSuffix}",
44
- 'mcpVersion': f"2025-06-{random.randint(1, 28)}",
45
- 'a2aEndpoint': f"https://api.example.com/a2a/{randomSuffix}.json",
46
- 'a2aVersion': f"0.{random.randint(30, 35)}",
47
- 'ensName': f"test{randomSuffix}.eth",
48
- 'ensVersion': f"1.{random.randint(0, 9)}",
49
- 'walletAddress': f"0x{'a' * 40}",
50
- 'walletChainId': random.choice([1, 11155111, 8453, 137, 42161]),
51
- 'active': True,
52
- 'x402support': False,
53
- 'reputation': random.choice([True, False]),
54
- 'cryptoEconomic': random.choice([True, False]),
55
- 'teeAttestation': random.choice([True, False])
56
- }
57
-
58
-
59
- def main():
60
- print("🧪 Testing Agent Registration with HTTP URI")
61
- print_config()
62
-
63
- # SDK Configuration - no IPFS
64
- sdkConfig = {
65
- 'chainId': CHAIN_ID,
66
- 'rpcUrl': RPC_URL
67
- }
68
-
69
- sdk = SDK(signer=AGENT_PRIVATE_KEY, **sdkConfig)
70
- testData = generateRandomData()
71
-
72
- # Step 1: Register agent on-chain with mock HTTP URI
73
- print("\n📍 Step 1: Register Agent on-Chain with Mock URI")
74
- print("-" * 60)
75
-
76
- agent = sdk.createAgent(
77
- name=testData['name'],
78
- description=testData['description'],
79
- image=testData['image']
80
- )
81
-
82
- # Register with mock URI to get agentId
83
- mockUri = "https://example.com/agents/registration.json"
84
- agent.register(mockUri)
85
- agentId = agent.agentId
86
- print(f"✅ Registered: ID={agentId}")
87
- print(f" Mock URI: {mockUri}")
88
-
89
- # Step 2: Configure agent with all details
90
- print("\n📍 Step 2: Configure Agent Details")
91
- print("-" * 60)
92
- print(f"✅ Created: {testData['name']}")
93
-
94
- agent.setMCP(testData['mcpEndpoint'], testData['mcpVersion'])
95
- agent.setA2A(testData['a2aEndpoint'], testData['a2aVersion'])
96
- agent.setENS(testData['ensName'], testData['ensVersion'])
97
- agent.setAgentWallet(testData['walletAddress'], testData['walletChainId'])
98
- agent.setActive(testData['active'])
99
- agent.setX402Support(testData['x402support'])
100
- agent.setTrust(
101
- reputation=testData['reputation'],
102
- cryptoEconomic=testData['cryptoEconomic'],
103
- teeAttestation=testData['teeAttestation']
104
- )
105
-
106
- # Step 3: Get registration file and print it
107
- print("\n📍 Step 3: Registration File for Hosting")
108
- print("-" * 60)
109
-
110
- registrationFile = agent.getRegistrationFile()
111
- registrationJson = json.dumps(registrationFile.to_dict(), indent=2)
112
-
113
- print("Registration file JSON (host this at the URL you specified):")
114
- print("\n" + registrationJson)
115
-
116
- # Save to file
117
- filename = f"agent_registration_{agentId.replace(':', '_')}.json"
118
- with open(filename, 'w') as f:
119
- f.write(registrationJson)
120
- print(f"\n✅ Saved to: {filename}")
121
-
122
- capturedState = {
123
- 'agentId': agent.agentId,
124
- 'agentURI': agent.agentURI,
125
- 'name': agent.name,
126
- 'description': agent.description,
127
- 'image': agent.image,
128
- 'walletAddress': agent.walletAddress,
129
- 'walletChainId': agent.walletChainId,
130
- 'active': agent.active,
131
- 'x402support': agent.x402support,
132
- 'mcpEndpoint': agent.mcpEndpoint,
133
- 'a2aEndpoint': agent.a2aEndpoint,
134
- 'ensEndpoint': agent.ensEndpoint,
135
- 'metadata': agent.metadata.copy()
136
- }
137
-
138
- # Step 4: Update agent
139
- print("\n📍 Step 4: Update Agent")
140
- print("-" * 60)
141
-
142
- agent.updateInfo(
143
- name=testData['name'] + " UPDATED",
144
- description=testData['description'] + " - UPDATED",
145
- image=f"https://example.com/image_{random.randint(1000, 9999)}_updated.png"
146
- )
147
- agent.setMCP(f"https://api.example.com/mcp/{random.randint(10000, 99999)}", f"2025-06-{random.randint(1, 28)}")
148
- agent.setA2A(f"https://api.example.com/a2a/{random.randint(10000, 99999)}.json", f"0.{random.randint(30, 35)}")
149
- agent.setAgentWallet(f"0x{'b' * 40}", random.choice([1, 11155111, 8453, 137, 42161]))
150
- agent.setENS(f"{testData['ensName']}.updated", f"1.{random.randint(0, 9)}")
151
- agent.setActive(False)
152
- agent.setX402Support(True)
153
- agent.setTrust(
154
- reputation=random.choice([True, False]),
155
- cryptoEconomic=random.choice([True, False]),
156
- teeAttestation=random.choice([True, False])
157
- )
158
- agent.setMetadata({
159
- "testKey": "testValue",
160
- "timestamp": int(time.time()),
161
- "customField": "customValue",
162
- "anotherField": "anotherValue",
163
- "numericField": random.randint(1000, 9999)
164
- })
165
-
166
- # Update registration file and re-register
167
- registrationFileUpdated = agent.getRegistrationFile()
168
- registrationJsonUpdated = json.dumps(registrationFileUpdated.to_dict(), indent=2)
169
-
170
- filenameUpdated = f"agent_registration_{agentId.replace(':', '_')}_updated.json"
171
- with open(filenameUpdated, 'w') as f:
172
- f.write(registrationJsonUpdated)
173
-
174
- agent.register(mockUri)
175
- print(f"✅ Updated & re-registered")
176
- print(f" Updated registration file: {filenameUpdated}")
177
-
178
- # Capture updated state
179
- updatedState = {
180
- 'name': agent.name,
181
- 'description': agent.description,
182
- 'image': agent.image,
183
- 'walletAddress': agent.walletAddress,
184
- 'walletChainId': agent.walletChainId,
185
- 'active': agent.active,
186
- 'x402support': agent.x402support,
187
- 'mcpEndpoint': agent.mcpEndpoint,
188
- 'a2aEndpoint': agent.a2aEndpoint,
189
- 'ensEndpoint': agent.ensEndpoint,
190
- 'metadata': agent.metadata.copy()
191
- }
192
-
193
- # Step 5: Reload and verify
194
- print("\n📍 Step 5: Reload and Verify")
195
- print("-" * 60)
196
-
197
- reloadedAgentId = agent.agentId
198
- del agent
199
- print("⏳ Waiting for blockchain transaction to be mined (15 seconds)...")
200
- time.sleep(15)
201
- reloadedAgent = sdk.loadAgent(reloadedAgentId)
202
- print(f"✅ Reloaded from blockchain")
203
-
204
- reloadedState = {
205
- 'name': reloadedAgent.name,
206
- 'description': reloadedAgent.description,
207
- 'image': reloadedAgent.image,
208
- 'walletAddress': reloadedAgent.walletAddress,
209
- 'walletChainId': reloadedAgent.walletChainId,
210
- 'active': reloadedAgent.active,
211
- 'x402support': reloadedAgent.x402support,
212
- 'mcpEndpoint': reloadedAgent.mcpEndpoint,
213
- 'a2aEndpoint': reloadedAgent.a2aEndpoint,
214
- 'ensEndpoint': reloadedAgent.ensEndpoint,
215
- 'metadata': reloadedAgent.metadata.copy()
216
- }
217
-
218
- expectedState = updatedState
219
- expectedState['walletAddress'] = f"0x{'b' * 40}"
220
- expectedState['walletChainId'] = sdk.chainId
221
-
222
- allMatch = True
223
- for field, expected in expectedState.items():
224
- actual = reloadedState.get(field)
225
-
226
- # Handle type casting for metadata fields
227
- if field == 'metadata' and isinstance(actual, dict) and isinstance(expected, dict):
228
- normalized_actual = {}
229
- for k, v in actual.items():
230
- if k in expected:
231
- expected_val = expected[k]
232
- if isinstance(expected_val, int):
233
- try:
234
- normalized_actual[k] = int(v) if isinstance(v, str) else v
235
- except (ValueError, TypeError):
236
- normalized_actual[k] = v
237
- elif isinstance(expected_val, float):
238
- try:
239
- normalized_actual[k] = float(v) if isinstance(v, str) else v
240
- except (ValueError, TypeError):
241
- normalized_actual[k] = v
242
- else:
243
- normalized_actual[k] = v
244
- else:
245
- normalized_actual[k] = v
246
- actual = normalized_actual
247
-
248
- if actual == expected:
249
- print(f"✅ {field}: {actual}")
250
- else:
251
- print(f"❌ {field}: expected={expected}, got={actual}")
252
- allMatch = False
253
-
254
- if allMatch:
255
- print("\n✅ ALL CHECKS PASSED")
256
- else:
257
- print("\n❌ SOME CHECKS FAILED")
258
-
259
-
260
- if __name__ == "__main__":
261
- try:
262
- main()
263
- except Exception as e:
264
- print(f"\n❌ Error: {e}")
265
- import traceback
266
- traceback.print_exc()
267
- exit(1)