grains-sdk 0.1.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: grains-sdk
3
+ Version: 0.1.0
4
+ Summary: The Python framework for building Grains agents (hosted AI agents with a signed identity that can charge per call).
5
+ Author: Grains
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://grains.run
8
+ Project-URL: Documentation, https://grains.run/docs.html
9
+ Project-URL: Repository, https://github.com/0000F8/grains
10
+ Keywords: ai,agents,llm,claude,mcp,x402,hosting
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: crypto
22
+ Requires-Dist: ecdsa>=0.18; extra == "crypto"
23
+ Requires-Dist: pycryptodome>=3.19; extra == "crypto"
24
+ Dynamic: license-file
25
+
26
+ # grains-sdk
27
+
28
+ The Python framework for building [Grains](https://grains.run) agents — deploy
29
+ AI agents that run hosted, get a signed cryptographic identity, and can charge
30
+ per call.
31
+
32
+ Bring your own brain (a Claude/GPT loop, CrewAI, LangChain, a rules engine —
33
+ anything); the SDK is the thin, zero-dependency contract between your handler
34
+ and the Grains platform.
35
+
36
+ ```python
37
+ from grains import agent
38
+
39
+ @agent.handler
40
+ def handle(task):
41
+ return task.reply("echo: " + task.text)
42
+ ```
43
+
44
+ Deploy it with the [`grains` CLI](https://pypi.org/project/grains-cli/) or from
45
+ inside Claude with [`grains-mcp`](https://pypi.org/project/grains-mcp/).
46
+
47
+ ## Install
48
+
49
+ ```bash
50
+ pip install grains-sdk # core (no runtime deps)
51
+ pip install "grains-sdk[crypto]" # + offline receipt/identity verification
52
+ ```
53
+
54
+ ## API
55
+
56
+ - `@agent.handler` — register your handler (sync or async); it receives a
57
+ `Task` and returns `task.reply(...)`.
58
+ - `Task` — `.text`, `.payload`, `.reply(text, **data)`, `.charge(value,
59
+ currency="USDC")` (amounts are decimal strings, never floats).
60
+ - `agent.tools(format="json"|"langchain"|"crewai")` — expose the platform
61
+ actions (`request_payment`, `check_balance`, `get_identity`) to your agent
62
+ framework.
63
+ - `grains.crypto` (with `[crypto]`) — offline verification of Grains identity
64
+ documents and payment receipts.
65
+
66
+ Docs: https://grains.run/docs.html · License: Apache-2.0
@@ -0,0 +1,41 @@
1
+ # grains-sdk
2
+
3
+ The Python framework for building [Grains](https://grains.run) agents — deploy
4
+ AI agents that run hosted, get a signed cryptographic identity, and can charge
5
+ per call.
6
+
7
+ Bring your own brain (a Claude/GPT loop, CrewAI, LangChain, a rules engine —
8
+ anything); the SDK is the thin, zero-dependency contract between your handler
9
+ and the Grains platform.
10
+
11
+ ```python
12
+ from grains import agent
13
+
14
+ @agent.handler
15
+ def handle(task):
16
+ return task.reply("echo: " + task.text)
17
+ ```
18
+
19
+ Deploy it with the [`grains` CLI](https://pypi.org/project/grains-cli/) or from
20
+ inside Claude with [`grains-mcp`](https://pypi.org/project/grains-mcp/).
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install grains-sdk # core (no runtime deps)
26
+ pip install "grains-sdk[crypto]" # + offline receipt/identity verification
27
+ ```
28
+
29
+ ## API
30
+
31
+ - `@agent.handler` — register your handler (sync or async); it receives a
32
+ `Task` and returns `task.reply(...)`.
33
+ - `Task` — `.text`, `.payload`, `.reply(text, **data)`, `.charge(value,
34
+ currency="USDC")` (amounts are decimal strings, never floats).
35
+ - `agent.tools(format="json"|"langchain"|"crewai")` — expose the platform
36
+ actions (`request_payment`, `check_balance`, `get_identity`) to your agent
37
+ framework.
38
+ - `grains.crypto` (with `[crypto]`) — offline verification of Grains identity
39
+ documents and payment receipts.
40
+
41
+ Docs: https://grains.run/docs.html · License: Apache-2.0
@@ -0,0 +1,56 @@
1
+ """grains-sdk: `@agent.handler`, `Task`, and tool adapters. Stdlib only."""
2
+ from __future__ import annotations
3
+
4
+ import inspect
5
+ from typing import Callable
6
+
7
+ from .task import Charge, Reply, Task
8
+ from .tools import get_tools
9
+
10
+ __all__ = ["agent", "Task", "Reply", "Charge"]
11
+
12
+
13
+ class _Agent:
14
+ """Process-wide handler registry — exactly one handler per process.
15
+
16
+ Re-registering (calling @agent.handler again) replaces the previous
17
+ handler, matching a single Lambda/worker process running one agent.
18
+ """
19
+
20
+ def __init__(self):
21
+ self._handler: Callable | None = None
22
+
23
+ def handler(self, func: Callable) -> Callable:
24
+ self._handler = func
25
+ return func
26
+
27
+ def get_handler(self) -> Callable | None:
28
+ return self._handler
29
+
30
+ def tools(self, format: str = "json") -> list:
31
+ return get_tools(format)
32
+
33
+ async def invoke(self, task: Task) -> Reply:
34
+ """Run the registered handler (sync or async) and normalize its result."""
35
+ handler = self._handler
36
+ if handler is None:
37
+ raise RuntimeError("no handler registered; use @agent.handler")
38
+ if inspect.iscoroutinefunction(handler):
39
+ result = await handler(task)
40
+ else:
41
+ result = handler(task)
42
+ if isinstance(result, Reply):
43
+ return result
44
+ if isinstance(result, str):
45
+ return task.reply(result)
46
+ if result is None:
47
+ if task.replies:
48
+ return task.replies[-1]
49
+ raise TypeError(
50
+ "handler returned None and recorded no reply - did you forget "
51
+ "`return task.reply(...)`?"
52
+ )
53
+ raise TypeError(f"handler must return a Reply or str, got {type(result).__name__}")
54
+
55
+
56
+ agent = _Agent()
@@ -0,0 +1,181 @@
1
+ """grains-sdk crypto: identity (secp256k1 did:key) and receipt primitives.
2
+
3
+ Implements spec/identity.md and spec/receipts.md, matching
4
+ spec/tools/generate_vectors.py exactly. Requires the `crypto` extra
5
+ (`ecdsa`, `pycryptodome`); imports of those libraries are deferred into the
6
+ functions that need them so importing this module never requires them.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import hashlib
12
+ import json
13
+ from datetime import datetime
14
+ from typing import Callable
15
+
16
+ _B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
17
+ _DID_PREFIX = "did:key:z"
18
+ _MULTICODEC_SECP256K1 = b"\xe7\x01"
19
+
20
+
21
+ def canonical(doc: dict) -> bytes:
22
+ """Canonical signing bytes per spec/identity.md §4 (`sig` field removed)."""
23
+ doc = {k: v for k, v in doc.items() if k != "sig"}
24
+ return json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
25
+ "utf-8"
26
+ )
27
+
28
+
29
+ def _b58encode(data: bytes) -> str:
30
+ n = int.from_bytes(data, "big")
31
+ out = ""
32
+ while n:
33
+ n, r = divmod(n, 58)
34
+ out = _B58_ALPHABET[r] + out
35
+ pad = 0
36
+ for b in data:
37
+ if b == 0:
38
+ pad += 1
39
+ else:
40
+ break
41
+ return "1" * pad + out
42
+
43
+
44
+ def _b58decode(s: str) -> bytes:
45
+ n = 0
46
+ for ch in s:
47
+ n = n * 58 + _B58_ALPHABET.index(ch)
48
+ raw = n.to_bytes((n.bit_length() + 7) // 8, "big")
49
+ pad = len(s) - len(s.lstrip("1"))
50
+ return b"\x00" * pad + raw
51
+
52
+
53
+ def pubkey_to_did(compressed: bytes) -> str:
54
+ """secp256k1 compressed pubkey (33 bytes) -> did:key (spec/identity.md §2)."""
55
+ return _DID_PREFIX + _b58encode(_MULTICODEC_SECP256K1 + compressed)
56
+
57
+
58
+ def did_to_pubkey(did: str) -> bytes:
59
+ """did:key -> secp256k1 compressed pubkey (reverse of spec/identity.md §2)."""
60
+ if not did.startswith(_DID_PREFIX):
61
+ raise ValueError(f"not a did:key: {did!r}")
62
+ decoded = _b58decode(did[len(_DID_PREFIX):])
63
+ if decoded[:2] != _MULTICODEC_SECP256K1:
64
+ raise ValueError("not a secp256k1-pub did:key")
65
+ return decoded[2:]
66
+
67
+
68
+ def pubkey_to_evm_address(uncompressed: bytes) -> str:
69
+ """secp256k1 uncompressed pubkey (65 bytes) -> EVM address (spec/identity.md §3)."""
70
+ from Crypto.Hash import keccak
71
+
72
+ k = keccak.new(digest_bits=256)
73
+ k.update(uncompressed[1:])
74
+ return "0x" + k.digest()[-20:].hex()
75
+
76
+
77
+ def sign_doc(doc: dict, signer: Callable[[bytes], bytes], did: str) -> dict:
78
+ """Sign `doc` and return its `sig` object per spec/identity.md §5.
79
+
80
+ `signer` receives the SHA-256 digest of the canonical bytes and must
81
+ return a 64-byte r||s signature -- this is the shared call shape for
82
+ both local (ecdsa) and KMS signing.
83
+ """
84
+ digest = hashlib.sha256(canonical(doc)).digest()
85
+ raw = signer(digest)
86
+ value = base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
87
+ return {"alg": "ES256K", "kid": did, "value": value}
88
+
89
+
90
+ def _verify_sig(doc: dict) -> "object | None":
91
+ """Verify a document's `sig` against the key named by `sig.kid`.
92
+
93
+ Returns the VerifyingKey on success, else None. Enforces strict low-s
94
+ (§5, no signature malleability) and fails closed on any malformed input.
95
+ Does NOT check who kid belongs to -- that binding is the caller's, and
96
+ differs for identity docs (kid == did) vs receipts (kid == payee).
97
+ """
98
+ from ecdsa import BadSignatureError, SECP256k1, VerifyingKey
99
+ from ecdsa.errors import MalformedPointError
100
+
101
+ sig = doc.get("sig")
102
+ if not isinstance(sig, dict) or sig.get("alg") != "ES256K":
103
+ return None
104
+ try:
105
+ vk = VerifyingKey.from_string(did_to_pubkey(sig["kid"]), curve=SECP256k1)
106
+ raw = base64.urlsafe_b64decode(sig["value"] + "=" * (-len(sig["value"]) % 4))
107
+ if len(raw) != 64:
108
+ return None
109
+ if int.from_bytes(raw[32:], "big") > SECP256k1.order // 2:
110
+ return None
111
+ if not vk.verify(raw, canonical(doc), hashfunc=hashlib.sha256):
112
+ return None
113
+ return vk
114
+ except (BadSignatureError, MalformedPointError, ValueError, KeyError, TypeError):
115
+ return None
116
+
117
+
118
+ def verify_doc(doc: dict) -> bool:
119
+ """Self-contained identity-document verification per spec/identity.md §7.
120
+
121
+ Enforces: valid signature (§5, low-s); sig.kid == doc.did (step 2); and,
122
+ for every rail binding claiming the root key, that the bound address
123
+ re-derives from the signing key (step 3). Fails closed.
124
+ """
125
+ from ecdsa.errors import MalformedPointError
126
+
127
+ # §7 step 2: the signer's key MUST be the document's own DID.
128
+ if not isinstance(doc.get("sig"), dict) or doc["sig"].get("kid") != doc.get("did"):
129
+ return False
130
+ vk = _verify_sig(doc)
131
+ if vk is None:
132
+ return False
133
+
134
+ # §7 step 3: a rail binding sharing the root key must match a re-derived
135
+ # address, or a valid signature could still direct funds anywhere.
136
+ try:
137
+ expected = pubkey_to_evm_address(b"\x04" + vk.to_string("uncompressed")[-64:])
138
+ except (MalformedPointError, ValueError):
139
+ return False
140
+ for binding in doc.get("bindings", []):
141
+ if isinstance(binding, dict) and binding.get("type") == "rail":
142
+ addr = binding.get("address")
143
+ if isinstance(addr, str) and addr.lower() != expected.lower():
144
+ return False
145
+ return True
146
+
147
+
148
+ def verify_receipt(receipt: dict) -> tuple[bool, str]:
149
+ """Offline verification per spec/receipts.md §2 steps 1-4."""
150
+ payee_identity = receipt.get("payee_identity")
151
+ if not isinstance(payee_identity, dict):
152
+ return False, "missing payee_identity"
153
+ if not verify_doc(payee_identity):
154
+ return False, "payee_identity signature invalid"
155
+
156
+ did = payee_identity.get("did")
157
+ sig = receipt.get("sig") or {}
158
+ if not (receipt.get("payee") == did == sig.get("kid")):
159
+ return False, "payee / payee_identity.did / sig.kid mismatch"
160
+
161
+ if _verify_sig(receipt) is None:
162
+ return False, "receipt signature invalid"
163
+
164
+ amount = receipt.get("amount") or {}
165
+ value = amount.get("value")
166
+ decimals = amount.get("decimals")
167
+ if not isinstance(value, str) or not isinstance(decimals, int):
168
+ return False, "amount malformed"
169
+ whole, sep, frac = value.partition(".")
170
+ if not sep or len(frac) != decimals or not frac.isdigit() or not whole.lstrip("-").isdigit():
171
+ return False, "amount.value malformed for decimals"
172
+
173
+ try:
174
+ datetime.fromisoformat(str(receipt.get("issued_at", "")).replace("Z", "+00:00"))
175
+ except ValueError:
176
+ return False, "issued_at malformed"
177
+
178
+ if receipt.get("type") != "payment":
179
+ return False, "unknown receipt type"
180
+
181
+ return True, "VERIFIED (offline)"
@@ -0,0 +1,43 @@
1
+ """Task, Reply, and Charge — the SDK's core data shapes."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass
8
+ class Reply:
9
+ text: str
10
+ data: dict
11
+
12
+
13
+ @dataclass
14
+ class Charge:
15
+ # value is a decimal string (e.g. "1.50"), never a float — see spec/identity.md.
16
+ value: str
17
+ currency: str
18
+
19
+ def __post_init__(self) -> None:
20
+ if not isinstance(self.value, str):
21
+ raise TypeError(
22
+ f"charge value must be a decimal string, not {type(self.value).__name__} "
23
+ "(amounts are never floats)"
24
+ )
25
+
26
+
27
+ class Task:
28
+ def __init__(self, id: str, text: str, payload: dict | None = None):
29
+ self.id = id
30
+ self.text = text
31
+ self.payload = payload if payload is not None else {}
32
+ self.replies: list[Reply] = []
33
+ self.charges: list[Charge] = []
34
+
35
+ def reply(self, text: str, **data) -> Reply:
36
+ r = Reply(text=text, data=data)
37
+ self.replies.append(r)
38
+ return r
39
+
40
+ def charge(self, value: str, currency: str = "USDC") -> Charge:
41
+ c = Charge(value=value, currency=currency)
42
+ self.charges.append(c)
43
+ return c
@@ -0,0 +1,104 @@
1
+ """Agent tool definitions and framework adapters.
2
+
3
+ M1: tool executors are stubs — real payment/identity wiring lands with the
4
+ control plane (M2+). Definitions themselves are stable JSON Schema so agent
5
+ authors can start writing tool-using prompts today.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ TOOL_DEFS = [
10
+ {
11
+ "name": "request_payment",
12
+ "description": "Request a payment from the caller for work this agent performed.",
13
+ "input_schema": {
14
+ "type": "object",
15
+ "properties": {
16
+ "amount": {
17
+ "type": "string",
18
+ "description": "Decimal amount as a string, e.g. \"1.50\" (never a float).",
19
+ },
20
+ "currency": {
21
+ "type": "string",
22
+ "description": "Currency code.",
23
+ "default": "USDC",
24
+ },
25
+ "reason": {
26
+ "type": "string",
27
+ "description": "Human-readable reason for the charge.",
28
+ },
29
+ },
30
+ "required": ["amount"],
31
+ },
32
+ },
33
+ {
34
+ "name": "check_balance",
35
+ "description": "Check this agent's current wallet balance.",
36
+ "input_schema": {
37
+ "type": "object",
38
+ "properties": {
39
+ "currency": {
40
+ "type": "string",
41
+ "description": "Currency code to check.",
42
+ "default": "USDC",
43
+ },
44
+ },
45
+ "required": [],
46
+ },
47
+ },
48
+ {
49
+ "name": "get_identity",
50
+ "description": "Get this agent's signed identity document (did:key, wallet address).",
51
+ "input_schema": {
52
+ "type": "object",
53
+ "properties": {},
54
+ "required": [],
55
+ },
56
+ },
57
+ ]
58
+
59
+
60
+ def _stub_executor(**_kwargs) -> dict:
61
+ return {"status": "unavailable_in_local_dev"}
62
+
63
+
64
+ def get_tools(format: str = "json") -> list:
65
+ if format == "json":
66
+ return [dict(t) for t in TOOL_DEFS]
67
+ if format == "langchain":
68
+ return _wrap_langchain()
69
+ if format == "crewai":
70
+ return _wrap_crewai()
71
+ raise ValueError(f"unknown tools format: {format!r}")
72
+
73
+
74
+ def _wrap_langchain() -> list:
75
+ try:
76
+ from langchain_core.tools import StructuredTool
77
+ except ImportError as e:
78
+ raise ImportError(
79
+ "the 'langchain' tools format requires the 'langchain-core' package "
80
+ "(pip install langchain-core)"
81
+ ) from e
82
+ return [
83
+ StructuredTool.from_function(
84
+ func=_stub_executor,
85
+ name=t["name"],
86
+ description=t["description"],
87
+ )
88
+ for t in TOOL_DEFS
89
+ ]
90
+
91
+
92
+ def _wrap_crewai() -> list:
93
+ try:
94
+ from crewai.tools import BaseTool
95
+ except ImportError as e:
96
+ raise ImportError(
97
+ "the 'crewai' tools format requires the 'crewai' package (pip install crewai)"
98
+ ) from e
99
+
100
+ class _StubTool(BaseTool):
101
+ def _run(self, **kwargs) -> dict:
102
+ return _stub_executor(**kwargs)
103
+
104
+ return [_StubTool(name=t["name"], description=t["description"]) for t in TOOL_DEFS]
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: grains-sdk
3
+ Version: 0.1.0
4
+ Summary: The Python framework for building Grains agents (hosted AI agents with a signed identity that can charge per call).
5
+ Author: Grains
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://grains.run
8
+ Project-URL: Documentation, https://grains.run/docs.html
9
+ Project-URL: Repository, https://github.com/0000F8/grains
10
+ Keywords: ai,agents,llm,claude,mcp,x402,hosting
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: crypto
22
+ Requires-Dist: ecdsa>=0.18; extra == "crypto"
23
+ Requires-Dist: pycryptodome>=3.19; extra == "crypto"
24
+ Dynamic: license-file
25
+
26
+ # grains-sdk
27
+
28
+ The Python framework for building [Grains](https://grains.run) agents — deploy
29
+ AI agents that run hosted, get a signed cryptographic identity, and can charge
30
+ per call.
31
+
32
+ Bring your own brain (a Claude/GPT loop, CrewAI, LangChain, a rules engine —
33
+ anything); the SDK is the thin, zero-dependency contract between your handler
34
+ and the Grains platform.
35
+
36
+ ```python
37
+ from grains import agent
38
+
39
+ @agent.handler
40
+ def handle(task):
41
+ return task.reply("echo: " + task.text)
42
+ ```
43
+
44
+ Deploy it with the [`grains` CLI](https://pypi.org/project/grains-cli/) or from
45
+ inside Claude with [`grains-mcp`](https://pypi.org/project/grains-mcp/).
46
+
47
+ ## Install
48
+
49
+ ```bash
50
+ pip install grains-sdk # core (no runtime deps)
51
+ pip install "grains-sdk[crypto]" # + offline receipt/identity verification
52
+ ```
53
+
54
+ ## API
55
+
56
+ - `@agent.handler` — register your handler (sync or async); it receives a
57
+ `Task` and returns `task.reply(...)`.
58
+ - `Task` — `.text`, `.payload`, `.reply(text, **data)`, `.charge(value,
59
+ currency="USDC")` (amounts are decimal strings, never floats).
60
+ - `agent.tools(format="json"|"langchain"|"crewai")` — expose the platform
61
+ actions (`request_payment`, `check_balance`, `get_identity`) to your agent
62
+ framework.
63
+ - `grains.crypto` (with `[crypto]`) — offline verification of Grains identity
64
+ documents and payment receipts.
65
+
66
+ Docs: https://grains.run/docs.html · License: Apache-2.0
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ grains/__init__.py
5
+ grains/crypto.py
6
+ grains/task.py
7
+ grains/tools.py
8
+ grains_sdk.egg-info/PKG-INFO
9
+ grains_sdk.egg-info/SOURCES.txt
10
+ grains_sdk.egg-info/dependency_links.txt
11
+ grains_sdk.egg-info/requires.txt
12
+ grains_sdk.egg-info/top_level.txt
13
+ tests/test_crypto.py
14
+ tests/test_handler.py
15
+ tests/test_task.py
16
+ tests/test_tools.py
@@ -0,0 +1,4 @@
1
+
2
+ [crypto]
3
+ ecdsa>=0.18
4
+ pycryptodome>=3.19
@@ -0,0 +1 @@
1
+ grains
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "grains-sdk"
7
+ version = "0.1.0"
8
+ description = "The Python framework for building Grains agents (hosted AI agents with a signed identity that can charge per call)."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ authors = [{ name = "Grains" }]
12
+ keywords = ["ai", "agents", "llm", "claude", "mcp", "x402", "hosting"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Developers",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Topic :: Software Development :: Libraries",
21
+ ]
22
+ requires-python = ">=3.10"
23
+ dependencies = []
24
+
25
+ [project.optional-dependencies]
26
+ crypto = ["ecdsa>=0.18", "pycryptodome>=3.19"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://grains.run"
30
+ Documentation = "https://grains.run/docs.html"
31
+ Repository = "https://github.com/0000F8/grains"
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["grains*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,155 @@
1
+ """crypto.py round-trips against spec/vectors/*.json -- see spec/tools/generate_vectors.py."""
2
+ import base64
3
+ import copy
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+ from grains import crypto
10
+ from grains.crypto import verify_doc
11
+
12
+ VECTORS = Path(__file__).resolve().parents[2] / "spec" / "vectors"
13
+
14
+
15
+ def load(name):
16
+ return json.loads((VECTORS / name).read_text())
17
+
18
+
19
+ def _local_signer(priv: bytes):
20
+ from ecdsa import SECP256k1, SigningKey
21
+ from ecdsa.util import sigencode_string_canonize
22
+
23
+ sk = SigningKey.from_string(priv, curve=SECP256k1)
24
+
25
+ def signer(digest: bytes) -> bytes:
26
+ return sk.sign_digest_deterministic(
27
+ digest, hashfunc=hashlib.sha256, sigencode=sigencode_string_canonize
28
+ )
29
+
30
+ return signer
31
+
32
+
33
+ def test_key_derivations_match_vector():
34
+ keys = load("keys.json")
35
+ compressed = bytes.fromhex(keys["public_key_compressed_hex"])
36
+ uncompressed = bytes.fromhex(keys["public_key_uncompressed_hex"])
37
+ assert crypto.pubkey_to_did(compressed) == keys["did"]
38
+ assert crypto.did_to_pubkey(keys["did"]) == compressed
39
+ assert crypto.pubkey_to_evm_address(uncompressed) == keys["evm_address"]
40
+
41
+
42
+ def test_sign_doc_matches_vector_exactly():
43
+ keys = load("keys.json")
44
+ priv = bytes.fromhex(keys["private_key_hex"])
45
+ identity = load("identity_doc.json")
46
+ unsigned = {k: v for k, v in identity.items() if k != "sig"}
47
+ signed = crypto.sign_doc(unsigned, _local_signer(priv), keys["did"])
48
+ assert signed == identity["sig"]
49
+
50
+
51
+ def test_identity_doc_verifies():
52
+ identity = load("identity_doc.json")
53
+ assert crypto.verify_doc(identity)
54
+ assert identity["sig"]["kid"] == identity["did"]
55
+
56
+
57
+ def test_receipt_verifies_offline():
58
+ receipt = load("payment_receipt.json")
59
+ ok, reason = crypto.verify_receipt(receipt)
60
+ assert ok, reason
61
+ assert reason == "VERIFIED (offline)"
62
+
63
+
64
+ @pytest.mark.parametrize(
65
+ "mutate",
66
+ [
67
+ lambda d: d.__setitem__("did", d["did"][:-2] + "aa"),
68
+ lambda d: d["sig"].__setitem__("value", d["sig"]["value"][:-2] + "AA"),
69
+ lambda d: d["bindings"][0].__setitem__("address", "0x" + "0" * 40),
70
+ ],
71
+ )
72
+ def test_identity_tamper_fails(mutate):
73
+ identity = copy.deepcopy(load("identity_doc.json"))
74
+ mutate(identity)
75
+ assert not crypto.verify_doc(identity)
76
+
77
+
78
+ @pytest.mark.parametrize(
79
+ "mutate",
80
+ [
81
+ lambda r: r["amount"].__setitem__("value", "9.999999"),
82
+ lambda r: r["tx"].__setitem__("hash", "0x" + "cd" * 32),
83
+ lambda r: r.__setitem__("payee", r["payee"][:-2] + "aa"),
84
+ lambda r: r["sig"].__setitem__("value", r["sig"]["value"][:-2] + "AA"),
85
+ lambda r: r["payee_identity"]["sig"].__setitem__(
86
+ "value", r["payee_identity"]["sig"]["value"][:-2] + "AA"
87
+ ),
88
+ ],
89
+ )
90
+ def test_receipt_tamper_fails(mutate):
91
+ receipt = copy.deepcopy(load("payment_receipt.json"))
92
+ mutate(receipt)
93
+ ok, _reason = crypto.verify_receipt(receipt)
94
+ assert not ok
95
+
96
+
97
+ def test_verify_doc_rejects_missing_sig():
98
+ assert not crypto.verify_doc({"spec": "grains-identity/0.1"})
99
+
100
+
101
+ # --- security regression tests (review findings 2, 6, 7, 8) ---
102
+
103
+
104
+ def test_verify_doc_rejects_kid_did_mismatch():
105
+ # finding 2: sig.kid must equal doc.did
106
+ doc = copy.deepcopy(load("identity_doc.json"))
107
+ doc["sig"]["kid"] = doc["did"][:-4] + "aaaa"
108
+ assert verify_doc(doc) is False
109
+
110
+
111
+ def test_verify_doc_rejects_high_s():
112
+ # finding 6: malleated high-s signature must fail
113
+ from ecdsa import SECP256k1
114
+ doc = copy.deepcopy(load("identity_doc.json"))
115
+ raw = base64.urlsafe_b64decode(doc["sig"]["value"] + "==")
116
+ r = int.from_bytes(raw[:32], "big")
117
+ s = int.from_bytes(raw[32:], "big")
118
+ mall = r.to_bytes(32, "big") + (SECP256k1.order - s).to_bytes(32, "big")
119
+ doc["sig"]["value"] = base64.urlsafe_b64encode(mall).rstrip(b"=").decode()
120
+ assert verify_doc(doc) is False
121
+
122
+
123
+ def test_verify_doc_fails_closed_on_malformed_did():
124
+ # finding 7: MalformedPointError must be caught -> False, not raise
125
+ doc = copy.deepcopy(load("identity_doc.json"))
126
+ doc["did"] = "did:key:zQ3sNOTAVALIDPOINT"
127
+ doc["sig"]["kid"] = doc["did"]
128
+ assert verify_doc(doc) is False
129
+
130
+
131
+ def test_verify_doc_rejects_bogus_rail_address():
132
+ # finding 8: rail binding address must re-derive from the signing key
133
+ from ecdsa import SECP256k1, SigningKey
134
+ from ecdsa.util import sigencode_string_canonize
135
+ from grains.crypto import sign_doc
136
+
137
+ keys = load("keys.json")
138
+ sk = SigningKey.from_string(bytes.fromhex(keys["private_key_hex"]), curve=SECP256k1)
139
+ doc = copy.deepcopy(load("identity_doc.json"))
140
+ for b in doc["bindings"]:
141
+ if b["type"] == "rail":
142
+ b["address"] = "0x000000000000000000000000000000000000dead"
143
+ doc.pop("sig", None)
144
+
145
+ def signer(digest):
146
+ return sk.sign_digest_deterministic(
147
+ digest, hashfunc=hashlib.sha256, sigencode=sigencode_string_canonize
148
+ )
149
+
150
+ doc["sig"] = sign_doc(doc, signer, keys["did"])
151
+ assert verify_doc(doc) is False
152
+
153
+
154
+ def test_verify_doc_still_accepts_genuine():
155
+ assert verify_doc(load("identity_doc.json")) is True
@@ -0,0 +1,100 @@
1
+ import asyncio
2
+
3
+ import pytest
4
+ from grains import Reply, Task, agent
5
+
6
+
7
+ def test_sync_handler_registration_and_reply():
8
+ @agent.handler
9
+ def handle(task: Task):
10
+ return task.reply("sync: " + task.text)
11
+
12
+ assert agent.get_handler() is handle
13
+ task = Task(id="1", text="hi")
14
+ reply = asyncio.run(agent.invoke(task))
15
+ assert reply.text == "sync: hi"
16
+
17
+
18
+ def test_async_handler_registration_and_reply():
19
+ @agent.handler
20
+ async def handle(task: Task):
21
+ return task.reply("async: " + task.text)
22
+
23
+ assert agent.get_handler() is handle
24
+ task = Task(id="2", text="hi")
25
+ reply = asyncio.run(agent.invoke(task))
26
+ assert reply.text == "async: hi"
27
+
28
+
29
+ def test_str_return_is_wrapped_as_reply():
30
+ @agent.handler
31
+ def handle(task: Task):
32
+ return "plain string"
33
+
34
+ task = Task(id="3", text="hi")
35
+ reply = asyncio.run(agent.invoke(task))
36
+ assert isinstance(reply, Reply)
37
+ assert reply.text == "plain string"
38
+ assert task.replies == [reply]
39
+
40
+
41
+ def test_reregistering_replaces_handler():
42
+ @agent.handler
43
+ def first(task: Task):
44
+ return "first"
45
+
46
+ @agent.handler
47
+ def second(task: Task):
48
+ return "second"
49
+
50
+ assert agent.get_handler() is second
51
+ task = Task(id="4", text="hi")
52
+ reply = asyncio.run(agent.invoke(task))
53
+ assert reply.text == "second"
54
+
55
+
56
+ def test_invoke_without_handler_raises():
57
+ agent._handler = None
58
+ task = Task(id="5", text="hi")
59
+ with pytest.raises(RuntimeError):
60
+ asyncio.run(agent.invoke(task))
61
+
62
+
63
+ def test_none_return_with_recorded_reply_uses_it():
64
+ from grains import Task, agent
65
+
66
+ @agent.handler
67
+ def h(task):
68
+ task.reply("recorded")
69
+
70
+ import asyncio
71
+ reply = asyncio.run(agent.invoke(Task(id="t", text="x")))
72
+ assert reply.text == "recorded"
73
+
74
+
75
+ def test_none_return_without_reply_raises():
76
+ import asyncio
77
+
78
+ import pytest
79
+ from grains import Task, agent
80
+
81
+ @agent.handler
82
+ def h(task):
83
+ return None
84
+
85
+ with pytest.raises(TypeError, match="forget"):
86
+ asyncio.run(agent.invoke(Task(id="t", text="x")))
87
+
88
+
89
+ def test_non_reply_return_raises():
90
+ import asyncio
91
+
92
+ import pytest
93
+ from grains import Task, agent
94
+
95
+ @agent.handler
96
+ def h(task):
97
+ return {"oops": True}
98
+
99
+ with pytest.raises(TypeError, match="dict"):
100
+ asyncio.run(agent.invoke(Task(id="t", text="x")))
@@ -0,0 +1,45 @@
1
+ import pytest
2
+ from grains import Task
3
+
4
+
5
+ def test_reply_records_and_returns():
6
+ task = Task(id="t1", text="hello")
7
+ reply = task.reply("hi there", foo="bar")
8
+ assert reply.text == "hi there"
9
+ assert reply.data == {"foo": "bar"}
10
+ assert task.replies == [reply]
11
+
12
+
13
+ def test_charge_records_intent():
14
+ task = Task(id="t1", text="hello")
15
+ charge = task.charge("1.50", currency="USDC")
16
+ assert charge.value == "1.50"
17
+ assert charge.currency == "USDC"
18
+ assert task.charges == [charge]
19
+
20
+
21
+ def test_charge_default_currency():
22
+ task = Task(id="t1", text="hello")
23
+ charge = task.charge("2.00")
24
+ assert charge.currency == "USDC"
25
+
26
+
27
+ def test_charge_rejects_float():
28
+ task = Task(id="t1", text="hello")
29
+ with pytest.raises(TypeError):
30
+ task.charge(1.50)
31
+
32
+
33
+ def test_task_payload_defaults_to_empty_dict():
34
+ task = Task(id="t1", text="hello")
35
+ assert task.payload == {}
36
+ task2 = Task(id="t2", text="hello", payload={"a": 1})
37
+ assert task2.payload == {"a": 1}
38
+
39
+
40
+ def test_charge_dataclass_rejects_float_directly():
41
+ import pytest
42
+ from grains.task import Charge
43
+
44
+ with pytest.raises(TypeError, match="decimal string"):
45
+ Charge(value=1.5, currency="USDC")
@@ -0,0 +1,40 @@
1
+ import pytest
2
+ from grains import agent
3
+
4
+ EXPECTED_NAMES = {"request_payment", "check_balance", "get_identity"}
5
+
6
+
7
+ def test_json_format_returns_three_tools():
8
+ tools = agent.tools(format="json")
9
+ assert len(tools) == 3
10
+ assert {t["name"] for t in tools} == EXPECTED_NAMES
11
+
12
+
13
+ def test_json_format_default():
14
+ assert agent.tools() == agent.tools(format="json")
15
+
16
+
17
+ def test_json_tools_have_valid_schema_keys():
18
+ for tool in agent.tools(format="json"):
19
+ assert set(tool.keys()) == {"name", "description", "input_schema"}
20
+ assert isinstance(tool["name"], str)
21
+ assert isinstance(tool["description"], str)
22
+ schema = tool["input_schema"]
23
+ assert schema["type"] == "object"
24
+ assert "properties" in schema
25
+ assert "required" in schema
26
+
27
+
28
+ def test_langchain_format_raises_import_error_when_missing():
29
+ with pytest.raises(ImportError, match="langchain-core"):
30
+ agent.tools(format="langchain")
31
+
32
+
33
+ def test_crewai_format_raises_import_error_when_missing():
34
+ with pytest.raises(ImportError, match="crewai"):
35
+ agent.tools(format="crewai")
36
+
37
+
38
+ def test_unknown_format_raises_value_error():
39
+ with pytest.raises(ValueError):
40
+ agent.tools(format="bogus")