paygent-agent-sdk 1.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.
Files changed (30) hide show
  1. paygent_agent_sdk-1.1.0/PKG-INFO +307 -0
  2. paygent_agent_sdk-1.1.0/README.md +298 -0
  3. paygent_agent_sdk-1.1.0/paygent_agent/__init__.py +22 -0
  4. paygent_agent_sdk-1.1.0/paygent_agent/canonical.py +42 -0
  5. paygent_agent_sdk-1.1.0/paygent_agent/card.py +77 -0
  6. paygent_agent_sdk-1.1.0/paygent_agent/envelope.py +266 -0
  7. paygent_agent_sdk-1.1.0/paygent_agent/errors.py +94 -0
  8. paygent_agent_sdk-1.1.0/paygent_agent/keys.py +79 -0
  9. paygent_agent_sdk-1.1.0/paygent_agent/kya.py +393 -0
  10. paygent_agent_sdk-1.1.0/paygent_agent/py.typed +0 -0
  11. paygent_agent_sdk-1.1.0/paygent_agent/signing.py +378 -0
  12. paygent_agent_sdk-1.1.0/paygent_agent/signing_client.py +265 -0
  13. paygent_agent_sdk-1.1.0/paygent_agent/testing/__init__.py +280 -0
  14. paygent_agent_sdk-1.1.0/paygent_agent/testing/vectors/content-digest/vectors.json +36 -0
  15. paygent_agent_sdk-1.1.0/paygent_agent/testing/vectors/items-hash/vectors.json +82 -0
  16. paygent_agent_sdk-1.1.0/paygent_agent/testing/vectors/keys.json +20 -0
  17. paygent_agent_sdk-1.1.0/paygent_agent/testing/vectors/signature-base/vectors.json +41 -0
  18. paygent_agent_sdk-1.1.0/paygent_agent_sdk.egg-info/PKG-INFO +307 -0
  19. paygent_agent_sdk-1.1.0/paygent_agent_sdk.egg-info/SOURCES.txt +28 -0
  20. paygent_agent_sdk-1.1.0/paygent_agent_sdk.egg-info/dependency_links.txt +1 -0
  21. paygent_agent_sdk-1.1.0/paygent_agent_sdk.egg-info/requires.txt +2 -0
  22. paygent_agent_sdk-1.1.0/paygent_agent_sdk.egg-info/top_level.txt +1 -0
  23. paygent_agent_sdk-1.1.0/pyproject.toml +31 -0
  24. paygent_agent_sdk-1.1.0/setup.cfg +4 -0
  25. paygent_agent_sdk-1.1.0/tests/test_card.py +58 -0
  26. paygent_agent_sdk-1.1.0/tests/test_envelope.py +214 -0
  27. paygent_agent_sdk-1.1.0/tests/test_primitives.py +91 -0
  28. paygent_agent_sdk-1.1.0/tests/test_scaffold.py +151 -0
  29. paygent_agent_sdk-1.1.0/tests/test_signing_client.py +290 -0
  30. paygent_agent_sdk-1.1.0/tests/test_testing_vectors.py +112 -0
@@ -0,0 +1,307 @@
1
+ Metadata-Version: 2.4
2
+ Name: paygent-agent-sdk
3
+ Version: 1.1.0
4
+ Summary: Signing, KYA, and MCP envelope primitives for building a Paygent wallet agent
5
+ Requires-Python: >=3.14
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: cryptography>=44
8
+ Requires-Dist: pydantic>=2.10
9
+
10
+ # `paygent-agent-sdk`
11
+
12
+ Signing, KYA, and the MCP envelope for building a **Paygent wallet agent** — the primitives of the
13
+ payment-agent contract, packaged so you do not have to vendor a reference implementation to get
14
+ them right.
15
+
16
+ The contract itself is Paygent's **payment-agent guide**, which they give you at onboarding. This
17
+ package implements it; it does not replace reading it.
18
+
19
+ ## This is not the platform's client SDK
20
+
21
+ Read this first, because the names are close enough to cost you a day.
22
+
23
+ | Your code | Direction | The package you want |
24
+ | --- | --- | --- |
25
+ | **calls** Paygent | outbound | the platform's `/v1` client SDK |
26
+ | is **called by** Paygent | inbound | **this one** |
27
+
28
+ This package is for the third party on the far end of the contract: you publish an agent card (§1),
29
+ verify Paygent's inbound RFC 9421 signatures and sign your own responses (§2), speak §3's JSON-RPC
30
+ envelope, run §7's KYA checks on a mandate and an approval proof, and answer the §4 tool calls out
31
+ of your own ledger. The two packages are disjoint in direction *and* in dependency — neither is a
32
+ superset of the other, and installing the wrong one gets you an API that faces the wrong way.
33
+
34
+ A bare `§` below is a section of that guide. `paygent_agent.CONTRACT_VERSION` names the contract
35
+ revision this package implements (`1.1`), not the version of any agent built on it.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install paygent-agent-sdk
41
+ ```
42
+
43
+ Dependencies are `cryptography` and `pydantic`, and deliberately nothing else. No FastAPI, no
44
+ uvicorn, no httpx: the envelope takes and returns bytes and dicts, so the web framework is yours to
45
+ pick. The constraint is asserted, not just intended: the package's own test suite imports every
46
+ module in an environment where the frameworks are unimportable.
47
+
48
+ ## Build a minimal agent
49
+
50
+ A conformant agent is two HTTP endpoints — `POST /mcp` and the card at
51
+ `/.well-known/agent_card.json` — and the SDK covers everything between the bytes arriving and the
52
+ bytes leaving. Four pieces follow: the tools, the endpoint, the card, and the check that you agree
53
+ with Paygent on the bytes.
54
+
55
+ The examples are Starlette for brevity; only the request and response objects are
56
+ framework-specific. Every upper-case name is yours to supply — `MCP_URL` is the endpoint URL you
57
+ publish on your card, `KEY_ID` and `PRIVATE_KEY` are your response-signing keypair, and
58
+ `PAYGENT_PUBLIC_KEYS` is the key id → public key mapping Paygent gives you at onboarding. So is
59
+ `my_ledger`: that is your own store, and the SDK never touches it.
60
+
61
+ **The fragments below are excerpts from a complete, working agent.** All ten §4 tools, idempotency,
62
+ the redemption lifecycle, and §4.11's approval flow are built out in
63
+ [`examples/minimal/`](https://github.com/paygent-labs/paygent-wallet-agent/tree/master/examples/minimal)
64
+ — roughly 650 lines, on Starlette, scoring 16 of 20 on the §8 harness with the remaining four
65
+ reported not-implemented rather than failed. Read it when a quickstart snippet stops being enough.
66
+
67
+ ### 1. The tools you actually implement
68
+
69
+ Everything the guide says a tool *does* lives behind `ToolRegistry`. The envelope never sees your
70
+ balances, your stores, or your keys — which is what makes it reusable by an agent that shares no
71
+ code with the reference one.
72
+
73
+ ```python
74
+ from paygent_agent.envelope import InvalidToolCall
75
+ from paygent_agent.errors import ErrorCode, WalletError
76
+
77
+
78
+ class Wallet: # satisfies `envelope.ToolRegistry` structurally; no base class to inherit
79
+ def descriptors(self, *, sandbox: bool) -> list[dict]:
80
+ """§3's `tools/list`. Advertise §4.10 if and only if `sandbox` is true."""
81
+ return [
82
+ {
83
+ "name": "wallet.loyalty_balance",
84
+ "description": "Report the user's spendable and reserved loyalty points.",
85
+ "inputSchema": {
86
+ "type": "object",
87
+ "properties": {"user_ref": {"type": "string"}},
88
+ "required": ["user_ref"],
89
+ },
90
+ }
91
+ ]
92
+
93
+ def call(self, name, arguments) -> dict:
94
+ """Run one tool. `name` and `arguments` arrive exactly as sent, untyped — validating them
95
+ is your job, not the envelope's."""
96
+ if name != "wallet.loyalty_balance" or not isinstance(arguments, dict):
97
+ # Unanswerable, not a money outcome: this becomes JSON-RPC `-32602`.
98
+ raise InvalidToolCall(name)
99
+ user_ref = arguments.get("user_ref")
100
+ if not isinstance(user_ref, str):
101
+ raise InvalidToolCall(name)
102
+ balance = my_ledger.loyalty_balance(user_ref)
103
+ if balance is None:
104
+ # A §6 domain failure. It leaves as a *result* with `isError: true` and HTTP 200 —
105
+ # never a JSON-RPC error, which §3 reserves for "the peer is unusable".
106
+ raise WalletError(ErrorCode.UNKNOWN_INSTRUMENT)
107
+ # The plain payload. The envelope applies `tool_result` for you on the way out — wrapping
108
+ # it here too would nest one result inside another.
109
+ return {
110
+ "user_ref": user_ref,
111
+ "available_points": balance.available,
112
+ "reserved_points": balance.reserved,
113
+ "currency": balance.currency,
114
+ }
115
+ ```
116
+
117
+ A spend-affecting tool runs §7's mandate check before it touches the ledger:
118
+
119
+ ```python
120
+ from paygent_agent.kya import MandatedCall, verify_mandate
121
+
122
+ mandate = verify_mandate(
123
+ arguments.get("mandate"),
124
+ MandatedCall(user_ref=user_ref, points=points),
125
+ )
126
+ ```
127
+
128
+ A refusal raises `KyaRefusal`, which **is** a `WalletError` carrying `mandate_invalid` or
129
+ `approval_invalid`. Any handler that already turns `WalletError` into a §6 result needs no new
130
+ branch; the `reason` attribute is the fine-grained detail, and it stays on your side of the wire —
131
+ §6 allows only the code itself out.
132
+
133
+ ### 2. The endpoint
134
+
135
+ ```python
136
+ import anyio.to_thread
137
+ from starlette.responses import Response
138
+
139
+ from paygent_agent.envelope import MAX_REQUEST_BODY_BYTES, MCPEnvelope, read_capped_body
140
+ from paygent_agent.signing import SignatureError, sign_response, verify_request
141
+
142
+ envelope = MCPEnvelope(Wallet(), server_name="acme-wallet", sandbox=False)
143
+
144
+
145
+ def signed(answer):
146
+ """Sign the exact bytes the envelope produced, and send them untouched.
147
+
148
+ Never re-encode a body after signing: the digest covers the bytes as they were, and a
149
+ re-serialisation is a response whose digest covers something else.
150
+ """
151
+ headers = sign_response(
152
+ status=answer.status, body=answer.body, key_id=KEY_ID, private_key=PRIVATE_KEY
153
+ )
154
+ return Response(
155
+ answer.body,
156
+ status_code=answer.status,
157
+ media_type="application/json" if answer.is_json else None,
158
+ headers=headers,
159
+ )
160
+
161
+
162
+ async def mcp(request):
163
+ body = await read_capped_body(request.stream())
164
+ if body is None:
165
+ # Over `MAX_REQUEST_BODY_BYTES` (1 MiB), so it can never be verified. `unauthenticated`
166
+ # like any other unverifiable request — a distinct code would only tell an attacker where
167
+ # the cap sits.
168
+ return signed(envelope.unauthenticated())
169
+
170
+ try:
171
+ verify_request(
172
+ method=request.method,
173
+ # Your card's `url`, not a reconstructed request URI. Behind a TLS-terminating proxy
174
+ # the two differ, and only the published value is what Paygent could have signed.
175
+ target_uri=MCP_URL,
176
+ body=body,
177
+ headers={k.lower(): v for k, v in request.headers.items()},
178
+ known_keys=PAYGENT_PUBLIC_KEYS,
179
+ )
180
+ except SignatureError:
181
+ # §2: 401 with a *signed* body carrying `unauthenticated`. The reason stays in your logs —
182
+ # only the §6 code reaches the wire.
183
+ return signed(envelope.unauthenticated())
184
+
185
+ # Off the event loop: `dispatch` is blocking, and a registry that fsyncs a durable record
186
+ # would otherwise stall every other request in flight for the length of each call.
187
+ return signed(await anyio.to_thread.run_sync(envelope.dispatch, body))
188
+ ```
189
+
190
+ Three things the envelope deliberately leaves to you:
191
+
192
+ - **Verify before dispatching.** `dispatch` trusts its input; §2 verification is the gate in front
193
+ of it.
194
+ - **Sign everything you return**, the 401s and the 500 included. Paygent verifies your responses, so
195
+ an unsigned rejection is indistinguishable from an attacker's.
196
+ - **Keep `dispatch` off the event loop.** It is blocking by contract, so a registry that touches a
197
+ durable store stalls everything else if it runs on the loop. The snippet uses
198
+ `anyio.to_thread.run_sync`; outside ASGI, any worker thread will do. Once calls run in threads,
199
+ your registry needs its own lock, as `examples/minimal/` shows.
200
+
201
+ ### 3. The card
202
+
203
+ Served at `/.well-known/agent_card.json`, and unsigned: it is the trust root, and its authenticity
204
+ rests on TLS to your origin (§7.4).
205
+
206
+ ```python
207
+ from paygent_agent.card import AgentCardSpec, build_agent_card
208
+ from paygent_agent.keys import public_key_to_base64
209
+
210
+ card = build_agent_card(
211
+ AgentCardSpec(
212
+ name="acme-wallet",
213
+ url=MCP_URL,
214
+ signing_keys={KEY_ID: public_key_to_base64(PUBLIC_KEY)},
215
+ sandbox=False,
216
+ )
217
+ )
218
+ ```
219
+
220
+ `signing_keys` takes every key a verifier should accept, so a rotation can publish both halves at
221
+ once. The spec rejects anything that is not a base64 raw 32-byte Ed25519 key at construction,
222
+ rather than letting the typo surface as an unexplainable signature failure on a caller.
223
+
224
+ ### 4. Prove you agree on the bytes
225
+
226
+ The published wire vectors ship with the package, so byte agreement with §2 and §7.3 is a test in
227
+ your own suite rather than a cloned repo:
228
+
229
+ ```python
230
+ from paygent_agent.testing import replay_vectors
231
+
232
+
233
+ def test_wire_vectors():
234
+ failed = [result for result in replay_vectors() if not result.ok]
235
+ assert not failed, failed
236
+ ```
237
+
238
+ `replay_vectors()` re-derives every published value with this package. If your signing or hashing
239
+ is your own rather than the SDK's, `load_vector()` and `vector_bytes()` hand back the published
240
+ document and its raw bytes to diff against instead.
241
+
242
+ That is a unit check, not conformance. The §8 conformance harness is what says an agent is
243
+ conformant; it speaks only HTTP to a `--base-url`, so it runs against any agent in any language.
244
+
245
+ ## Modules
246
+
247
+ In guide order, so the table doubles as a reading order for the contract itself.
248
+
249
+ | Module | § | What it covers |
250
+ | --- | --- | --- |
251
+ | `paygent_agent` | — | `CONTRACT_VERSION` and `PROTOCOL_VERSION`, and nothing else — importing the root pulls in no submodule |
252
+ | `paygent_agent.card` | §1 | The agent card — `AgentCardSpec`, `build_agent_card`, `CAPABILITY` |
253
+ | `paygent_agent.keys` | §1 | Ed25519 encodings — raw 32-byte base64, in and out |
254
+ | `paygent_agent.signing` | §2 | Server half — `verify_request`, `sign_response`, the signature bases, `Content-Digest` |
255
+ | `paygent_agent.signing_client` | §2 | Client half — `RequestSigner`, `verify_response`, for integration tests and for verifying Paygent's responses |
256
+ | `paygent_agent.envelope` | §3 | JSON-RPC framing, `initialize` / `tools/list` / `tools/call` dispatch, the capped body read, the §6 → JSON-RPC boundary |
257
+ | `paygent_agent.errors` | §6 | The error vocabulary — `ErrorCode`, `WalletError`, `tool_result`, `tool_error` |
258
+ | `paygent_agent.kya` | §7 | `verify_mandate`, `items_hash`, `sign_approval`, `verify_approval` |
259
+ | `paygent_agent.canonical` | §7.3 | RFC 8785 / JCS canonical JSON |
260
+ | `paygent_agent.testing` | — | The published vectors as package data, plus `replay_vectors()` |
261
+
262
+ Every module states its surface in `__all__`, and `py.typed` ships, so a type checker sees real
263
+ types rather than `Any`.
264
+
265
+ ## Bind your own approval domain
266
+
267
+ `sign_approval` and `verify_approval` prefix the bytes they sign with a domain separator, which
268
+ defaults to `APPROVAL_SIGNATURE_CONTEXT` — the string `"paygent-wallet-agent/approval/v1"`.
269
+
270
+ §7.3 makes the approval scheme vendor-internal: the value never leaves your process, and Paygent
271
+ does not verify it. So the default crosses no trust boundary and interoperates with nothing — but it
272
+ does name the reference implementation's repository rather than your service. Pass your own instead,
273
+ and pass the *same* one to both calls:
274
+
275
+ ```python
276
+ from paygent_agent.kya import sign_approval, verify_approval
277
+
278
+ APPROVAL_CONTEXT = "acme-wallet/approval/v1"
279
+
280
+ proof = sign_approval(APPROVAL_KEY, approval, context=APPROVAL_CONTEXT)
281
+ verify_approval(
282
+ proof,
283
+ checkout_ref=checkout_ref,
284
+ user_ref=user_ref,
285
+ public_key=APPROVAL_PUBLIC_KEY,
286
+ context=APPROVAL_CONTEXT,
287
+ )
288
+ ```
289
+
290
+ **Choose the string before you mint anything in production.** Changing it later invalidates every
291
+ approval signed under the old one, and the only symptom is `approval_invalid` on a proof that
292
+ verified yesterday. Pin it with a test asserting the exact literal, the way this repo pins its own.
293
+
294
+ ## Versioning
295
+
296
+ The version tracks the **contract**, not any agent: `paygent_agent.CONTRACT_VERSION` is `"1.1"` and
297
+ the distribution is `1.1.x`. A patch is a fix in this package; a minor is a contract minor. Contract
298
+ `1.x` is frozen in the sense that matters — existing shapes, error codes, and verification rules
299
+ will not change under it, and `1.1` is additive over `1.0`.
300
+
301
+ ## Provenance
302
+
303
+ This package is extracted from
304
+ [`paygent-wallet-agent`](https://github.com/paygent-labs/paygent-wallet-agent), a clean-room
305
+ reference implementation built from the guide alone. Every surface here is argued from
306
+ `docs/PAYMENT-AGENT-GUIDE.md`; the reference agent dogfoods the package and gates its releases
307
+ against the §8 conformance harness, so the SDK and a conformant agent are never checked apart.
@@ -0,0 +1,298 @@
1
+ # `paygent-agent-sdk`
2
+
3
+ Signing, KYA, and the MCP envelope for building a **Paygent wallet agent** — the primitives of the
4
+ payment-agent contract, packaged so you do not have to vendor a reference implementation to get
5
+ them right.
6
+
7
+ The contract itself is Paygent's **payment-agent guide**, which they give you at onboarding. This
8
+ package implements it; it does not replace reading it.
9
+
10
+ ## This is not the platform's client SDK
11
+
12
+ Read this first, because the names are close enough to cost you a day.
13
+
14
+ | Your code | Direction | The package you want |
15
+ | --- | --- | --- |
16
+ | **calls** Paygent | outbound | the platform's `/v1` client SDK |
17
+ | is **called by** Paygent | inbound | **this one** |
18
+
19
+ This package is for the third party on the far end of the contract: you publish an agent card (§1),
20
+ verify Paygent's inbound RFC 9421 signatures and sign your own responses (§2), speak §3's JSON-RPC
21
+ envelope, run §7's KYA checks on a mandate and an approval proof, and answer the §4 tool calls out
22
+ of your own ledger. The two packages are disjoint in direction *and* in dependency — neither is a
23
+ superset of the other, and installing the wrong one gets you an API that faces the wrong way.
24
+
25
+ A bare `§` below is a section of that guide. `paygent_agent.CONTRACT_VERSION` names the contract
26
+ revision this package implements (`1.1`), not the version of any agent built on it.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install paygent-agent-sdk
32
+ ```
33
+
34
+ Dependencies are `cryptography` and `pydantic`, and deliberately nothing else. No FastAPI, no
35
+ uvicorn, no httpx: the envelope takes and returns bytes and dicts, so the web framework is yours to
36
+ pick. The constraint is asserted, not just intended: the package's own test suite imports every
37
+ module in an environment where the frameworks are unimportable.
38
+
39
+ ## Build a minimal agent
40
+
41
+ A conformant agent is two HTTP endpoints — `POST /mcp` and the card at
42
+ `/.well-known/agent_card.json` — and the SDK covers everything between the bytes arriving and the
43
+ bytes leaving. Four pieces follow: the tools, the endpoint, the card, and the check that you agree
44
+ with Paygent on the bytes.
45
+
46
+ The examples are Starlette for brevity; only the request and response objects are
47
+ framework-specific. Every upper-case name is yours to supply — `MCP_URL` is the endpoint URL you
48
+ publish on your card, `KEY_ID` and `PRIVATE_KEY` are your response-signing keypair, and
49
+ `PAYGENT_PUBLIC_KEYS` is the key id → public key mapping Paygent gives you at onboarding. So is
50
+ `my_ledger`: that is your own store, and the SDK never touches it.
51
+
52
+ **The fragments below are excerpts from a complete, working agent.** All ten §4 tools, idempotency,
53
+ the redemption lifecycle, and §4.11's approval flow are built out in
54
+ [`examples/minimal/`](https://github.com/paygent-labs/paygent-wallet-agent/tree/master/examples/minimal)
55
+ — roughly 650 lines, on Starlette, scoring 16 of 20 on the §8 harness with the remaining four
56
+ reported not-implemented rather than failed. Read it when a quickstart snippet stops being enough.
57
+
58
+ ### 1. The tools you actually implement
59
+
60
+ Everything the guide says a tool *does* lives behind `ToolRegistry`. The envelope never sees your
61
+ balances, your stores, or your keys — which is what makes it reusable by an agent that shares no
62
+ code with the reference one.
63
+
64
+ ```python
65
+ from paygent_agent.envelope import InvalidToolCall
66
+ from paygent_agent.errors import ErrorCode, WalletError
67
+
68
+
69
+ class Wallet: # satisfies `envelope.ToolRegistry` structurally; no base class to inherit
70
+ def descriptors(self, *, sandbox: bool) -> list[dict]:
71
+ """§3's `tools/list`. Advertise §4.10 if and only if `sandbox` is true."""
72
+ return [
73
+ {
74
+ "name": "wallet.loyalty_balance",
75
+ "description": "Report the user's spendable and reserved loyalty points.",
76
+ "inputSchema": {
77
+ "type": "object",
78
+ "properties": {"user_ref": {"type": "string"}},
79
+ "required": ["user_ref"],
80
+ },
81
+ }
82
+ ]
83
+
84
+ def call(self, name, arguments) -> dict:
85
+ """Run one tool. `name` and `arguments` arrive exactly as sent, untyped — validating them
86
+ is your job, not the envelope's."""
87
+ if name != "wallet.loyalty_balance" or not isinstance(arguments, dict):
88
+ # Unanswerable, not a money outcome: this becomes JSON-RPC `-32602`.
89
+ raise InvalidToolCall(name)
90
+ user_ref = arguments.get("user_ref")
91
+ if not isinstance(user_ref, str):
92
+ raise InvalidToolCall(name)
93
+ balance = my_ledger.loyalty_balance(user_ref)
94
+ if balance is None:
95
+ # A §6 domain failure. It leaves as a *result* with `isError: true` and HTTP 200 —
96
+ # never a JSON-RPC error, which §3 reserves for "the peer is unusable".
97
+ raise WalletError(ErrorCode.UNKNOWN_INSTRUMENT)
98
+ # The plain payload. The envelope applies `tool_result` for you on the way out — wrapping
99
+ # it here too would nest one result inside another.
100
+ return {
101
+ "user_ref": user_ref,
102
+ "available_points": balance.available,
103
+ "reserved_points": balance.reserved,
104
+ "currency": balance.currency,
105
+ }
106
+ ```
107
+
108
+ A spend-affecting tool runs §7's mandate check before it touches the ledger:
109
+
110
+ ```python
111
+ from paygent_agent.kya import MandatedCall, verify_mandate
112
+
113
+ mandate = verify_mandate(
114
+ arguments.get("mandate"),
115
+ MandatedCall(user_ref=user_ref, points=points),
116
+ )
117
+ ```
118
+
119
+ A refusal raises `KyaRefusal`, which **is** a `WalletError` carrying `mandate_invalid` or
120
+ `approval_invalid`. Any handler that already turns `WalletError` into a §6 result needs no new
121
+ branch; the `reason` attribute is the fine-grained detail, and it stays on your side of the wire —
122
+ §6 allows only the code itself out.
123
+
124
+ ### 2. The endpoint
125
+
126
+ ```python
127
+ import anyio.to_thread
128
+ from starlette.responses import Response
129
+
130
+ from paygent_agent.envelope import MAX_REQUEST_BODY_BYTES, MCPEnvelope, read_capped_body
131
+ from paygent_agent.signing import SignatureError, sign_response, verify_request
132
+
133
+ envelope = MCPEnvelope(Wallet(), server_name="acme-wallet", sandbox=False)
134
+
135
+
136
+ def signed(answer):
137
+ """Sign the exact bytes the envelope produced, and send them untouched.
138
+
139
+ Never re-encode a body after signing: the digest covers the bytes as they were, and a
140
+ re-serialisation is a response whose digest covers something else.
141
+ """
142
+ headers = sign_response(
143
+ status=answer.status, body=answer.body, key_id=KEY_ID, private_key=PRIVATE_KEY
144
+ )
145
+ return Response(
146
+ answer.body,
147
+ status_code=answer.status,
148
+ media_type="application/json" if answer.is_json else None,
149
+ headers=headers,
150
+ )
151
+
152
+
153
+ async def mcp(request):
154
+ body = await read_capped_body(request.stream())
155
+ if body is None:
156
+ # Over `MAX_REQUEST_BODY_BYTES` (1 MiB), so it can never be verified. `unauthenticated`
157
+ # like any other unverifiable request — a distinct code would only tell an attacker where
158
+ # the cap sits.
159
+ return signed(envelope.unauthenticated())
160
+
161
+ try:
162
+ verify_request(
163
+ method=request.method,
164
+ # Your card's `url`, not a reconstructed request URI. Behind a TLS-terminating proxy
165
+ # the two differ, and only the published value is what Paygent could have signed.
166
+ target_uri=MCP_URL,
167
+ body=body,
168
+ headers={k.lower(): v for k, v in request.headers.items()},
169
+ known_keys=PAYGENT_PUBLIC_KEYS,
170
+ )
171
+ except SignatureError:
172
+ # §2: 401 with a *signed* body carrying `unauthenticated`. The reason stays in your logs —
173
+ # only the §6 code reaches the wire.
174
+ return signed(envelope.unauthenticated())
175
+
176
+ # Off the event loop: `dispatch` is blocking, and a registry that fsyncs a durable record
177
+ # would otherwise stall every other request in flight for the length of each call.
178
+ return signed(await anyio.to_thread.run_sync(envelope.dispatch, body))
179
+ ```
180
+
181
+ Three things the envelope deliberately leaves to you:
182
+
183
+ - **Verify before dispatching.** `dispatch` trusts its input; §2 verification is the gate in front
184
+ of it.
185
+ - **Sign everything you return**, the 401s and the 500 included. Paygent verifies your responses, so
186
+ an unsigned rejection is indistinguishable from an attacker's.
187
+ - **Keep `dispatch` off the event loop.** It is blocking by contract, so a registry that touches a
188
+ durable store stalls everything else if it runs on the loop. The snippet uses
189
+ `anyio.to_thread.run_sync`; outside ASGI, any worker thread will do. Once calls run in threads,
190
+ your registry needs its own lock, as `examples/minimal/` shows.
191
+
192
+ ### 3. The card
193
+
194
+ Served at `/.well-known/agent_card.json`, and unsigned: it is the trust root, and its authenticity
195
+ rests on TLS to your origin (§7.4).
196
+
197
+ ```python
198
+ from paygent_agent.card import AgentCardSpec, build_agent_card
199
+ from paygent_agent.keys import public_key_to_base64
200
+
201
+ card = build_agent_card(
202
+ AgentCardSpec(
203
+ name="acme-wallet",
204
+ url=MCP_URL,
205
+ signing_keys={KEY_ID: public_key_to_base64(PUBLIC_KEY)},
206
+ sandbox=False,
207
+ )
208
+ )
209
+ ```
210
+
211
+ `signing_keys` takes every key a verifier should accept, so a rotation can publish both halves at
212
+ once. The spec rejects anything that is not a base64 raw 32-byte Ed25519 key at construction,
213
+ rather than letting the typo surface as an unexplainable signature failure on a caller.
214
+
215
+ ### 4. Prove you agree on the bytes
216
+
217
+ The published wire vectors ship with the package, so byte agreement with §2 and §7.3 is a test in
218
+ your own suite rather than a cloned repo:
219
+
220
+ ```python
221
+ from paygent_agent.testing import replay_vectors
222
+
223
+
224
+ def test_wire_vectors():
225
+ failed = [result for result in replay_vectors() if not result.ok]
226
+ assert not failed, failed
227
+ ```
228
+
229
+ `replay_vectors()` re-derives every published value with this package. If your signing or hashing
230
+ is your own rather than the SDK's, `load_vector()` and `vector_bytes()` hand back the published
231
+ document and its raw bytes to diff against instead.
232
+
233
+ That is a unit check, not conformance. The §8 conformance harness is what says an agent is
234
+ conformant; it speaks only HTTP to a `--base-url`, so it runs against any agent in any language.
235
+
236
+ ## Modules
237
+
238
+ In guide order, so the table doubles as a reading order for the contract itself.
239
+
240
+ | Module | § | What it covers |
241
+ | --- | --- | --- |
242
+ | `paygent_agent` | — | `CONTRACT_VERSION` and `PROTOCOL_VERSION`, and nothing else — importing the root pulls in no submodule |
243
+ | `paygent_agent.card` | §1 | The agent card — `AgentCardSpec`, `build_agent_card`, `CAPABILITY` |
244
+ | `paygent_agent.keys` | §1 | Ed25519 encodings — raw 32-byte base64, in and out |
245
+ | `paygent_agent.signing` | §2 | Server half — `verify_request`, `sign_response`, the signature bases, `Content-Digest` |
246
+ | `paygent_agent.signing_client` | §2 | Client half — `RequestSigner`, `verify_response`, for integration tests and for verifying Paygent's responses |
247
+ | `paygent_agent.envelope` | §3 | JSON-RPC framing, `initialize` / `tools/list` / `tools/call` dispatch, the capped body read, the §6 → JSON-RPC boundary |
248
+ | `paygent_agent.errors` | §6 | The error vocabulary — `ErrorCode`, `WalletError`, `tool_result`, `tool_error` |
249
+ | `paygent_agent.kya` | §7 | `verify_mandate`, `items_hash`, `sign_approval`, `verify_approval` |
250
+ | `paygent_agent.canonical` | §7.3 | RFC 8785 / JCS canonical JSON |
251
+ | `paygent_agent.testing` | — | The published vectors as package data, plus `replay_vectors()` |
252
+
253
+ Every module states its surface in `__all__`, and `py.typed` ships, so a type checker sees real
254
+ types rather than `Any`.
255
+
256
+ ## Bind your own approval domain
257
+
258
+ `sign_approval` and `verify_approval` prefix the bytes they sign with a domain separator, which
259
+ defaults to `APPROVAL_SIGNATURE_CONTEXT` — the string `"paygent-wallet-agent/approval/v1"`.
260
+
261
+ §7.3 makes the approval scheme vendor-internal: the value never leaves your process, and Paygent
262
+ does not verify it. So the default crosses no trust boundary and interoperates with nothing — but it
263
+ does name the reference implementation's repository rather than your service. Pass your own instead,
264
+ and pass the *same* one to both calls:
265
+
266
+ ```python
267
+ from paygent_agent.kya import sign_approval, verify_approval
268
+
269
+ APPROVAL_CONTEXT = "acme-wallet/approval/v1"
270
+
271
+ proof = sign_approval(APPROVAL_KEY, approval, context=APPROVAL_CONTEXT)
272
+ verify_approval(
273
+ proof,
274
+ checkout_ref=checkout_ref,
275
+ user_ref=user_ref,
276
+ public_key=APPROVAL_PUBLIC_KEY,
277
+ context=APPROVAL_CONTEXT,
278
+ )
279
+ ```
280
+
281
+ **Choose the string before you mint anything in production.** Changing it later invalidates every
282
+ approval signed under the old one, and the only symptom is `approval_invalid` on a proof that
283
+ verified yesterday. Pin it with a test asserting the exact literal, the way this repo pins its own.
284
+
285
+ ## Versioning
286
+
287
+ The version tracks the **contract**, not any agent: `paygent_agent.CONTRACT_VERSION` is `"1.1"` and
288
+ the distribution is `1.1.x`. A patch is a fix in this package; a minor is a contract minor. Contract
289
+ `1.x` is frozen in the sense that matters — existing shapes, error codes, and verification rules
290
+ will not change under it, and `1.1` is additive over `1.0`.
291
+
292
+ ## Provenance
293
+
294
+ This package is extracted from
295
+ [`paygent-wallet-agent`](https://github.com/paygent-labs/paygent-wallet-agent), a clean-room
296
+ reference implementation built from the guide alone. Every surface here is argued from
297
+ `docs/PAYMENT-AGENT-GUIDE.md`; the reference agent dogfoods the package and gates its releases
298
+ against the §8 conformance harness, so the SDK and a conformant agent are never checked apart.
@@ -0,0 +1,22 @@
1
+ """`paygent-agent-sdk` — primitives for building a Paygent wallet agent.
2
+
3
+ This package is for code Paygent *calls*: a third party building a wallet agent that verifies
4
+ inbound signatures (§2), signs its own responses, runs the §7 KYA checks, and speaks §3's envelope.
5
+ It is **not** the platform's `/v1` client SDK, which is for code calling Paygent. The two are
6
+ disjoint in direction and in dependency — see `docs/SDK-PLAN.md` section 1.
7
+
8
+ Every surface here is argued from `docs/PAYMENT-AGENT-GUIDE.md`. A bare `§` names a section of it.
9
+
10
+ `canonical`, `keys`, `errors`, `signing`, `signing_client`, `kya`, `envelope`, `card`, and
11
+ `testing` all live here as of `docs/SDK-PLAN.md` step 6.
12
+ """
13
+
14
+ #: The contract revision this package implements, not the version of any one agent built on it.
15
+ #: `tests/test_pinned_guide.py` asserts it against the pinned guide's header so the two cannot
16
+ #: drift silently.
17
+ CONTRACT_VERSION = "1.1"
18
+
19
+ #: The MCP protocol revision the §3 envelope speaks.
20
+ PROTOCOL_VERSION = "2025-06-18"
21
+
22
+ __all__ = ["CONTRACT_VERSION", "PROTOCOL_VERSION"]
@@ -0,0 +1,42 @@
1
+ """Canonical JSON, shared by everything that has to hash or sign a structure.
2
+
3
+ §7 defines `items_hash` over canonical JSON, and §5's argument comparison needs the same property
4
+ for a different reason: two encodings of one call must not fingerprint differently, or a retry
5
+ whose fields arrived in another order would be read as a conflict. One implementation serves both,
6
+ so the two can never disagree about what "the same object" means.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from typing import Any
13
+
14
+ #: The module's public surface, stated rather than inferred: it is what a star-import exports,
15
+ #: what a type checker treats as a re-export, and what `sdk/tests/test_scaffold.py` requires of
16
+ #: every module here.
17
+ __all__ = [
18
+ "canonical_json",
19
+ ]
20
+
21
+
22
+ def canonical_json(value: Any) -> bytes:
23
+ """RFC 8785 (JCS), to the extent this contract needs it: object keys sorted by their UTF-16
24
+ code units, no insignificant whitespace, UTF-8 output.
25
+
26
+ Every value this contract canonicalises is a string, an integer, a bool, or null, so JCS's
27
+ number-formatting rules — the hard part — cannot be reached; floats are rejected rather than
28
+ serialised, since money and quantities are never floats (§4).
29
+ """
30
+
31
+ def check(node: Any) -> None:
32
+ if isinstance(node, float):
33
+ raise TypeError("canonical JSON here carries no floats")
34
+ if isinstance(node, dict):
35
+ for item in node.values():
36
+ check(item)
37
+ elif isinstance(node, list):
38
+ for item in node:
39
+ check(item)
40
+
41
+ check(value)
42
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()