mcp-usage-control-mcp 1.0.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one of
111
+ the following places: within a NOTICE text file distributed as
112
+ part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,135 @@
1
+ # mcp-usage-control-mcp
2
+
3
+ MCP TypeScript SDK v2 adapter for `mcp-usage-control`.
4
+
5
+ > **Current distribution status:** this package is not published to npm yet. Use the repository checkout or locally packed `mcp-usage-control` + `mcp-usage-control-mcp` tarballs. See [Use from source / local tarballs](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/using-from-source.md) / [日本語](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/using-from-source.ja.md).
6
+
7
+ ## English
8
+
9
+ `protectTool()` wraps **single-round** `@modelcontextprotocol/server` v2 tool handlers with admission, cost-liable activation, lease heartbeat, MCP-aware result classification, and explicit settlement.
10
+
11
+ `protectMultiRoundTool()` is the opt-in wrapper for MCP v2 `input_required` flows. It keeps one logical usage reservation across fresh MCP retry requests instead of reserving again for every round.
12
+
13
+ For a tool with no input schema, set `noInput: true`. For input-schema tools, omit it. The adapter normalizes the SDK no-input callback/runtime shape without guessing whether `{}` is real input.
14
+
15
+ It distinguishes normal success, `{ isError: true }`, and thrown errors. Invalid/throwing cost classifiers cause the full reservation to be settled before `UsageClassificationError` is surfaced. Ambiguous settlement failures are surfaced as `UsageSettlementError` and are not blindly retried.
16
+
17
+ ### Returning a bounded remaining value
18
+
19
+ Successful core admission exposes the authoritative store-produced `remainingByBudget`. The MCP wrappers intentionally do not inject balances into handler results. If a tool must return a bounded remaining value to its consumer, use the core lifecycle directly at that integration point and select only the application-approved budget value:
20
+
21
+ ```ts
22
+ const admission = await control.reserve(request);
23
+ if (!admission.allowed) throw new UsageDeniedError(admission.reason);
24
+
25
+ const remaining = admission.remainingByBudget.find(
26
+ balance => balance.key === expectedBudgetKey,
27
+ )?.remaining;
28
+
29
+ const lease = admission.lease;
30
+ await lease.markLiable();
31
+ const value = await runTool();
32
+ await lease.settle(1, 'success');
33
+
34
+ return {
35
+ content: [
36
+ {
37
+ type: 'text',
38
+ text: JSON.stringify({ value, ...(remaining === undefined ? {} : { remaining }) }),
39
+ },
40
+ ],
41
+ };
42
+ ```
43
+
44
+ Do not recompute the balance from configured limits in the MCP layer; the usage store is authoritative. Budget keys can contain application-sensitive or high-cardinality identity, so do not expose the key itself to the model/client or promote it to metric labels by default. Prefer a single numeric value selected by application policy.
45
+
46
+ ### Multi-round trust boundary
47
+
48
+ MCP `requestState` round-trips through the client and is untrusted. `protectMultiRoundTool()` therefore does **not** put the usage lease in client state and does not trust a client-supplied flow identifier by itself.
49
+
50
+ - configure the MCP server's `requestState.verify` hook, for example with the official SDK `createRequestStateCodec()`;
51
+ - pass the matching mint function through `requestState.mint`;
52
+ - keep `McpUsageFlowRecord` server-side;
53
+ - use a `McpUsageFlowStore` whose `consume()` atomically compares the principal/tool/args binding and consumes the flow exactly once;
54
+ - use `MemoryMcpUsageFlowStore` only for tests or a single-process server, and instantiate it outside a per-request `createMcpHandler` factory;
55
+ - distributed servers must provide a durable/shared implementation with the same atomic compare-and-consume contract.
56
+
57
+ The wrapper owns the wire `requestState`. A handler-authored `requestState` is retained only in trusted server-side flow storage and is supplied on the next round as `flow.applicationRequestState`.
58
+
59
+ `suspendTtlMs` is explicit. The lease is already cost-liable before the application handler runs; if a suspended/claimed flow is abandoned, expiry conservatively retains the full reservation rather than refunding a possibly executed operation.
60
+
61
+ Resume tokens are one-time. A concurrent or repeated resume after one caller has claimed the token fails closed instead of re-running the handler. This prevents duplicate execution/reservation, but it is not a general exactly-once side-effect or response-replay mechanism; applications that require replay of a completed business result need their own business-idempotency/result store.
62
+
63
+ - [Current source/tarball usage](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/using-from-source.md)
64
+ - [MCP integration](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/mcp-integration.md)
65
+ - [API reference](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/api-reference.md)
66
+ - [Architecture](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/architecture.md)
67
+
68
+ The application remains responsible for trusted principal/tenant derivation, authentication/authorization, retry-stable logical operation IDs, durable flow storage when horizontally scaled, and provider-specific fencing after lease loss.
69
+
70
+ ## 日本語
71
+
72
+ `protectTool()` は `@modelcontextprotocol/server` v2の **single-round** tool handlerをusage admission、cost-liable activation、lease heartbeat、MCP-aware result classification、explicit settlementでwrapします。
73
+
74
+ `protectMultiRoundTool()` はMCP v2 `input_required` 向けのopt-in wrapperです。fresh MCP retry requestごとに再reserveせず、1つのlogical usage reservationをround間で維持します。
75
+
76
+ input schemaがないtoolでは `noInput: true` を指定し、input schemaありでは省略します。SDKのno-input callback / runtime shapeをnormalizeしますが、`{}` がreal inputかどうかを推測しません。
77
+
78
+ normal success、`{ isError: true }`、thrown errorを区別します。classifierがthrow / invalid unitsを返した場合はfull reservationをsettleしてから `UsageClassificationError` を表面化します。ambiguous settlement failureは `UsageSettlementError` として表面化しblind retryしません。
79
+
80
+ ### boundedなremaining値を返す
81
+
82
+ coreのadmission成功結果には、authoritative storeが算出した `remainingByBudget` が含まれます。MCP wrapperはbalanceをhandler resultへ自動注入しません。tool consumerへboundedなremaining値を返したい場合は、そのintegration pointだけcore lifecycleを直接使い、applicationが許可したbudgetの値だけを選択します。
83
+
84
+ ```ts
85
+ const admission = await control.reserve(request);
86
+ if (!admission.allowed) throw new UsageDeniedError(admission.reason);
87
+
88
+ const remaining = admission.remainingByBudget.find(
89
+ balance => balance.key === expectedBudgetKey,
90
+ )?.remaining;
91
+
92
+ const lease = admission.lease;
93
+ await lease.markLiable();
94
+ const value = await runTool();
95
+ await lease.settle(1, 'success');
96
+
97
+ return {
98
+ content: [
99
+ {
100
+ type: 'text',
101
+ text: JSON.stringify({ value, ...(remaining === undefined ? {} : { remaining }) }),
102
+ },
103
+ ],
104
+ };
105
+ ```
106
+
107
+ MCP layerでconfigured limitからbalanceを再計算しないでください。usage storeがsource of truthです。budget keyにはapplication-sensitive / high-cardinalityなidentityが含まれ得るため、key自体をmodel/clientへ出したりmetric labelへ自動昇格したりしません。application policyで選択した単一のnumeric valueだけを返す形を推奨します。
108
+
109
+ ### Multi-roundのtrust boundary
110
+
111
+ MCP `requestState` はclientを往復するためuntrustedです。`protectMultiRoundTool()` はusage leaseをclient stateへ入れず、client supplied flow IDだけをaccounting authorityとして信用しません。
112
+
113
+ - MCP server側で `requestState.verify` を設定します。公式SDKの `createRequestStateCodec()` を利用できます。
114
+ - 対応するmint関数を `requestState.mint` へ渡します。
115
+ - `McpUsageFlowRecord` はserver-sideに保持します。
116
+ - `McpUsageFlowStore.consume()` はprincipal / tool / args bindingを比較し、matchしたflowだけをatomicにone-time consumeする必要があります。
117
+ - `MemoryMcpUsageFlowStore` はtestまたはsingle-process server専用です。per-request `createMcpHandler` factoryの外側で生成してください。
118
+ - horizontal scaleするserverでは同じatomic compare-and-consume contractを満たすshared/durable storeを用意してください。
119
+
120
+ wire上の `requestState` はwrapperが所有します。application handlerが返した `requestState` はtrusted server-side flow storageだけに保持し、次roundでは `flow.applicationRequestState` として渡します。
121
+
122
+ `suspendTtlMs` は明示必須です。application handlerへ入る前にleaseはすでにcost-liableなので、suspend / claim後にflowがabandonされた場合はexpiryでfull reservationを保守的に維持し、実行済みかもしれない処理をrefundしません。
123
+
124
+ resume tokenはone-timeです。同じtokenのconcurrent/repeated resumeは1 callerがclaimした後fail-closeし、handlerを再実行しません。これはduplicate execution / duplicate reservationを防ぎますが、汎用的なexactly-once side effectやcompleted response replayを保証するものではありません。business resultのreplayが必要なapplicationは既存のbusiness idempotency / result storeを併用してください。
125
+
126
+ - [現在のsource / tarball利用手順](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/using-from-source.ja.md)
127
+ - [MCP integration](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/mcp-integration.ja.md)
128
+ - [API reference](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/api-reference.ja.md)
129
+ - [Architecture](https://github.com/git-ksk/mcp-usage-control/blob/main/docs/architecture.ja.md)
130
+
131
+ trustedなprincipal / tenant derivation、authentication / authorization、retry-stable logical operation ID、horizontal scale時のdurable flow storage、lease loss後のprovider-specific fencingはapplication側の責務です。
132
+
133
+ ## Vector workloads (v0.7)
134
+
135
+ `protectTool()` remains the bounded scalar convenience wrapper. Heterogeneous request/token/compute workloads should use the explicit `VectorUsageControl` / `VectorUsageLease` lifecycle from `mcp-usage-control` so every required dimension is reserved, grown, and settled atomically before metered work proceeds.
@@ -0,0 +1,42 @@
1
+ import type { McpUsageFlowStore } from './index.js';
2
+ type MaybePromise<T> = T | Promise<T>;
3
+ export interface McpUsageFlowStoreConformanceHarness {
4
+ /** Return an isolated flow-store domain for one scenario. */
5
+ createStore(scenario: string): MaybePromise<McpUsageFlowStore>;
6
+ /** Wait until a flow with the supplied TTL is authoritatively expired. */
7
+ waitForFlowExpiry(ttlMs: number, scenario: string): MaybePromise<void>;
8
+ /** Optional cleanup for the isolated scenario domain. */
9
+ cleanup?(scenario: string): MaybePromise<void>;
10
+ /** Flow lifetime used by the expiry case. Defaults to 40 ms. */
11
+ flowTtlMs?: number;
12
+ /** Parallel consumers used by the one-time claim race. Defaults to 16. */
13
+ concurrency?: number;
14
+ }
15
+ export interface McpUsageFlowStoreConformanceCaseResult {
16
+ name: string;
17
+ passed: boolean;
18
+ error?: string;
19
+ }
20
+ export interface McpUsageFlowStoreConformanceReport {
21
+ passed: boolean;
22
+ cases: McpUsageFlowStoreConformanceCaseResult[];
23
+ }
24
+ export declare class McpUsageFlowStoreConformanceError extends Error {
25
+ readonly report: McpUsageFlowStoreConformanceReport;
26
+ constructor(report: McpUsageFlowStoreConformanceReport);
27
+ }
28
+ /**
29
+ * Verify the portable compare-and-consume contract required by
30
+ * protectMultiRoundTool().
31
+ *
32
+ * Passing proves behavioral one-time claim semantics, including the requirement
33
+ * that `consume()` reject expiry before returning a record using the store's own
34
+ * authoritative time domain. Callers treat a returned record as expiry-valid and
35
+ * do not re-check it against an unrelated host clock. Production-safe flow stores
36
+ * must additionally document durability/HA and prove that a lost consume ACK does
37
+ * not trigger caller-side blind retry/re-entry.
38
+ */
39
+ export declare function runMcpUsageFlowStoreConformance(harness: McpUsageFlowStoreConformanceHarness): Promise<McpUsageFlowStoreConformanceReport>;
40
+ export declare function assertMcpUsageFlowStoreConformance(harness: McpUsageFlowStoreConformanceHarness): Promise<McpUsageFlowStoreConformanceReport>;
41
+ export {};
42
+ //# sourceMappingURL=flow-store-conformance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow-store-conformance.d.ts","sourceRoot":"","sources":["../src/flow-store-conformance.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAEpB,KAAK,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEtC,MAAM,WAAW,mCAAmC;IAClD,6DAA6D;IAC7D,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,YAAY,CAAC,iBAAiB,CAAC,CAAC;IAE/D,0EAA0E;IAC1E,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IAEvE,yDAAyD;IACzD,OAAO,CAAC,CAAC,QAAQ,EAAE,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IAE/C,gEAAgE;IAChE,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,sCAAsC;IACrD,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,kCAAkC;IACjD,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,sCAAsC,EAAE,CAAC;CACjD;AAED,qBAAa,iCAAkC,SAAQ,KAAK;aAC9B,MAAM,EAAE,kCAAkC;gBAA1C,MAAM,EAAE,kCAAkC;CASvE;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,+BAA+B,CACnD,OAAO,EAAE,mCAAmC,GAC3C,OAAO,CAAC,kCAAkC,CAAC,CAkE7C;AAED,wBAAsB,kCAAkC,CACtD,OAAO,EAAE,mCAAmC,GAC3C,OAAO,CAAC,kCAAkC,CAAC,CAI7C"}
@@ -0,0 +1,178 @@
1
+ export class McpUsageFlowStoreConformanceError extends Error {
2
+ report;
3
+ constructor(report) {
4
+ const failed = report.cases.filter(result => !result.passed);
5
+ super(`McpUsageFlowStore conformance failed: ${failed
6
+ .map(result => `${result.name}: ${result.error ?? 'unknown failure'}`)
7
+ .join('; ')}`);
8
+ this.report = report;
9
+ this.name = 'McpUsageFlowStoreConformanceError';
10
+ }
11
+ }
12
+ /**
13
+ * Verify the portable compare-and-consume contract required by
14
+ * protectMultiRoundTool().
15
+ *
16
+ * Passing proves behavioral one-time claim semantics, including the requirement
17
+ * that `consume()` reject expiry before returning a record using the store's own
18
+ * authoritative time domain. Callers treat a returned record as expiry-valid and
19
+ * do not re-check it against an unrelated host clock. Production-safe flow stores
20
+ * must additionally document durability/HA and prove that a lost consume ACK does
21
+ * not trigger caller-side blind retry/re-entry.
22
+ */
23
+ export async function runMcpUsageFlowStoreConformance(harness) {
24
+ const flowTtlMs = harness.flowTtlMs ?? 40;
25
+ const concurrency = harness.concurrency ?? 16;
26
+ assertPositiveInteger(flowTtlMs, 'flowTtlMs');
27
+ assertPositiveInteger(concurrency, 'concurrency');
28
+ const cases = [];
29
+ await runCase(harness, cases, 'one-time-consume', async (store) => {
30
+ const record = flowRecord('flow-contract-one-time-0001', 5_000);
31
+ await store.suspend(record);
32
+ const first = await store.consume(record.flowId, record.binding);
33
+ assert(first !== undefined, 'first matching consume must return the flow');
34
+ assertRecordMatches(first, record);
35
+ const replay = await store.consume(record.flowId, record.binding);
36
+ assert(replay === undefined, 'matching flow must be consumed at most once');
37
+ });
38
+ await runCase(harness, cases, 'binding-mismatch-preserves-legitimate-flow', async (store) => {
39
+ const record = flowRecord('flow-contract-binding-0001', 5_000);
40
+ await store.suspend(record);
41
+ const mismatches = [
42
+ { ...record.binding, principalId: 'other-principal' },
43
+ { ...record.binding, tenantId: 'other-tenant' },
44
+ { ...record.binding, tool: 'other-tool' },
45
+ { ...record.binding, argsHash: 'b'.repeat(64) },
46
+ ];
47
+ for (const mismatch of mismatches) {
48
+ const result = await store.consume(record.flowId, mismatch);
49
+ assert(result === undefined, 'binding mismatch must not return trusted flow state');
50
+ }
51
+ const legitimate = await store.consume(record.flowId, record.binding);
52
+ assert(legitimate !== undefined, 'binding mismatch must not consume legitimate flow state');
53
+ assertRecordMatches(legitimate, record);
54
+ });
55
+ await runCase(harness, cases, 'concurrent-one-time-consume', async (store) => {
56
+ const record = flowRecord('flow-contract-concurrent-0001', 5_000);
57
+ await store.suspend(record);
58
+ const results = await Promise.all(Array.from({ length: concurrency }, () => store.consume(record.flowId, record.binding)));
59
+ const winners = results.filter((result) => result !== undefined);
60
+ assert(winners.length === 1, `expected exactly one consume winner, got ${winners.length}`);
61
+ assertRecordMatches(winners[0], record);
62
+ });
63
+ await runCase(harness, cases, 'duplicate-suspend-fails', async (store) => {
64
+ const record = flowRecord('flow-contract-duplicate-0001', 5_000);
65
+ await store.suspend(record);
66
+ await assertRejects(() => Promise.resolve(store.suspend(record)), 'duplicate flow ID must fail');
67
+ const legitimate = await store.consume(record.flowId, record.binding);
68
+ assert(legitimate !== undefined, 'duplicate suspend failure must preserve original flow');
69
+ });
70
+ await runCase(harness, cases, 'expired-flow-cannot-resume', async (store) => {
71
+ const record = flowRecord('flow-contract-expiry-0001', flowTtlMs);
72
+ await store.suspend(record);
73
+ await harness.waitForFlowExpiry(flowTtlMs, 'expired-flow-cannot-resume');
74
+ const expired = await store.consume(record.flowId, record.binding);
75
+ assert(expired === undefined, 'expired flow must not resume');
76
+ });
77
+ return { passed: cases.every(result => result.passed), cases };
78
+ }
79
+ export async function assertMcpUsageFlowStoreConformance(harness) {
80
+ const report = await runMcpUsageFlowStoreConformance(harness);
81
+ if (!report.passed)
82
+ throw new McpUsageFlowStoreConformanceError(report);
83
+ return report;
84
+ }
85
+ async function runCase(harness, results, name, body) {
86
+ try {
87
+ const store = await harness.createStore(name);
88
+ await body(store);
89
+ results.push({ name, passed: true });
90
+ }
91
+ catch (error) {
92
+ results.push({ name, passed: false, error: errorMessage(error) });
93
+ }
94
+ finally {
95
+ try {
96
+ await harness.cleanup?.(name);
97
+ }
98
+ catch (error) {
99
+ results.push({ name: `${name}:cleanup`, passed: false, error: errorMessage(error) });
100
+ }
101
+ }
102
+ }
103
+ function flowRecord(flowId, ttlMs) {
104
+ const now = Date.now();
105
+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0 || ttlMs > Number.MAX_SAFE_INTEGER - now) {
106
+ throw new RangeError('flow-store conformance ttlMs exceeds safe timestamp range');
107
+ }
108
+ const expiresAt = now + ttlMs;
109
+ return {
110
+ flowId,
111
+ binding: {
112
+ principalId: 'principal-1',
113
+ tenantId: 'tenant-1',
114
+ tool: 'contract-tool',
115
+ argsHash: 'a'.repeat(64),
116
+ },
117
+ lease: {
118
+ reservation: {
119
+ id: 'contract-reservation',
120
+ operationId: 'contract-operation',
121
+ principalId: 'principal-1',
122
+ tenantId: 'tenant-1',
123
+ tool: 'contract-tool',
124
+ budgetKeys: ['contract:budget'],
125
+ reservedUnits: 1,
126
+ expiresAt,
127
+ },
128
+ ttlMs,
129
+ unresolvedGrowth: {
130
+ incrementId: 'contract-growth-increment',
131
+ additionalUnits: 2,
132
+ budgets: [{ key: 'contract:budget', limit: 10 }],
133
+ },
134
+ },
135
+ round: 1,
136
+ expiresAt,
137
+ };
138
+ }
139
+ function assertRecordMatches(actual, expected) {
140
+ assert(actual.flowId === expected.flowId, 'flowId changed across storage');
141
+ assert(actual.round === expected.round, 'round changed across storage');
142
+ assert(actual.expiresAt === expected.expiresAt, 'expiresAt changed across storage');
143
+ assert(actual.binding.principalId === expected.binding.principalId, 'principal binding changed');
144
+ assert(actual.binding.tenantId === expected.binding.tenantId, 'tenant binding changed');
145
+ assert(actual.binding.tool === expected.binding.tool, 'tool binding changed');
146
+ assert(actual.binding.argsHash === expected.binding.argsHash, 'args binding changed');
147
+ assert(actual.lease.reservation.id === expected.lease.reservation.id, 'reservation identity changed across storage');
148
+ assert(JSON.stringify(actual.lease.unresolvedGrowth) === JSON.stringify(expected.lease.unresolvedGrowth), 'unresolved growth changed across storage');
149
+ if (expected.lease.unresolvedGrowth !== undefined) {
150
+ assert(actual.lease.unresolvedGrowth !== expected.lease.unresolvedGrowth, 'unresolved growth must be detached from caller state');
151
+ assert(actual.lease.unresolvedGrowth?.budgets !== expected.lease.unresolvedGrowth.budgets, 'unresolved growth budgets must be detached from caller state');
152
+ }
153
+ }
154
+ async function assertRejects(action, message) {
155
+ let rejected = false;
156
+ try {
157
+ await action();
158
+ }
159
+ catch {
160
+ rejected = true;
161
+ }
162
+ assert(rejected, message);
163
+ }
164
+ function assert(condition, message) {
165
+ if (!condition)
166
+ throw new Error(message);
167
+ }
168
+ function assertPositiveInteger(value, name) {
169
+ if (!Number.isSafeInteger(value) || value <= 0) {
170
+ throw new RangeError(`${name} must be a positive safe integer`);
171
+ }
172
+ }
173
+ function errorMessage(error) {
174
+ if (error instanceof Error)
175
+ return `${error.name}: ${error.message}`;
176
+ return String(error);
177
+ }
178
+ //# sourceMappingURL=flow-store-conformance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow-store-conformance.js","sourceRoot":"","sources":["../src/flow-store-conformance.ts"],"names":[],"mappings":"AAoCA,MAAM,OAAO,iCAAkC,SAAQ,KAAK;IAC9B;IAA5B,YAA4B,MAA0C;QACpE,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,MAA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