This guide helps you implement SNAP Protocol support in your application.
SNAP has three layers. Implement the layers you need:
| Layer | Steps | Required? |
|---|---|---|
| Auth (core) | 1 (Key Generation), 4 (Sign), 5 (Verify), 6 (HTTP Transport) | Yes |
| Discovery | 2 (Agent Card), 3 (Publish to Nostr), 7 (Discover Agents) | Optional |
| Communication | Message/task handling in Step 6 | Optional (extends Auth) |
Auth only? Implement Steps 1, 4, 5, and a simplified Step 6 (just signature verification + allowlist). Skip Steps 2, 3, 7.
Cryptography:
- Schnorr signature implementation (BIP-340)
- SHA-256 hashing
- Bech32m encoding/decoding
- BIP-39 (mnemonic generation)
- BIP-86 (key derivation)
Serialization:
- JSON parser
- JCS (JSON Canonicalization Scheme, RFC 8785)
Transport:
- HTTP client/server
- WebSocket client/server (optional)
- Nostr client library (optional)
JavaScript/TypeScript:
{
"@noble/curves": "^2.0.0",
"@noble/hashes": "^1.7.0",
"bech32": "^2.0.0",
"canonicalize": "^2.0.0",
"nostr-tools": "^2.0.0"
}Python:
secp256k1>=0.14.0
bech32>=1.2.0
canonicaljson>=2.0.0
nostr-sdk>=0.30.0Generate a P2TR identity for your agent.
Pseudocode:
# 1. Generate or load BIP-39 mnemonic
mnemonic = generate_mnemonic(24) # 24 words
# 2. Derive master key
master_key = mnemonic_to_master_key(mnemonic)
# 3. Derive agent key using BIP-86 path
path = "m/86'/0'/0'/0/0" # First agent
private_key = derive_key(master_key, path)
# 4. Compute internal public key (x-only)
internal_key = get_public_key(private_key) # P
# 5. Apply BIP-341 taproot tweak: Q = P + tagged_hash("TapTweak", P) * G
output_key = taproot_tweak(internal_key) # Q
# 6. Encode tweaked output key as P2TR address
identity = encode_p2tr(output_key) # bc1p...Key Storage:
- Store mnemonic securely (encrypted, HSM, or offline)
- Never expose private key in logs or API responses
- Use environment variables or secure key stores
Define your agent's capabilities.
Pseudocode:
agent_card = {
"name": "My Code Assistant",
"description": "An AI agent for code generation",
"version": "1.0.0",
"identity": identity, # bc1p...
"endpoints": [
{"protocol": "http", "url": "https://my-agent.example.com/snap"}
],
"skills": [
{
"id": "code-generation",
"name": "Code Generation",
"description": "Generate code from descriptions",
"tags": ["code", "typescript", "python"]
}
],
"defaultInputModes": ["text/plain"],
"defaultOutputModes": ["text/plain", "application/json"]
}Validate against constraints.md before publishing.
Make your agent discoverable.
Pseudocode:
# 1. Create Nostr event
nostr_event = {
"kind": 31337,
"pubkey": get_public_key(private_key), # Internal key (hex), NOT the tweaked key from P2TR
"created_at": current_timestamp(),
"tags": [
["d", identity], # P2TR address as identifier
["name", "My Code Assistant"],
["version", "1.0.0"],
["skill", "code-generation", "Code Generation"],
["endpoint", "http", "https://my-agent.example.com/snap"]
],
"content": json_stringify(agent_card)
}
# 2. Sign event (Nostr signature, not SNAP)
nostr_event["id"] = compute_nostr_event_id(nostr_event)
nostr_event["sig"] = sign_nostr_event(nostr_event, private_key)
# 3. Publish to relays
relays = ["wss://relay.damus.io", "wss://relay.nostr.band"]
for relay in relays:
publish_event(relay, nostr_event)Sign outgoing messages.
Pseudocode:
def sign_snap_message(message, private_key):
# 1. Compute the BIP-341 tweaked private key
tweaked_key = tweak_private_key(private_key)
# 2. Build canonical signature input
parts = [
message["id"],
message["from"],
message.get("to", ""), # Empty string if absent (Agent-to-Service)
message["type"],
message["method"],
canonicalize_jcs(message["payload"]), # RFC 8785
str(message["timestamp"])
]
canonical_input = '\x00'.join(parts) # NULL byte separator
# 3. Hash the input
hash = sha256(canonical_input.encode('utf-8'))
# 4. Sign with Schnorr (BIP-340) using the tweaked private key
signature = schnorr_sign(hash, tweaked_key)
return signature.hex() # 128 hex chars
# Usage — Agent-to-Agent (with `to`)
message = {
"id": "msg-001",
"version": "0.1",
"from": my_identity,
"to": recipient_identity,
"type": "request",
"method": "message/send",
"payload": {"message": {...}},
"timestamp": current_timestamp()
}
# Usage — Agent-to-Service (without `to`)
message = {
"id": "svc-001",
"version": "0.1",
"from": my_identity,
"type": "request",
"method": "service/call",
"payload": {"name": "query_database", "arguments": {"sql": "SELECT 1"}},
"timestamp": current_timestamp()
}
message["sig"] = sign_snap_message(message, my_private_key)Critical: Use JCS (RFC 8785) for payload canonicalization, not regular JSON serialization.
Verify signatures before processing.
Pseudocode:
def verify_snap_message(message):
# 1. Check timestamp
now = current_timestamp()
if abs(now - message["timestamp"]) > 60:
raise TimestampExpiredError()
# 2. Check for duplicate (replay protection)
if is_duplicate(message["from"], message["id"]):
raise DuplicateMessageError()
# 3. Extract tweaked public key from P2TR address
# This returns the BIP-341 tweaked output key (Q), which is
# the correct key for verifying signatures made with the tweaked private key.
public_key = extract_pubkey_from_p2tr(message["from"])
# 4. Rebuild canonical input
parts = [
message["id"],
message["from"],
message.get("to", ""), # Empty string if absent (Agent-to-Service)
message["type"],
message["method"],
canonicalize_jcs(message["payload"]),
str(message["timestamp"])
]
canonical_input = '\x00'.join(parts)
# 5. Hash the input
hash = sha256(canonical_input.encode('utf-8'))
# 6. Verify Schnorr signature
signature = bytes.fromhex(message["sig"])
if not schnorr_verify(signature, hash, public_key):
raise SignatureInvalidError()
# 7. Track message ID (for deduplication)
track_message_id(message["from"], message["id"])
return TrueHandle incoming SNAP requests.
Pseudocode (Responder):
@app.post("/snap")
def handle_snap_request(request):
# 1. Parse JSON
message = parse_json(request.body)
# 2. Verify signature
try:
verify_snap_message(message)
except SignatureError as e:
return error_response(2001, str(e))
# 3. Validate message structure
try:
validate_message(message)
except ValidationError as e:
return error_response(1004, str(e))
# 4. Route to handler
if message["method"] == "message/send":
return handle_message_send(message)
elif message["method"] == "tasks/get":
return handle_tasks_get(message)
else:
return error_response(1007, "Method not found")Pseudocode (Requester):
def send_snap_request(endpoint, message, private_key):
# 1. Sign message
message["sig"] = sign_snap_message(message, private_key)
# 2. Send HTTP POST
response = http_post(
endpoint,
headers={
"Content-Type": "application/json",
"SNAP-Version": "0.1"
},
body=json_stringify(message)
)
# 3. Parse response
response_message = parse_json(response.body)
# 4. Verify response signature (if present)
if "sig" in response_message:
verify_snap_message(response_message)
return response_messageFind agents on Nostr.
Pseudocode:
def discover_agents_by_skill(skill_id):
relays = ["wss://relay.damus.io", "wss://relay.nostr.band"]
agents = []
for relay in relays:
# Query for Agent Cards with the skill
events = relay.query({
"kinds": [31337],
"#skill": [skill_id]
})
for event in events:
# Parse Agent Card from event content
agent_card = parse_json(event["content"])
# Verify event signature (Nostr)
if not verify_nostr_event(event):
continue
agents.append(agent_card)
# Deduplicate by identity
return deduplicate(agents, key="identity")Implement these validations:
- Required fields present (
id,version,from,type,method,payload,timestamp,sig) -
idmatches pattern^[a-zA-Z0-9_-]+$, length 1-128 -
versionmatches pattern^\d+\.\d+$ -
fromis a valid P2TR address (62 chars, checksum) -
to, if present, is a valid P2TR address (62 chars, checksum) -
typeisrequest,response, orevent -
methodmatches pattern^[a-z]+/[a-z_]+$(standard methods:message/send,message/stream,tasks/get,tasks/cancel,tasks/resubscribe,service/call; custom methods also allowed) -
timestampis integer, within ±60 seconds -
sigis 128 hex characters -
payloadis valid JSON object, max 1 MB
- Public key extracted from
fromaddress - Canonical input computed correctly (JCS for payload)
- SHA-256 hash computed
- Schnorr signature verified (BIP-340)
- Timestamp within ±60 seconds
- Message ID not seen before (120s window)
- All required fields present
-
identityis valid P2TR address -
endpointsentries have valid protocol and URL (if present) - At least one skill defined
- Skills have valid IDs (pattern
^[a-z0-9-]+$) - Total size under 64 KB
Return appropriate error codes:
def error_response(code, message, data=None):
return {
"type": "response",
"method": original_method,
"payload": {
"error": {
"code": code,
"message": message,
"data": data or {}
}
},
"timestamp": current_timestamp()
# Optional: sign the response
}Common errors:
2001- Signature verification failed2004- Timestamp expired2006- Duplicate message (replay)1004- Invalid payload1007- Method not found
See errors.md for full list.
Test your implementation with:
- Unit tests - Test each component (signing, verification, validation)
- Integration tests - Test full request/response flow
- Compliance tests - Use test vectors in
test-vectors/ - Interop tests - Test against other implementations
See security-practices.md for detailed guidance.
Key points:
- Store private keys securely (HSM for production)
- Validate all inputs before processing
- Implement rate limiting
- Use HTTPS for HTTP transport
- Require signed responses for sensitive operations
- Cache Nostr relay connections
- Reuse HTTP connections (keep-alive)
- Batch Nostr queries when possible
- Implement message deduplication efficiently (time-bounded cache)
- Validate message structure before signature verification (fail fast)
- Read security-practices.md
- Review constraints.md for validation rules
- Check examples/ for code samples (coming soon)
- Review test vectors in
test-vectors/for compliance
- Open a GitHub issue for specification questions
- Check faq.md for common questions
- Review existing implementations (reference implementations coming in v0.5)