agentcash
Version:
Generic MCP server for calling x402-protected APIs with automatic payment handling
122 lines (120 loc) • 4.05 kB
JavaScript
import {
createTempoClient,
deleteStoredChannel,
findStoredChannel,
mppErr,
mppOk,
mppResultFromPromise,
safeGetMppChallenge,
sessionCloseFailedErr
} from "./chunk-H2JGMFEG.js";
import {
safeFetch,
safeReadResponseText
} from "./chunk-RAS5DZPQ.js";
// src/operations/sessions/close.ts
import { Mppx, tempo as tempoMethod } from "mppx/client";
import { Session } from "mppx/tempo";
async function closeMppSession(input, options) {
const { surface, wallets } = options;
const { channelId, url, cumulativeAmountRaw } = input;
const stored = findStoredChannel(wallets.evm.address, channelId);
if (!stored) {
return mppErr(surface, {
cause: "mpp_session_close_no_channel",
message: `No tracked MPP session channel ${channelId} for wallet ${wallets.evm.address}. agentcash records open channels per wallet; there is nothing to close (it may already be closed, or was opened by a different client).`
});
}
const probeResult = await safeFetch(
surface,
new Request(url, { method: "POST" })
);
if (probeResult.isErr()) {
return mppErr(
surface,
sessionCloseFailedErr(
probeResult.error.message,
`Failed to probe ${url} for a session challenge`
)
);
}
const probeResponse = probeResult.value;
if (probeResponse.status !== 402) {
return mppErr(surface, {
cause: "mpp_session_close_no_challenge",
message: `Expected a 402 session challenge from ${url}, received ${probeResponse.status} ${probeResponse.statusText}. The endpoint may not be MPP-protected or the channel has already been closed.`
});
}
const challengeResult = safeGetMppChallenge(surface, probeResponse);
if (challengeResult.isErr()) {
return challengeResult;
}
const challenge = challengeResult.value;
if (challenge.intent !== "session") {
return mppErr(surface, {
cause: "mpp_session_close_no_challenge",
message: `${url} returned a ${challenge.method}:${challenge.intent} challenge, not a session challenge.`
});
}
const cumulativeRaw = cumulativeAmountRaw ?? stored.cumulativeAmount;
const mppx = Mppx.create({
polyfill: false,
methods: [
tempoMethod({ account: wallets.evm, getClient: createTempoClient })
]
});
const credentialResult = await mppResultFromPromise(
surface,
mppx.createCredential(probeResponse, {
action: "close",
channelId: stored.channelId,
cumulativeAmountRaw: cumulativeRaw,
descriptor: stored.descriptor
}),
(e) => sessionCloseFailedErr(e, "Failed to sign close credential")
);
if (credentialResult.isErr()) {
return credentialResult;
}
const closeResult = await safeFetch(
surface,
new Request(url, {
method: "POST",
headers: { Authorization: credentialResult.value }
})
);
if (closeResult.isErr()) {
return mppErr(
surface,
sessionCloseFailedErr(
closeResult.error.message,
`Close POST to ${url} failed`
)
);
}
const closeResponse = closeResult.value;
if (!closeResponse.ok) {
const body = await safeReadResponseText(surface, closeResponse).unwrapOr(
""
);
const detail = body ? `: ${body}` : "";
return mppErr(
surface,
sessionCloseFailedErr(
`Server rejected close credential with ${closeResponse.status} ${closeResponse.statusText}${detail}. The cumulative-amount may be below the server's voucher state \u2014 retry with --cumulative-amount-raw set to the server's expected value.`
)
);
}
const receiptHeader = closeResponse.headers.get("Payment-Receipt");
const receipt = receiptHeader ? Session.Precompile.Receipt.deserializeSessionReceipt(receiptHeader) : null;
deleteStoredChannel(wallets.evm.address, stored.channelId);
return mppOk({
channelId: stored.channelId,
cumulativeAmount: receipt?.spent ?? cumulativeRaw,
...receipt?.txHash ? { transactionHash: receipt.txHash } : {}
});
}
export {
closeMppSession
};
//# sourceMappingURL=chunk-FRESP5ZE.js.map