# SAP Payments X402

Use this skill for SAP x402 payment context, balances, subscriptions, paid API
workflows, and hosted SAP MCP x402/pay.sh monetization.

## Tools

- `sap_x402_prepare_payment`
- `sap_x402_get_balance`
- `sap_payments_profile_current`
- `sap_payments_wallet_guard`
- `sap_payments_process_status`
- `sap_payments_call_paid_tool`
- `sap_payments_call_external_x402`
- `sap_payments_register_agent`
- `sap_payments_update_agent`
- `sap_payments_finalize_transaction`
- `sap_payments_prepare_challenge`
- `sap_payments_sign_challenge`
- `sap_payments_verify_receipt`
- `sap_prepare_action`
- `sap_x402_paid_call`
- `sap_create_subscription`
- `sap_fund_subscription`
- `sap_cancel_subscription`
- `sap_fetch_subscription`

## Flow

1. Inspect agent profile and pricing with `sap_get_agent_profile`.
2. Use `sap_x402_prepare_payment` before building a paid request.
3. Use `sap_x402_get_balance` before assuming a depositor can pay.
4. Use subscription tools only after explaining amount, cadence, and
   cancellation path.

## Hosted MCP Monetization

Canonical hosted endpoint: `https://mcp.sap.oobeprotocol.ai/mcp`.

Remote `/mcp` deployments can require x402 v2 payment for paid `tools/call`
requests. Local `stdio` usage remains free and should not attempt x402 payment.
Do not treat hosted `402 Payment Required` as a failure; it is the expected
payment handshake. Do not silently bypass hosted paid tools by switching to a
local free stdio MCP server unless the user explicitly asks for local execution.
If `sap_profile_current` says the hosted server has no signer, treat that as
the non-custodial model: OOBE does not hold user keys. Paid and value-moving
hosted calls still proceed through x402/pay.sh plus the user's local SAP profile
or external signer.

- Free: MCP handshake, `tools/list`, `prompts/list`, `resources/list`,
  `sap_profile_current`, `sap_agent_start`, `sap_agent_runtime_status`,
  `sap_agent_next_action`, `sap_estimate_tool_cost`, `sap_pricing_catalog`,
  repair/status tools, local payment bridge control, transaction
  preview/finalization helpers, SOL/SPL/x402 balance readiness, single-asset
  price snapshots, and memory/audit helpers.
- Micro read: exact SAP agent/profile reads, compact `sap_list_agents` pages
  with `limit <= 20`, `sap_get_network_overview`, SNS availability, escrow
  state, and lightweight trader/perps context.
- Read premium: `sap_discover_agents`, `sap_list_all_agents`, full/enriched or
  large `sap_list_agents` pages, enriched holdings, indexed discovery, network
  stats, protocol/capability indexes, DAS, token lists, quotes/routes, and
  OHLCV/history.
- Builder: batch SNS/domain checks, analytics, transaction builders.
- Value action: fixed fee plus configured basis-points fee when public USD
  notional fields are present.

When a remote call returns HTTP `402`, read the x402 `PAYMENT-REQUIRED`
instructions, create a payment, retry with `PAYMENT-SIGNATURE`, and capture
`PAYMENT-RESPONSE` after settlement. If a `payShCheckoutUrl` is present, surface
it for browser/manual checkout flows.

Before retrying `payment_required`, `hosted_local_signer_required`,
`BlockhashNotFound`, timeout, missing `sap_payments`, or an unconfirmed
signature, call `sap_agent_next_action`. Use its `safeToRetryNow`, `nextTool`,
and `paymentCharged` fields as the retry guard.

Before starting a paid or value-moving workflow, call the free hosted
`sap_prepare_action` planner with the closest intent and the local
`sap_payments_wallet_guard` guard when the `sap_payments` namespace is visible.
The wallet guard returns the active profile, signer public key, wallet storage
class, permission hints, allowed local signing capabilities, and forbidden
actions. It never returns a wallet path, keypair bytes, seed phrase, or private
material. Treat local signing as a capability exposed through `sap_payments`,
not as a file the agent can inspect.

The planner returns:

- fresh data that must be fetched again before payment/signing;
- whether to use hosted `sap`, local `sap_payments`, or a hosted unsigned
  builder plus `sap_payments_finalize_transaction`;
- max-price and confirmation guidance;
- retry rules and the proof-tape fields to report back to the user.

For fast x402 execution:

1. Reuse the MCP session returned by `initialize`.
2. Retry the same MCP method and params after payment. The JSON-RPC `id` may
   change, but the tool name and arguments must match the challenge.
3. Use `PAYMENT-SIGNATURE` first; use `X-PAYMENT` only for clients that require
   the alternate header.
4. Cache only static MCP surface metadata such as `tools/list`, `prompts/list`,
   and `resources/list` inside the runtime when useful. Session memory can
   store operational context, receipts, signatures, and error classifications.
   Do not cache on-chain balances, SAP agent rows, pricing, SNS ownership,
   quotes, blockhashes, simulations, liquidity, routes, or settlement state
   when the user expects fresh data.
5. Treat `PAYMENT-RESPONSE` as the receipt bound to the tool output.
6. If the client runtime cannot sign or attach x402 payment headers itself, use
   the local SAP MCP `sap_payments_call_paid_tool` bridge configured by the SAP
   MCP wizard instead of falling back to local stdio automatically.

Do not use x402 for core balance or single-asset price readiness reads.
`sol_get_balance`, `spl-token_getBalance`, `spl-token_getTokenAccounts`,
`magicblock_balance`, `sap_x402_get_balance`, `jupiter_getPrice`,
`pyth_getPrice`, and `coingecko_getTokenPrice` are free hosted tools and should
be called directly through the remote SAP MCP connection. Use
`jupiter_getHoldings` only when the user needs enriched paid portfolio context.
Always verify USDC and SOL balances before attempting paid calls — an agent
without USDC cannot make paid calls.

Before any paid tool call, use `sap_estimate_tool_cost` with the tool name to
get the exact tier, estimated USD cost, and recommended `maxPriceUsd`. This
prevents silent cap aborts and avoids wasting x402 attempts on local-signer-only
tools that never issue a 402 challenge.

When available locally, call `sap_payments_call_paid_tool` with `toolName`,
`arguments`, `maxPriceUsd`, and `confirm: true`. It initializes the hosted MCP
session, obtains the x402 challenge, signs with the user SAP MCP profile wallet
or external signer, retries the hosted tool call, and returns the settlement
receipt. Do not ask the user to install a separate x402 plugin when the local
SAP MCP `sap_payments` bridge is already configured. The legacy
`sap_x402_paid_call` alias is acceptable only when a runtime has not refreshed
to the new tool name.

If the local bridge feels stuck, paid calls start timing out, or the runtime
reports `ClosedResourceError`, call `sap_payments_process_status` before
retrying. It reports the bridge PID, parent runtime, profile/runtime lock, and
possible duplicate SAP MCP processes. Do not kill bridge processes during an
active MCP session; fully quit and reopen the agent runtime so stdio reconnects
cleanly.

The bridge is expected to run as one process per SAP profile/runtime. Current
configs set `SAP_MCP_RUNTIME_ID`; if a runtime omits it, the bridge falls back
to a stable `default-runtime` lock rather than a parent-PID lock. A second live
bridge for the same profile/runtime fails fast, and orphaned bridge-only
processes exit when their parent runtime is gone.

For wallet/profile questions, prefer `sap_payments_wallet_guard` plus
`sap_payments_profile_current` over shell commands. The agent may report the
active profile name and signer public key, but must not read local wallet files,
print keypair paths, create `.js`/`.mjs` signing scripts, or infer a private key
location from runtime config.

If an agent accidentally routes a free hosted tool through
`sap_payments_call_paid_tool`, the bridge returns the normal tool response with
`paymentCharged:false` and `freeToolBypass:true`. This is not an error and no
USDC was spent. For speed, still call known free tools directly through hosted
`sap` when possible.

For external x402 agents discovered through SAP registry metadata, do not
hand-roll HTTP payment scripts. Call `sap_payments_call_external_x402` with
`url`, `method`, optional JSON `body`, `maxPriceUsd`, `maxAttempts`, and
`confirm: true`. Use this for non-SAP-hosted HTTP providers such as another
agent's own x402 endpoint. It fetches the external 402 challenge, signs locally,
retries the same HTTP request with `PAYMENT-SIGNATURE`, and returns the response
plus receipt without exposing keypair bytes.

For hosted-user SAP agent registration, do not retry hosted
`sap_register_agent` after `hosted_local_signer_required`. The hosted server is
accountless by design and cannot sign user-owned registry writes. Call local
`sap_payments_register_agent` with the same registration fields and
`confirm: true`; it uses the active local SAP MCP profile signer, submits the
SAP registry transaction locally, and does not charge a hosted x402 access fee.
After it returns, verify `success`, `agentRegistered`, `confirmationStatus`,
`agentPda`, `protocolComplete`, and `protocolFee.status`. The expected protocol
fee is `100000000` lamports to treasury
`J7PyZAGKvprCz4SQ5DKBLAHstJxgVqZcz6kguUoWpP7P`. `success: true` means the agent
account and protocol fee invariant were both verified. If `success` is false
while `agentRegistered` is true, the account may exist but registration is not
SAP protocol-complete; report that state and do not retry automatically.

For hosted-user SAP agent profile updates, do not retry hosted
`sap_update_agent` after `hosted_local_signer_required`. Call local
`sap_payments_update_agent` with the intended replacement fields and
`confirm: true`; it signs locally and does not charge a hosted x402 access fee.
Use this for agent picture/profile metadata by first uploading the image or
metadata JSON to a public URI such as IPFS, Arweave, Kommodo, or HTTPS, then
setting `agentUri` or `metadataUri`. Do not use desktop file paths.
After update, fetch the agent profile again and verify the changed fields.

If the hosted paid tool returns `transactionBase64`, `transaction`, or an
unsigned transaction object, call `sap_payments_finalize_transaction` with
`confirm: true`. Set `submit: false` for preview/sign only, or `submit: true`
after the user approves execution. With `submit: true`, the bridge submits
already-signed bytes through `https://mcp.sap.oobeprotocol.ai/tx/submit` by
default and returns `confirmationStatus` plus `retrySafe`. Treat
`expired_or_not_landed` as unresolved, not success. Never create temporary
signing scripts, read keypair JSON, or call hosted `sap_sign_transaction` for
user-owned signatures.

For Escrow V2 hosted workflows, use the unsigned builder family first:
`sap_escrow_build_create_transaction`,
`sap_escrow_build_deposit_transaction`,
`sap_escrow_build_settle_transaction`,
`sap_escrow_build_finalize_transaction`,
`sap_escrow_build_withdraw_transaction`, or
`sap_escrow_build_close_transaction`, then finalize locally with
`sap_payments_finalize_transaction`. Use direct escrow write tools only when a
local SAP MCP profile with signer is the selected runtime.

Use low-level helpers only for custom clients:

- `sap_payments_prepare_challenge` returns the parsed hosted x402 challenge
  without signing.
- `sap_payments_sign_challenge` signs a parsed challenge and returns a one-time
  payment header. Treat that header as authorization material.
- `sap_payments_verify_receipt` decodes a `PAYMENT-RESPONSE` or
  `X-PAYMENT-RESPONSE` receipt.

The OOBE hosted server should not expose local signing helpers when it has no
local user wallet because payment signing belongs on the user's machine.

## Transient Settlement Errors

If a hosted paid call fails with `BlockhashNotFound`,
`transaction_simulation_failed`, `smart_wallet_simulation_failed`, `node is
behind`, `minimum context slot`, `fetch failed`, `gateway timeout`, or a
response marked `retryable: true`, treat it as a transient x402/Solana RPC
settlement failure. Do not say the SAP MCP server is down unless `/health`
also fails. Do not switch to terminal/direct RPC to bypass payment, and do not
reuse the old signed payment payload.

Correct recovery:

1. Call the local `sap_payments_call_paid_tool` bridge again with the same
   `toolName` and `arguments`.
2. Set `maxAttempts: 5` when the runtime supports it.
3. Let the helper create a fresh x402 challenge and payment payload for each
   attempt.
4. If all attempts fail, report that x402 settlement is temporarily unavailable
   and ask the user to retry or repair the facilitator/RPC deployment.

References: `USER_DOCS/03_X402_PAYSH_PAID_TOOL_RUNBOOK.md` and
`docs/06_X402_PAYSH_MONETIZATION_SETTLEMENT.md`.

## Safety

Payment and subscription operations move funds or create future obligations.
Respect `maxTxValueSol`, `dailyLimitSol`, and `requireApprovalAboveSol`.
Do not log private key material, keypair bytes, or raw payment signatures.
