mppx 0.21.3 → 0.22.0
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.
- package/CHANGELOG.md +26 -0
- package/dist/BodyDigest.d.ts +3 -3
- package/dist/BodyDigest.js +5 -3
- package/dist/Challenge.js +12 -2
- package/dist/Credential.js +9 -1
- package/dist/Errors.d.ts +62 -8
- package/dist/Errors.js +57 -6
- package/dist/Store.d.ts +7 -4
- package/dist/Store.js +18 -8
- package/dist/cli/cli.js +135 -135
- package/dist/cli/internal.js +1 -1
- package/dist/cli/plugins/index.js +12 -12
- package/dist/client/Budget.d.ts +49 -0
- package/dist/client/Budget.js +101 -0
- package/dist/client/Mppx.d.ts +8 -3
- package/dist/client/Mppx.js +55 -13
- package/dist/client/Spend.d.ts +134 -0
- package/dist/client/Spend.js +58 -0
- package/dist/client/core.d.ts +2 -0
- package/dist/client/core.js +2 -0
- package/dist/client/internal/Fetch.d.ts +23 -3
- package/dist/client/internal/Fetch.js +155 -37
- package/dist/client/internal/FundsMoved.d.ts +9 -0
- package/dist/client/internal/FundsMoved.js +18 -0
- package/dist/client/internal/SpendGate.d.ts +136 -0
- package/dist/client/internal/SpendGate.js +608 -0
- package/dist/client/internal/SpendHooks.d.ts +42 -0
- package/dist/client/internal/SpendHooks.js +36 -0
- package/dist/client/internal/protocols/Mcp.d.ts +9 -0
- package/dist/client/internal/protocols/Mcp.js +27 -0
- package/dist/client/internal/protocols/Mpp.js +20 -3
- package/dist/client/internal/protocols/Shared.js +29 -3
- package/dist/evm/client/Charge.js +20 -8
- package/dist/extensions/identity/erc8004/server/index.d.ts +7 -1
- package/dist/extensions/identity/erc8004/server/index.js +13 -1
- package/dist/extensions/identity/link/client/index.js +57 -5
- package/dist/identity/Client.d.ts +7 -3
- package/dist/identity/Client.js +178 -13
- package/dist/identity/Types.d.ts +2 -1
- package/dist/integrations/x402/Negotiator.js +4 -1
- package/dist/integrations/x402/Solana.d.ts +75 -0
- package/dist/integrations/x402/Solana.js +143 -0
- package/dist/internal/challengeMeta.d.ts +17 -2
- package/dist/internal/challengeMeta.js +35 -7
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/mcp/client/McpClient.d.ts +6 -1
- package/dist/mcp/client/McpClient.js +48 -10
- package/dist/middlewares/express.d.ts +1 -1
- package/dist/server/Mppx.d.ts +12 -1
- package/dist/server/Mppx.js +58 -6
- package/dist/server/Request.d.ts +1 -1
- package/dist/server/Transport.js +46 -2
- package/dist/server/internal/host.js +5 -2
- package/dist/stripe/server/internal/html.gen.js +1 -1
- package/dist/tempo/client/Charge.js +81 -17
- package/dist/tempo/server/Charge.d.ts +7 -1
- package/dist/tempo/server/Charge.js +98 -12
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/client/SessionManager.js +3 -0
- package/dist/x402/server/EvmCharge.js +3 -0
- package/package.json +1 -1
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { HTTPRequestContext } from '@x402/core/server';
|
|
2
|
+
import type { PaymentRequired, PaymentRequirements } from '@x402/core/types';
|
|
3
|
+
import * as z from '../../zod.js';
|
|
4
|
+
import type { Config } from './Evm.js';
|
|
5
|
+
/**
|
|
6
|
+
* Solana clusters by CAIP-2 network, named as the `solana/charge` method names them
|
|
7
|
+
* (`methodDetails.network`).
|
|
8
|
+
*/
|
|
9
|
+
export declare const networks: {
|
|
10
|
+
readonly 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': 'mainnet';
|
|
11
|
+
readonly 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1': 'devnet';
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The fee-sponsored, server-broadcast subset of the `solana/charge` method (the same wire
|
|
15
|
+
* format as `@solana/mpp`'s `solana.charge`), so a client that pays `solana/charge` pays it.
|
|
16
|
+
* Only what an x402 `exact` facilitator can settle is offered: an SPL transfer the client
|
|
17
|
+
* partially signs, with the facilitator as fee payer.
|
|
18
|
+
*/
|
|
19
|
+
export declare const charge: {
|
|
20
|
+
readonly name: "solana";
|
|
21
|
+
readonly intent: "charge";
|
|
22
|
+
readonly schema: {
|
|
23
|
+
credential: {
|
|
24
|
+
payload: z.ZodMiniObject<{
|
|
25
|
+
transaction: z.ZodMiniString<string>;
|
|
26
|
+
type: z.ZodMiniLiteral<"transaction">;
|
|
27
|
+
}, z.core.$strip>;
|
|
28
|
+
};
|
|
29
|
+
request: z.ZodMiniObject<{
|
|
30
|
+
amount: z.ZodMiniString<string>;
|
|
31
|
+
currency: z.ZodMiniString<string>;
|
|
32
|
+
description: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
33
|
+
externalId: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
34
|
+
methodDetails: z.ZodMiniObject<{
|
|
35
|
+
decimals: z.ZodMiniNumber<number>;
|
|
36
|
+
feePayer: z.ZodMiniLiteral<true>;
|
|
37
|
+
feePayerKey: z.ZodMiniString<string>;
|
|
38
|
+
network: z.ZodMiniEnum<{
|
|
39
|
+
devnet: "devnet";
|
|
40
|
+
mainnet: "mainnet";
|
|
41
|
+
}>;
|
|
42
|
+
}, z.core.$strip>;
|
|
43
|
+
recipient: z.ZodMiniString<string>;
|
|
44
|
+
}, z.core.$strip>;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Creates a native `solana/charge` MPP handler backed by a compatible x402 Solana `exact`
|
|
49
|
+
* requirement. The client's partially signed transaction is verified and settled by the route's
|
|
50
|
+
* x402 facilitator, exactly as an x402 payment would be.
|
|
51
|
+
*/
|
|
52
|
+
export declare function createHandler(parameters: {
|
|
53
|
+
config: Config;
|
|
54
|
+
context: HTTPRequestContext;
|
|
55
|
+
paymentRequired: PaymentRequired;
|
|
56
|
+
}): ((request: Request) => Promise<{
|
|
57
|
+
payment: {
|
|
58
|
+
challenge: Response;
|
|
59
|
+
rejection?: import("../../identity/Types.js").Rejection | undefined;
|
|
60
|
+
status: 402;
|
|
61
|
+
} | {
|
|
62
|
+
status: 200;
|
|
63
|
+
challenge?: import("../../Challenge.js").Challenge | undefined;
|
|
64
|
+
identity?: import("../../identity/Types.js").Results | undefined;
|
|
65
|
+
withReceipt: import("../../server/Transport.js").WithReceipt<import("../../server/Transport.js").Http>;
|
|
66
|
+
};
|
|
67
|
+
skipHandlerResponse: Response | undefined;
|
|
68
|
+
}>) | undefined;
|
|
69
|
+
/**
|
|
70
|
+
* The first x402 requirement a `solana/charge` credential can satisfy: `exact` on a known
|
|
71
|
+
* Solana cluster, with a facilitator fee payer and no seller memo (a `solana/charge` client does
|
|
72
|
+
* not write x402's `extra.memo`). Routes with x402 extensions are left to x402.
|
|
73
|
+
*/
|
|
74
|
+
export declare function selectRequirement(paymentRequired: PaymentRequired): PaymentRequirements | undefined;
|
|
75
|
+
//# sourceMappingURL=Solana.d.ts.map
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { VerificationFailedError } from '../../Errors.js';
|
|
2
|
+
import * as Expires from '../../Expires.js';
|
|
3
|
+
import * as Method from '../../Method.js';
|
|
4
|
+
import * as Receipt from '../../Receipt.js';
|
|
5
|
+
import * as Mppx from '../../server/Mppx.js';
|
|
6
|
+
import * as z from '../../zod.js';
|
|
7
|
+
/**
|
|
8
|
+
* Solana clusters by CAIP-2 network, named as the `solana/charge` method names them
|
|
9
|
+
* (`methodDetails.network`).
|
|
10
|
+
*/
|
|
11
|
+
export const networks = {
|
|
12
|
+
'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': 'mainnet',
|
|
13
|
+
'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1': 'devnet',
|
|
14
|
+
};
|
|
15
|
+
const base58 = z.string().check(z.regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'Invalid Solana address'));
|
|
16
|
+
/**
|
|
17
|
+
* The fee-sponsored, server-broadcast subset of the `solana/charge` method (the same wire
|
|
18
|
+
* format as `@solana/mpp`'s `solana.charge`), so a client that pays `solana/charge` pays it.
|
|
19
|
+
* Only what an x402 `exact` facilitator can settle is offered: an SPL transfer the client
|
|
20
|
+
* partially signs, with the facilitator as fee payer.
|
|
21
|
+
*/
|
|
22
|
+
export const charge = Method.from({
|
|
23
|
+
name: 'solana',
|
|
24
|
+
intent: 'charge',
|
|
25
|
+
schema: {
|
|
26
|
+
credential: {
|
|
27
|
+
payload: z.object({
|
|
28
|
+
transaction: z.string().check(z.minLength(1)),
|
|
29
|
+
type: z.literal('transaction'),
|
|
30
|
+
}),
|
|
31
|
+
},
|
|
32
|
+
request: z.object({
|
|
33
|
+
amount: z.string().check(z.regex(/^\d+$/, 'Invalid atomic amount')),
|
|
34
|
+
currency: base58,
|
|
35
|
+
description: z.optional(z.string()),
|
|
36
|
+
externalId: z.optional(z.string()),
|
|
37
|
+
methodDetails: z.object({
|
|
38
|
+
decimals: z.number(),
|
|
39
|
+
feePayer: z.literal(true),
|
|
40
|
+
feePayerKey: base58,
|
|
41
|
+
network: z.enum(['devnet', 'mainnet']),
|
|
42
|
+
}),
|
|
43
|
+
recipient: base58,
|
|
44
|
+
}),
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
/**
|
|
48
|
+
* Creates a native `solana/charge` MPP handler backed by a compatible x402 Solana `exact`
|
|
49
|
+
* requirement. The client's partially signed transaction is verified and settled by the route's
|
|
50
|
+
* x402 facilitator, exactly as an x402 payment would be.
|
|
51
|
+
*/
|
|
52
|
+
export function createHandler(parameters) {
|
|
53
|
+
const requirement = selectRequirement(parameters.paymentRequired);
|
|
54
|
+
if (!requirement)
|
|
55
|
+
return undefined;
|
|
56
|
+
const decimals = parameters.config.server.getAssetDecimalsForRequirements(requirement);
|
|
57
|
+
const method = Method.toServer(charge, {
|
|
58
|
+
async verify({ credential }) {
|
|
59
|
+
const reference = await settle({
|
|
60
|
+
context: parameters.context,
|
|
61
|
+
paymentRequired: parameters.paymentRequired,
|
|
62
|
+
requirement,
|
|
63
|
+
server: parameters.config.server,
|
|
64
|
+
transaction: credential.payload.transaction,
|
|
65
|
+
});
|
|
66
|
+
return Receipt.from({
|
|
67
|
+
method: charge.name,
|
|
68
|
+
reference,
|
|
69
|
+
status: 'success',
|
|
70
|
+
timestamp: new Date().toISOString(),
|
|
71
|
+
});
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
const payment = Mppx.create({
|
|
75
|
+
methods: [method],
|
|
76
|
+
...(parameters.config.realm ? { realm: parameters.config.realm } : {}),
|
|
77
|
+
secretKey: parameters.config.secretKey,
|
|
78
|
+
});
|
|
79
|
+
const description = parameters.paymentRequired.resource.description;
|
|
80
|
+
const options = {
|
|
81
|
+
amount: requirement.amount,
|
|
82
|
+
currency: requirement.asset,
|
|
83
|
+
...(description ? { description } : {}),
|
|
84
|
+
expires: Expires.seconds(requirement.maxTimeoutSeconds),
|
|
85
|
+
methodDetails: {
|
|
86
|
+
decimals,
|
|
87
|
+
feePayer: true,
|
|
88
|
+
feePayerKey: requirement.extra.feePayer,
|
|
89
|
+
network: networks[requirement.network],
|
|
90
|
+
},
|
|
91
|
+
recipient: requirement.payTo,
|
|
92
|
+
scope: parameters.paymentRequired.resource.url,
|
|
93
|
+
};
|
|
94
|
+
const handler = payment.compose([payment.solana.charge, options]);
|
|
95
|
+
return async (request) => ({
|
|
96
|
+
payment: await handler(request),
|
|
97
|
+
skipHandlerResponse: undefined,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The first x402 requirement a `solana/charge` credential can satisfy: `exact` on a known
|
|
102
|
+
* Solana cluster, with a facilitator fee payer and no seller memo (a `solana/charge` client does
|
|
103
|
+
* not write x402's `extra.memo`). Routes with x402 extensions are left to x402.
|
|
104
|
+
*/
|
|
105
|
+
export function selectRequirement(paymentRequired) {
|
|
106
|
+
if (paymentRequired.extensions && Object.keys(paymentRequired.extensions).length > 0)
|
|
107
|
+
return undefined;
|
|
108
|
+
return paymentRequired.accepts.find((requirement) => {
|
|
109
|
+
if (requirement.scheme !== 'exact')
|
|
110
|
+
return false;
|
|
111
|
+
if (!(requirement.network in networks))
|
|
112
|
+
return false;
|
|
113
|
+
if (requirement.extra?.memo !== undefined)
|
|
114
|
+
return false;
|
|
115
|
+
const { feePayer } = requirement.extra ?? {};
|
|
116
|
+
return (typeof feePayer === 'string' &&
|
|
117
|
+
base58.safeParse(feePayer).success &&
|
|
118
|
+
base58.safeParse(requirement.asset).success &&
|
|
119
|
+
base58.safeParse(requirement.payTo).success &&
|
|
120
|
+
/^\d+$/.test(requirement.amount));
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
async function settle(parameters) {
|
|
124
|
+
const paymentPayload = {
|
|
125
|
+
accepted: parameters.requirement,
|
|
126
|
+
payload: { transaction: parameters.transaction },
|
|
127
|
+
resource: parameters.paymentRequired.resource,
|
|
128
|
+
x402Version: 2,
|
|
129
|
+
};
|
|
130
|
+
const transportContext = { request: parameters.context };
|
|
131
|
+
const verified = await parameters.server.verifyPayment(paymentPayload, parameters.requirement, parameters.paymentRequired.extensions, transportContext);
|
|
132
|
+
if (!verified.isValid)
|
|
133
|
+
throw new VerificationFailedError({
|
|
134
|
+
reason: verified.invalidMessage ?? verified.invalidReason ?? 'x402 verification failed',
|
|
135
|
+
});
|
|
136
|
+
const settled = await parameters.server.settlePayment(paymentPayload, parameters.requirement, parameters.paymentRequired.extensions, transportContext);
|
|
137
|
+
if (!settled.success)
|
|
138
|
+
throw new VerificationFailedError({
|
|
139
|
+
reason: settled.errorMessage ?? settled.errorReason ?? 'x402 settlement failed',
|
|
140
|
+
});
|
|
141
|
+
return settled.transaction;
|
|
142
|
+
}
|
|
143
|
+
//# sourceMappingURL=Solana.js.map
|
|
@@ -1,5 +1,20 @@
|
|
|
1
|
-
/**
|
|
2
|
-
export declare
|
|
1
|
+
/** Reserved metadata key for HMAC-bound, per-issuance challenge randomness. */
|
|
2
|
+
export declare const nonceKey = "_mpp_nonce";
|
|
3
|
+
/**
|
|
4
|
+
* Adds fresh issuance randomness (16 random bytes, base64url without padding) under
|
|
5
|
+
* `_mpp_nonce` while preserving application and route metadata. With `enabled: false`,
|
|
6
|
+
* returns the metadata unchanged.
|
|
7
|
+
*/
|
|
8
|
+
export declare function withNonce(meta: Record<string, string> | undefined, enabled?: boolean): Record<string, string> | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* Whether the challenge carries a per-issuance nonce (`_mpp_nonce`, or `_mppx_nonce` from
|
|
11
|
+
* earlier releases). Reads `opaque` when present, the value the challenge HMAC covers, and
|
|
12
|
+
* `meta` only otherwise.
|
|
13
|
+
*/
|
|
14
|
+
export declare function hasNonce(challenge: {
|
|
15
|
+
meta?: Record<string, string> | undefined;
|
|
16
|
+
opaque?: string | undefined;
|
|
17
|
+
}): boolean;
|
|
3
18
|
/** Sets the expiry grace marker when `grace` is true and removes any copy of it otherwise. */
|
|
4
19
|
export declare function withExpiryGrace(meta: Record<string, string> | undefined, grace: boolean): Record<string, string> | undefined;
|
|
5
20
|
/**
|
|
@@ -1,11 +1,39 @@
|
|
|
1
|
-
import { Secp256k1 } from 'ox';
|
|
1
|
+
import { Base64, Secp256k1 } from 'ox';
|
|
2
2
|
import * as PaymentRequest from '../PaymentRequest.js';
|
|
3
3
|
/** Reserved metadata key for HMAC-bound, per-issuance challenge randomness. */
|
|
4
|
-
const nonceKey = '
|
|
5
|
-
/**
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
export const nonceKey = '_mpp_nonce';
|
|
5
|
+
/** Nonce key of earlier mppx releases: still ignored when comparing route metadata. */
|
|
6
|
+
const legacyNonceKey = '_mppx_nonce';
|
|
7
|
+
/**
|
|
8
|
+
* Adds fresh issuance randomness (16 random bytes, base64url without padding) under
|
|
9
|
+
* `_mpp_nonce` while preserving application and route metadata. With `enabled: false`,
|
|
10
|
+
* returns the metadata unchanged.
|
|
11
|
+
*/
|
|
12
|
+
export function withNonce(meta, enabled = true) {
|
|
13
|
+
if (!enabled)
|
|
14
|
+
return meta;
|
|
15
|
+
// Ox's key generation uses runtime-specific secure randomness, including Node without global
|
|
16
|
+
// Web Crypto; 16 of its 32 uniformly random bytes make the nonce.
|
|
17
|
+
const random = Secp256k1.randomPrivateKey({ as: 'Bytes' }).slice(0, 16);
|
|
18
|
+
const nonce = Base64.fromBytes(random, { url: true, pad: false });
|
|
19
|
+
return { ...meta, [nonceKey]: nonce };
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Whether the challenge carries a per-issuance nonce (`_mpp_nonce`, or `_mppx_nonce` from
|
|
23
|
+
* earlier releases). Reads `opaque` when present, the value the challenge HMAC covers, and
|
|
24
|
+
* `meta` only otherwise.
|
|
25
|
+
*/
|
|
26
|
+
export function hasNonce(challenge) {
|
|
27
|
+
const { meta, opaque } = challenge;
|
|
28
|
+
const has = (value) => typeof value?.[nonceKey] === 'string' || typeof value?.[legacyNonceKey] === 'string';
|
|
29
|
+
if (opaque === undefined)
|
|
30
|
+
return has(meta);
|
|
31
|
+
try {
|
|
32
|
+
return has(PaymentRequest.deserialize(opaque));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
9
37
|
}
|
|
10
38
|
/**
|
|
11
39
|
* Reserved metadata key marking a challenge whose method accepts some of its credentials for a
|
|
@@ -40,7 +68,7 @@ export function hasExpiryGrace(challenge) {
|
|
|
40
68
|
const legacyIdentityKey = '_mppx_identity';
|
|
41
69
|
/** Removes issuance-only metadata when comparing stable route requirements. */
|
|
42
70
|
export function routeMeta(meta) {
|
|
43
|
-
const { [nonceKey]: _, [
|
|
71
|
+
const { [nonceKey]: _, [legacyNonceKey]: __, [legacyIdentityKey]: ___, [expiryGraceKey]: ____, ...rest } = meta ?? {};
|
|
44
72
|
return Object.keys(rest).length ? rest : undefined;
|
|
45
73
|
}
|
|
46
74
|
//# sourceMappingURL=challengeMeta.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Current mppx package version. */
|
|
2
|
-
export declare const version = "0.
|
|
2
|
+
export declare const version = "0.22.0";
|
|
3
3
|
/** Canonical SDK identifier for this mppx release. */
|
|
4
|
-
export declare const sdkIdentifier = "mppx/0.
|
|
4
|
+
export declare const sdkIdentifier = "mppx/0.22.0";
|
|
5
5
|
//# sourceMappingURL=version.d.ts.map
|
package/dist/internal/version.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Generated by scripts/sync-version.ts.
|
|
2
2
|
/** Current mppx package version. */
|
|
3
|
-
export const version = '0.
|
|
3
|
+
export const version = '0.22.0';
|
|
4
4
|
/** Canonical SDK identifier for this mppx release. */
|
|
5
5
|
export const sdkIdentifier = `mppx/${version}`;
|
|
6
6
|
//# sourceMappingURL=version.js.map
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
2
2
|
import type { McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
3
3
|
import * as Challenge from '../../Challenge.js';
|
|
4
|
+
import * as SpendGate from '../../client/internal/SpendGate.js';
|
|
4
5
|
import * as AcceptPayment from '../../internal/AcceptPayment.js';
|
|
5
6
|
import * as core_Mcp from '../../Mcp.js';
|
|
6
7
|
import type * as Method from '../../Method.js';
|
|
@@ -35,6 +36,10 @@ export type CallToolResult = Awaited<ReturnType<Client['callTool']>> & {
|
|
|
35
36
|
* errors or as tool results carrying payment-required metadata. Calling
|
|
36
37
|
* `wrap()` again replaces the payment configuration.
|
|
37
38
|
*
|
|
39
|
+
* `maxPayment`, `authorize`, `funders` and `tokens` limit its payments as they do on
|
|
40
|
+
* `Mppx.create`. Set them here: an mppx fetch with spending options refuses the tool calls this
|
|
41
|
+
* client pays itself.
|
|
42
|
+
*
|
|
38
43
|
* @example
|
|
39
44
|
* ```ts
|
|
40
45
|
* import { Client } from '@modelcontextprotocol/sdk/client'
|
|
@@ -74,7 +79,7 @@ export declare namespace wrap {
|
|
|
74
79
|
* own a realm, so these signatures are refused unless their realm is listed here.
|
|
75
80
|
*/
|
|
76
81
|
trustedTempoProofRealms?: readonly string[] | undefined;
|
|
77
|
-
};
|
|
82
|
+
} & SpendGate.Config;
|
|
78
83
|
type McpClient<client extends Pick<Client, 'callTool'> = Pick<Client, 'callTool'>, methods extends Methods = DefaultMethods> = Omit<client, 'callTool'> & {
|
|
79
84
|
/** Call a tool with automatic payment handling. Preserves the MCP SDK signature. */
|
|
80
85
|
callTool: (params: CallToolParams, resultSchema?: CallToolResultSchema, options?: CallToolOptions<methods>) => Promise<CallToolResult>;
|
|
@@ -2,6 +2,8 @@ import * as Challenge from '../../Challenge.js';
|
|
|
2
2
|
import * as PendingSettlement from '../../client/internal/PendingSettlement.js';
|
|
3
3
|
import * as ProofRealm from '../../client/internal/ProofRealm.js';
|
|
4
4
|
import { adapterPaymentMetaKey } from '../../client/internal/protocols/Mcp.js';
|
|
5
|
+
import * as SpendGate from '../../client/internal/SpendGate.js';
|
|
6
|
+
import * as SpendHooks from '../../client/internal/SpendHooks.js';
|
|
5
7
|
import * as Credential from '../../Credential.js';
|
|
6
8
|
import * as Expires from '../../Expires.js';
|
|
7
9
|
import * as AcceptPayment from '../../internal/AcceptPayment.js';
|
|
@@ -22,6 +24,10 @@ const maxPaymentAttempts = 3;
|
|
|
22
24
|
* errors or as tool results carrying payment-required metadata. Calling
|
|
23
25
|
* `wrap()` again replaces the payment configuration.
|
|
24
26
|
*
|
|
27
|
+
* `maxPayment`, `authorize`, `funders` and `tokens` limit its payments as they do on
|
|
28
|
+
* `Mppx.create`. Set them here: an mppx fetch with spending options refuses the tool calls this
|
|
29
|
+
* client pays itself.
|
|
30
|
+
*
|
|
25
31
|
* @example
|
|
26
32
|
* ```ts
|
|
27
33
|
* import { Client } from '@modelcontextprotocol/sdk/client'
|
|
@@ -88,18 +94,23 @@ export function isPaymentRequiredError(error) {
|
|
|
88
94
|
}
|
|
89
95
|
/** @internal */
|
|
90
96
|
async function createCredential(challenge, config) {
|
|
91
|
-
const { context, method, signal } = config;
|
|
97
|
+
const { constraints, context, method, signal } = config;
|
|
92
98
|
if (challenge.expires)
|
|
93
99
|
Expires.assert(challenge.expires, challenge.id);
|
|
94
100
|
const parsedContext = method.context && context !== undefined ? method.context.parse(context) : undefined;
|
|
95
101
|
// A Zone withdrawal still settling is resumed for this challenge, not paid again.
|
|
96
|
-
return PendingSettlement.resume(() =>
|
|
97
|
-
? { challenge, context: parsedContext }
|
|
98
|
-
|
|
102
|
+
return PendingSettlement.resume(() => {
|
|
103
|
+
const parameters = parsedContext !== undefined ? { challenge, context: parsedContext } : { challenge };
|
|
104
|
+
if (constraints)
|
|
105
|
+
SpendHooks.constrain(parameters, constraints);
|
|
106
|
+
return method.createCredential(parameters);
|
|
107
|
+
}, { attempts: maxPaymentAttempts, signal });
|
|
99
108
|
}
|
|
100
109
|
function createPaymentAwareCallTool(callTool, config) {
|
|
101
110
|
const methods = config.methods.flat();
|
|
102
111
|
const paymentPreferences = AcceptPayment.resolve(methods, config.paymentPreferences);
|
|
112
|
+
// Validated here, so invalid spending options fail at `wrap()`.
|
|
113
|
+
const spender = SpendGate.from(SpendGate.pick(config));
|
|
103
114
|
const retryWithPayment = async (params, call, paymentRequired, cause, attemptsRemaining = maxPaymentAttempts) => {
|
|
104
115
|
const challenges = usableChallenges(paymentRequired.challenges);
|
|
105
116
|
const candidates = AcceptPayment.selectChallengeCandidates(challenges, methods, paymentPreferences.entries, call.context);
|
|
@@ -120,11 +131,23 @@ function createPaymentAwareCallTool(callTool, config) {
|
|
|
120
131
|
if (!approved)
|
|
121
132
|
throw new Error('Payment declined.', { cause });
|
|
122
133
|
}
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
134
|
+
const signal = call.requestOptions?.signal;
|
|
135
|
+
// Spending limits, authorization and funding run before any signing work.
|
|
136
|
+
const spend = SpendGate.payment(spender, selected.challenge, signal, selected.method);
|
|
137
|
+
let credential;
|
|
138
|
+
try {
|
|
139
|
+
credential = await spend.track((constraints) => createCredential(selected.challenge, {
|
|
140
|
+
constraints,
|
|
141
|
+
context: call.context,
|
|
142
|
+
method: selected.method,
|
|
143
|
+
signal,
|
|
144
|
+
}));
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
// A no-op once the credential committed it.
|
|
148
|
+
await spend.release();
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
128
151
|
const parsed = Credential.deserialize(credential);
|
|
129
152
|
try {
|
|
130
153
|
const retryResult = await callTool({
|
|
@@ -135,6 +158,10 @@ function createPaymentAwareCallTool(callTool, config) {
|
|
|
135
158
|
},
|
|
136
159
|
}, call.resultSchema, call.requestOptions);
|
|
137
160
|
const nextPaymentRequired = getPaymentRequiredMeta(retryResult);
|
|
161
|
+
// invalid-challenge answering the credential just sent can mean it was already settled
|
|
162
|
+
// (a replay): paying the fresh Challenge would pay twice, so the result is final.
|
|
163
|
+
if (nextPaymentRequired && isInvalidChallenge(nextPaymentRequired))
|
|
164
|
+
return withReceipt(retryResult);
|
|
138
165
|
if (nextPaymentRequired && attemptsRemaining > 1)
|
|
139
166
|
return retryWithPayment(params, call, nextPaymentRequired, retryResult, attemptsRemaining - 1);
|
|
140
167
|
return withReceipt(retryResult);
|
|
@@ -142,20 +169,26 @@ function createPaymentAwareCallTool(callTool, config) {
|
|
|
142
169
|
catch (error) {
|
|
143
170
|
if (!isPaymentRequiredError(error) || attemptsRemaining <= 1)
|
|
144
171
|
throw error;
|
|
172
|
+
if (isInvalidChallenge(error.data))
|
|
173
|
+
throw error;
|
|
145
174
|
return retryWithPayment(params, call, error.data, error, attemptsRemaining - 1);
|
|
146
175
|
}
|
|
147
176
|
};
|
|
148
177
|
return async (params, call) => {
|
|
178
|
+
// A credential the caller attached to the first call gets the same no-repay rule.
|
|
179
|
+
const credentialSent = params._meta?.[core_Mcp.credentialMetaKey] != null;
|
|
149
180
|
try {
|
|
150
181
|
const result = await callTool(params, call.resultSchema, call.requestOptions);
|
|
151
182
|
const paymentRequired = getPaymentRequiredMeta(result);
|
|
152
|
-
if (paymentRequired)
|
|
183
|
+
if (paymentRequired && !(credentialSent && isInvalidChallenge(paymentRequired)))
|
|
153
184
|
return retryWithPayment(params, call, paymentRequired, result);
|
|
154
185
|
return withReceipt(result);
|
|
155
186
|
}
|
|
156
187
|
catch (error) {
|
|
157
188
|
if (!isPaymentRequiredError(error))
|
|
158
189
|
throw error;
|
|
190
|
+
if (credentialSent && isInvalidChallenge(error.data))
|
|
191
|
+
throw error;
|
|
159
192
|
return retryWithPayment(params, call, error.data, error);
|
|
160
193
|
}
|
|
161
194
|
};
|
|
@@ -164,6 +197,11 @@ function getPaymentRequiredMeta(result) {
|
|
|
164
197
|
const data = result._meta?.[core_Mcp.paymentRequiredMetaKey];
|
|
165
198
|
return isPaymentRequiredData(data) ? data : undefined;
|
|
166
199
|
}
|
|
200
|
+
/** Whether payment-required data carries an invalid-challenge problem (such as a replayed credential). */
|
|
201
|
+
function isInvalidChallenge(data) {
|
|
202
|
+
return (data.problem?.type ===
|
|
203
|
+
'https://paymentauth.org/problems/invalid-challenge');
|
|
204
|
+
}
|
|
167
205
|
/**
|
|
168
206
|
* Validates payment-required data: challenges are validated, extra fields pass through. A
|
|
169
207
|
* well-formed challenge that selects an unsupported credential header is allowed here and skipped
|
|
@@ -25,7 +25,7 @@ export declare namespace Mppx {
|
|
|
25
25
|
}
|
|
26
26
|
/** Optional ingress validation shared by Express payment handlers. */
|
|
27
27
|
export type AdapterOptions = {
|
|
28
|
-
/** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it.
|
|
28
|
+
/** Exact incoming hosts, including ports. Treat the list as immutable; replace the array to change it. Required for signed identity requests unless a fixed Node host is configured; an empty list rejects all hosts. Configure trusted ingress to enforce the same list. */
|
|
29
29
|
allowedHosts?: readonly string[] | undefined;
|
|
30
30
|
};
|
|
31
31
|
/**
|
package/dist/server/Mppx.d.ts
CHANGED
|
@@ -352,6 +352,17 @@ type ChallengeFn<method extends Method.Method, defaults extends Record<string, u
|
|
|
352
352
|
export declare function create<const methods extends Methods, const transport extends Transport.AnyTransport = Transport.Http>(config: create.Config<methods, transport>): Mppx<methods, transport>;
|
|
353
353
|
export declare namespace create {
|
|
354
354
|
type Config<methods extends Methods = Methods, transport extends Transport.AnyTransport = Transport.Http> = {
|
|
355
|
+
/**
|
|
356
|
+
* Adds a fresh random nonce to every Challenge's `opaque` under `_mpp_nonce`, so each
|
|
357
|
+
* Challenge gets a unique ID. Route matching ignores it.
|
|
358
|
+
*
|
|
359
|
+
* With `false`, requests for the same route with the same `expires` get the same Challenge
|
|
360
|
+
* ID, so a payment bound to that ID could be redeemed by whichever requester presents it
|
|
361
|
+
* first. Tempo charge then accepts only pull (`transaction`) credentials and rejects push
|
|
362
|
+
* (`hash`, Zone) and proof credentials, so set its `supportedModes` to `['pull']`.
|
|
363
|
+
* @default true
|
|
364
|
+
*/
|
|
365
|
+
challengeNonce?: boolean | undefined;
|
|
355
366
|
/** Array of configured methods. @example [tempo()] */
|
|
356
367
|
methods: methods;
|
|
357
368
|
/** Uses `Payment-Authorization` for Payment credentials so `Authorization` remains available for application authentication. */
|
|
@@ -383,7 +394,7 @@ declare namespace MethodFn {
|
|
|
383
394
|
description?: string | undefined;
|
|
384
395
|
/** Optional challenge expiration timestamp (ISO 8601) or Date. */
|
|
385
396
|
expires?: z.DatetimeInput | undefined;
|
|
386
|
-
/** Optional server-defined correlation data serialized as `opaque`. `
|
|
397
|
+
/** Optional server-defined correlation data serialized as `opaque`. `_mpp_nonce` is reserved for a fresh server-generated issuance nonce, and `_mppx_expiry_grace` marks a challenge whose method accepts some credentials after it expires; clients MUST echo opaque unchanged. */
|
|
387
398
|
meta?: Record<string, string> | undefined;
|
|
388
399
|
/** Optional route/resource scope bound via reserved challenge metadata. */
|
|
389
400
|
scope?: string | undefined;
|