bitbank-lab-mcp 0.2.1 → 0.3.1
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/README.md +2 -2
- package/package.json +3 -2
- package/src/lib/bitbank-errors.ts +2 -0
- package/src/private/elicitation.ts +141 -60
- package/src/private/request-state.ts +98 -0
- package/src/schema/index.ts +1 -0
- package/src/schema/ui.ts +16 -0
- package/src/server.ts +79 -162
- package/src/tool-definition.ts +8 -5
- package/src/tool-registry.ts +4 -0
- package/src/ui-snapshot-cache.ts +80 -0
- package/tools/get_ui_snapshot.ts +46 -0
- package/tools/private/cancel_order.ts +5 -0
- package/tools/private/cancel_orders.ts +4 -0
- package/tools/private/create_order.ts +5 -0
- package/tools/private/preview_cancel_order.ts +16 -6
- package/tools/private/preview_cancel_orders.ts +7 -5
- package/tools/private/preview_order.ts +7 -5
- package/ui/cancel-confirm/dist/cancel-confirm.html +61 -36
- package/ui/order-confirm/dist/order-confirm.html +55 -30
package/README.md
CHANGED
|
@@ -326,8 +326,8 @@ API キーの有無でサーバーが公開する機能が自動的に切り替
|
|
|
326
326
|
|
|
327
327
|
| 設定 | ツール数 | プロンプト数 | 使える機能 |
|
|
328
328
|
|------|---------|------------|-----------|
|
|
329
|
-
| キー未設定 |
|
|
330
|
-
| キー設定済み |
|
|
329
|
+
| キー未設定 | 33(Public のみ) | 8 | 価格取得・テクニカル分析・チャート生成・バックテスト |
|
|
330
|
+
| キー設定済み | 33 + 16 = **49** | 8 + 1 = **9** | 上記 + 資産確認・注文・ポートフォリオ分析 |
|
|
331
331
|
|
|
332
332
|
キー未設定時、Private ツール・プロンプトは MCP クライアントに一切表示されません(エラーではなく、そもそも登録されません)。公開データの取得・分析だけなら設定不要で、そのまま使えます。
|
|
333
333
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bitbank-lab-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Experimental MCP server for bitbank — botters lab community edition. Market data, technical analysis, charting, and Private API trading tools.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -63,8 +63,9 @@
|
|
|
63
63
|
],
|
|
64
64
|
"author": "Bitbank, Inc.",
|
|
65
65
|
"dependencies": {
|
|
66
|
-
"@modelcontextprotocol/ext-apps": "^1.7.
|
|
66
|
+
"@modelcontextprotocol/ext-apps": "^1.7.5",
|
|
67
67
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
68
|
+
"@modelcontextprotocol/server": "2.0.0",
|
|
68
69
|
"dayjs": "^1.11.19",
|
|
69
70
|
"dotenv": "^17.4.2",
|
|
70
71
|
"lightweight-charts": "^5.1.0",
|
|
@@ -15,6 +15,8 @@ const BITBANK_ERROR_MESSAGES: Record<number, string> = {
|
|
|
15
15
|
50009: '指定された注文が見つかりません(3ヶ月以上前の注文は参照不可)',
|
|
16
16
|
50010: 'この注文はキャンセルできません',
|
|
17
17
|
50026: 'この注文は既にキャンセル済みです',
|
|
18
|
+
70019:
|
|
19
|
+
'注文はキャンセル処理中です(直前に別ルートでキャンセルが実行された可能性があります。get_order で最新状態を確認してください)',
|
|
18
20
|
50027: 'この注文は既に約定済みです',
|
|
19
21
|
// 信用取引固有エラー
|
|
20
22
|
50058: '信用取引の審査が完了していません。bitbank の管理画面から申込・審査を行ってください',
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* preview 系ツール(preview_order / preview_cancel_order / preview_cancel_orders)の
|
|
3
|
-
*
|
|
3
|
+
* ユーザー確認フローを共通化するヘルパー。
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* 1
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* MCP 2026-07-28 (SEP-2322 MRTR) スタイルで実装する:
|
|
6
|
+
* - round 1: クライアントが elicitation を扱えるなら `input_required` 結果
|
|
7
|
+
* (confirm 要求 + 署名付き requestState)を返す
|
|
8
|
+
* - round 2: クライアントが confirm 応答つきで元のツール呼び出しを再試行してきたら、
|
|
9
|
+
* requestState を検証(action / 引数 digest / one-time nonce)した上で
|
|
10
|
+
* accept なら execute を実行する
|
|
11
|
+
* - 2025 系クライアントには SDK の legacy shim(デフォルト有効)が round 1 の
|
|
12
|
+
* `input_required` を従来の `elicitation/create` push に自動変換し、応答を
|
|
13
|
+
* `inputResponses` に詰めてハンドラを再入させる。ハンドラは一度書けば両世代で動く
|
|
14
|
+
* - elicitation 非対応 / 検証失敗時は `fallback`(実行不可通知)を返す
|
|
9
15
|
*
|
|
10
16
|
* 取引系 HITL(Human-in-the-Loop)の中核であり、3 箇所に散らばっていると
|
|
11
17
|
* 仕様ドリフトで事故になるため、本モジュールに集約する。
|
|
@@ -17,34 +23,70 @@
|
|
|
17
23
|
* 呼び出し側が誤って `fallback` / `declinedStructured` に token を含めても、
|
|
18
24
|
* `withElicitedConfirmation` 内の `stripConfirmationTokenFields` で必ず除去される
|
|
19
25
|
* (多層防御。caller convention だけに依存しない最終ガード)。
|
|
26
|
+
* - `requestState` は署名のみで暗号化されない(クライアント / LLM から可視)ため、
|
|
27
|
+
* token を含めない。nonce + 引数 digest のみを載せ、再入時に検証する。
|
|
28
|
+
* 詳細は src/private/request-state.ts と ADR-0007 を参照。
|
|
20
29
|
* - 「`structuredContent` は LLM 非可視」をホストの仕様保証として扱わない。
|
|
21
30
|
* SEP-1624 / 各ホスト挙動の詳細は docs/private-api.md「content /
|
|
22
31
|
* structuredContent / `_meta` の役割と HITL の境界」節を参照。
|
|
23
32
|
*/
|
|
24
33
|
|
|
34
|
+
import { type InputRequiredResult, inputRequired, inputResponse } from '@modelcontextprotocol/server';
|
|
25
35
|
import { toStructured } from '../../lib/result.js';
|
|
26
36
|
import type { Result } from '../schema/types.js';
|
|
27
37
|
import type { McpResponse, ToolHandlerExtra } from '../tool-definition.js';
|
|
28
38
|
import { isHostApprovalTrusted } from './config.js';
|
|
39
|
+
import { type ConfirmRequestState, consumeNonce, digestArgs, mintConfirmState } from './request-state.js';
|
|
29
40
|
|
|
30
|
-
/**
|
|
31
|
-
|
|
32
|
-
elicitInput: (params: {
|
|
33
|
-
message: string;
|
|
34
|
-
requestedSchema: Record<string, unknown>;
|
|
35
|
-
}) => Promise<{ action: 'accept' | 'decline' | 'cancel'; content?: Record<string, unknown> }>;
|
|
36
|
-
}
|
|
41
|
+
/** inputResponses の confirm 応答を引くためのキー */
|
|
42
|
+
const CONFIRM_KEY = 'confirm';
|
|
37
43
|
|
|
38
44
|
/**
|
|
39
|
-
* クライアントが elicitation
|
|
40
|
-
*
|
|
41
|
-
*
|
|
45
|
+
* クライアントが elicitation を扱えるかを判定する。
|
|
46
|
+
*
|
|
47
|
+
* - 2025 系接続: initialize 時の client capabilities(server.getClientCapabilities())
|
|
48
|
+
* - 2026-07-28 系リクエスト: per-request の `_meta` envelope に載る clientCapabilities
|
|
49
|
+
*
|
|
50
|
+
* どちらにも `elicitation` が無いホストでは取引実行を行わず、呼び出し側が用意した
|
|
51
|
+
* `fallback`(実行不可通知レスポンス)を返す。
|
|
42
52
|
*/
|
|
43
53
|
export function clientSupportsElicitation(extra: ToolHandlerExtra | undefined): boolean {
|
|
44
54
|
const server = (extra as { server?: { getClientCapabilities?: () => unknown } } | undefined)?.server;
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
55
|
+
const initCaps = typeof server?.getClientCapabilities === 'function' ? server.getClientCapabilities() : undefined;
|
|
56
|
+
if ((initCaps as { elicitation?: unknown } | undefined)?.elicitation) return true;
|
|
57
|
+
|
|
58
|
+
const envelope = (extra as { mcpReq?: { envelope?: { clientCapabilities?: unknown } } } | undefined)?.mcpReq
|
|
59
|
+
?.envelope;
|
|
60
|
+
const envCaps = envelope?.clientCapabilities;
|
|
61
|
+
return Boolean((envCaps as { elicitation?: unknown } | undefined)?.elicitation);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 再入リクエストの inputResponses を ctx から取り出す。 */
|
|
65
|
+
function readInputResponses(extra: ToolHandlerExtra | undefined): Record<string, unknown> | undefined {
|
|
66
|
+
const responses = (extra as { mcpReq?: { inputResponses?: Record<string, unknown> } } | undefined)?.mcpReq
|
|
67
|
+
?.inputResponses;
|
|
68
|
+
return responses && typeof responses === 'object' ? responses : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* verify フック(server.ts の ServerOptions.requestState.verify)が復号した
|
|
73
|
+
* requestState payload を ctx から読み取る。形状が想定と異なる場合は undefined。
|
|
74
|
+
*/
|
|
75
|
+
function readConfirmState(extra: ToolHandlerExtra | undefined): ConfirmRequestState | undefined {
|
|
76
|
+
const accessor = (extra as { mcpReq?: { requestState?: unknown } } | undefined)?.mcpReq?.requestState;
|
|
77
|
+
if (typeof accessor !== 'function') return undefined;
|
|
78
|
+
let value: unknown;
|
|
79
|
+
try {
|
|
80
|
+
value = (accessor as () => unknown)();
|
|
81
|
+
} catch {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
if (!value || typeof value !== 'object') return undefined;
|
|
85
|
+
const state = value as Partial<ConfirmRequestState>;
|
|
86
|
+
if (typeof state.action !== 'string' || typeof state.argsDigest !== 'string' || typeof state.nonce !== 'string') {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
return state as ConfirmRequestState;
|
|
48
90
|
}
|
|
49
91
|
|
|
50
92
|
/**
|
|
@@ -74,6 +116,16 @@ function stripConfirmationTokenFields(value: Record<string, unknown>): Record<st
|
|
|
74
116
|
export interface WithElicitedConfirmationOptions {
|
|
75
117
|
/** ハンドラに渡される MCP リクエストコンテキスト */
|
|
76
118
|
extra: ToolHandlerExtra | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* 確認対象の操作種別('create_order' | 'cancel_order' | 'cancel_orders')。
|
|
121
|
+
* requestState のドメイン分離に使い、別操作への accept 流用を拒否する。
|
|
122
|
+
*/
|
|
123
|
+
action: string;
|
|
124
|
+
/**
|
|
125
|
+
* 元リクエストの引数。requestState の引数 digest にバインドし、round 2 で
|
|
126
|
+
* 引数を差し替えた再試行(ユーザーが見ていないプレビュー内容の実行)を拒否する。
|
|
127
|
+
*/
|
|
128
|
+
bindArgs: Record<string, unknown>;
|
|
77
129
|
/** elicitation の message に渡す preview 結果サマリ */
|
|
78
130
|
summary: string;
|
|
79
131
|
/** elicitation スキーマの confirmed フィールドに付ける title(例: 'この注文を発注する') */
|
|
@@ -95,9 +147,8 @@ export interface WithElicitedConfirmationOptions {
|
|
|
95
147
|
declinedStructured: Record<string, unknown>;
|
|
96
148
|
/**
|
|
97
149
|
* elicitation 非対応ホスト向けの「実行不可通知」レスポンス。以下のケースで返る:
|
|
98
|
-
* - クライアントが elicitation
|
|
99
|
-
* -
|
|
100
|
-
* - elicitInput が例外を投げた
|
|
150
|
+
* - クライアントが elicitation 非対応(2025 系 capabilities / 2026 系 envelope とも無し)
|
|
151
|
+
* - requestState の mint に失敗した
|
|
101
152
|
*
|
|
102
153
|
* セマンティクス: 取引実行は行わずプレビュー内容のみ返し、対応ホストで実行するよう
|
|
103
154
|
* ユーザー / LLM に促す。`structuredContent` 内の `confirmation_token` / `expires_at`
|
|
@@ -125,12 +176,13 @@ export interface WithElicitedConfirmationOptions {
|
|
|
125
176
|
}
|
|
126
177
|
|
|
127
178
|
/**
|
|
128
|
-
* preview 結果に対するユーザー確認(elicitation)フローを実行する高レベルラッパー。
|
|
179
|
+
* preview 結果に対するユーザー確認(MRTR / elicitation)フローを実行する高レベルラッパー。
|
|
129
180
|
*
|
|
130
181
|
* 責務:
|
|
131
|
-
* 1.
|
|
132
|
-
* 2.
|
|
133
|
-
* 3.
|
|
182
|
+
* 1. round 判定(inputResponses の confirm 応答の有無)
|
|
183
|
+
* 2. round 1: capability 判定 → `input_required` 結果の生成(requestState mint 込み)
|
|
184
|
+
* 3. round 2: requestState 検証(action / 引数 digest / one-time nonce)と
|
|
185
|
+
* ユーザー応答(accept / decline / cancel / confirmed=false)による分岐返却
|
|
134
186
|
*
|
|
135
187
|
* 実 API 呼び出し(create_order / cancel_order / cancel_orders)は呼び出し側が
|
|
136
188
|
* `onConfirmed` 内で行う。bitbank のキャンセル系は単数/複数で execute シグネチャが
|
|
@@ -138,11 +190,12 @@ export interface WithElicitedConfirmationOptions {
|
|
|
138
190
|
*
|
|
139
191
|
* 挙動の統一:
|
|
140
192
|
* - decline / cancel / accept-without-confirmed はすべて「ユーザー拒否」として
|
|
141
|
-
*
|
|
142
|
-
* - `onConfirmed`
|
|
143
|
-
* (elicitInput 自体の例外のみフォールバックさせる)。
|
|
193
|
+
* 同一処理にする。
|
|
194
|
+
* - `onConfirmed` の例外は捕捉せず呼び出し側に伝播させる。
|
|
144
195
|
*/
|
|
145
|
-
export async function withElicitedConfirmation(
|
|
196
|
+
export async function withElicitedConfirmation(
|
|
197
|
+
opts: WithElicitedConfirmationOptions,
|
|
198
|
+
): Promise<McpResponse | InputRequiredResult> {
|
|
146
199
|
// fallback / declinedStructured は caller convention だけに依頼せず、ここで必ず
|
|
147
200
|
// confirmation_token / expires_at を剥がす(多層防御の最終ガード)。
|
|
148
201
|
const safeFallback: McpResponse = {
|
|
@@ -157,46 +210,74 @@ export async function withElicitedConfirmation(opts: WithElicitedConfirmationOpt
|
|
|
157
210
|
// 詳細は docs/adr/0007-hitl-confirmation-token-delivery.md を参照。
|
|
158
211
|
const trustHostFallback = isHostApprovalTrusted() ? opts.trustHostFallback : undefined;
|
|
159
212
|
|
|
160
|
-
|
|
161
|
-
|
|
213
|
+
// ── round 2: confirm 応答つき再入 ──
|
|
214
|
+
const view = inputResponse(readInputResponses(opts.extra), CONFIRM_KEY);
|
|
215
|
+
if (view.kind === 'elicit') {
|
|
216
|
+
// requestState(verify フックで HMAC / 期限検証済み)の文脈バインドを検証する。
|
|
217
|
+
// 検証はユーザー応答の内容より先に行い、nonce は accept / decline を問わず消費する
|
|
218
|
+
// (拒否された確認の requestState を後から accept 付きで replay させない)。
|
|
219
|
+
const state = readConfirmState(opts.extra);
|
|
220
|
+
const bound =
|
|
221
|
+
state !== undefined &&
|
|
222
|
+
state.action === opts.action &&
|
|
223
|
+
state.argsDigest === digestArgs(opts.action, opts.bindArgs) &&
|
|
224
|
+
consumeNonce(state.nonce);
|
|
225
|
+
if (!bound) {
|
|
226
|
+
return {
|
|
227
|
+
content: [
|
|
228
|
+
{
|
|
229
|
+
type: 'text',
|
|
230
|
+
text: '確認情報が無効なため実行しませんでした(引数の変更・再利用・期限切れの可能性)。preview からやり直してください。',
|
|
231
|
+
},
|
|
232
|
+
],
|
|
233
|
+
structuredContent: safeDeclinedStructured,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (view.action !== 'accept' || view.content?.confirmed !== true) {
|
|
238
|
+
return {
|
|
239
|
+
content: [{ type: 'text', text: opts.onDeclinedText }],
|
|
240
|
+
structuredContent: safeDeclinedStructured,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const execResult = await opts.onConfirmed();
|
|
245
|
+
const text = execResult.ok ? execResult.summary : `Error: ${execResult.summary}`;
|
|
246
|
+
// onConfirmed の Result(create_order 等の戻り値)には confirmation_token は含まれない
|
|
247
|
+
// 想定だが、念のため同じ最終ガードを通す。
|
|
248
|
+
return {
|
|
249
|
+
content: [{ type: 'text', text }],
|
|
250
|
+
structuredContent: stripConfirmationTokenFields(toStructured(execResult)),
|
|
251
|
+
};
|
|
162
252
|
}
|
|
163
253
|
|
|
164
|
-
|
|
165
|
-
if (!
|
|
254
|
+
// ── round 1: 確認要求の発行 ──
|
|
255
|
+
if (!clientSupportsElicitation(opts.extra)) {
|
|
166
256
|
return trustHostFallback ?? safeFallback;
|
|
167
257
|
}
|
|
168
258
|
|
|
169
|
-
let
|
|
259
|
+
let requestState: string;
|
|
170
260
|
try {
|
|
171
|
-
|
|
172
|
-
message: opts.summary,
|
|
173
|
-
requestedSchema: {
|
|
174
|
-
type: 'object',
|
|
175
|
-
properties: {
|
|
176
|
-
confirmed: { type: 'boolean', title: opts.confirmTitle },
|
|
177
|
-
},
|
|
178
|
-
required: ['confirmed'],
|
|
179
|
-
},
|
|
180
|
-
});
|
|
261
|
+
requestState = await mintConfirmState(opts.action, opts.bindArgs);
|
|
181
262
|
} catch {
|
|
182
|
-
//
|
|
263
|
+
// mint が想定外に失敗した場合はフォールバックに進む。
|
|
183
264
|
// trust-host モード ON なら iframe ボタン経路を残す trustHostFallback を返す。
|
|
184
265
|
return trustHostFallback ?? safeFallback;
|
|
185
266
|
}
|
|
186
267
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
};
|
|
268
|
+
return inputRequired({
|
|
269
|
+
inputRequests: {
|
|
270
|
+
[CONFIRM_KEY]: inputRequired.elicit({
|
|
271
|
+
message: opts.summary,
|
|
272
|
+
requestedSchema: {
|
|
273
|
+
type: 'object',
|
|
274
|
+
properties: {
|
|
275
|
+
confirmed: { type: 'boolean', title: opts.confirmTitle },
|
|
276
|
+
},
|
|
277
|
+
required: ['confirmed'],
|
|
278
|
+
},
|
|
279
|
+
}),
|
|
280
|
+
},
|
|
281
|
+
requestState,
|
|
282
|
+
});
|
|
202
283
|
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MRTR (Multi Round-Trip Requests, SEP-2322) の `requestState` 管理。
|
|
3
|
+
*
|
|
4
|
+
* preview 系ツールの確認フロー(withElicitedConfirmation)が round 1 で mint し、
|
|
5
|
+
* confirm 応答つきの再入(round 2)で検証する。SDK の `createRequestStateCodec` は
|
|
6
|
+
* HMAC-SHA256 署名のみで**暗号化はしない**(payload はクライアントから可視)ため、
|
|
7
|
+
* `confirmation_token` 等の秘匿情報は一切格納しない。格納するのは:
|
|
8
|
+
*
|
|
9
|
+
* - `action` — 確認対象の操作種別(create_order 等)。別操作への流用を拒否する
|
|
10
|
+
* - `argsDigest` — 元リクエスト引数の digest。引数を差し替えた再試行での
|
|
11
|
+
* accept 再利用(プレビューを見ていない内容の実行)を拒否する
|
|
12
|
+
* - `nonce` — one-time-use。使用済み requestState の replay を拒否する
|
|
13
|
+
*
|
|
14
|
+
* 鍵は per-process ランダム。stdio サーバーは単一プロセスが全ラウンドを処理する
|
|
15
|
+
* 前提のためこれで足りる(SDK ドキュメントの明記どおり)。プロセス再起動で
|
|
16
|
+
* pending の確認は無効化される(安全側に倒れる)。
|
|
17
|
+
*
|
|
18
|
+
* 検証は 2 層:
|
|
19
|
+
* 1. HMAC / 有効期限 — SDK の verify フック(server.ts で ServerOptions に接続)が
|
|
20
|
+
* ハンドラ実行前に実施。失敗は wire レベルの -32602 になる
|
|
21
|
+
* 2. action / argsDigest / nonce — withElicitedConfirmation が実行直前に実施
|
|
22
|
+
*
|
|
23
|
+
* 設計の背景は docs/adr/0007-hitl-confirmation-token-delivery.md を参照。
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
27
|
+
import { createRequestStateCodec } from '@modelcontextprotocol/server';
|
|
28
|
+
|
|
29
|
+
/** requestState の payload。秘匿情報は含めない(署名のみで暗号化されないため)。 */
|
|
30
|
+
export interface ConfirmRequestState {
|
|
31
|
+
action: string;
|
|
32
|
+
argsDigest: string;
|
|
33
|
+
nonce: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 確認待ちの有効期限(秒)。人間の確認操作を待つ時間として confirmation token より長め。 */
|
|
37
|
+
const REQUEST_STATE_TTL_SECONDS = 300;
|
|
38
|
+
|
|
39
|
+
/** nonce の使用済み記録の保持期間(ms)。requestState TTL と揃える。 */
|
|
40
|
+
const NONCE_RETENTION_MS = REQUEST_STATE_TTL_SECONDS * 1000;
|
|
41
|
+
|
|
42
|
+
export const requestStateCodec = createRequestStateCodec<ConfirmRequestState>({
|
|
43
|
+
key: randomBytes(32),
|
|
44
|
+
ttlSeconds: REQUEST_STATE_TTL_SECONDS,
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 引数オブジェクトを正規化(キー再帰ソート + undefined 除去)して SHA-256 digest にする。
|
|
49
|
+
* action を含めてドメイン分離する。
|
|
50
|
+
*/
|
|
51
|
+
export function digestArgs(action: string, args: Record<string, unknown>): string {
|
|
52
|
+
const canonical = JSON.stringify(sortValue({ action, args }));
|
|
53
|
+
return createHash('sha256').update(canonical).digest('hex');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function sortValue(value: unknown): unknown {
|
|
57
|
+
if (Array.isArray(value)) return value.map(sortValue);
|
|
58
|
+
if (value && typeof value === 'object') {
|
|
59
|
+
const obj = value as Record<string, unknown>;
|
|
60
|
+
return Object.keys(obj)
|
|
61
|
+
.sort()
|
|
62
|
+
.reduce<Record<string, unknown>>((acc, key) => {
|
|
63
|
+
if (obj[key] !== undefined) acc[key] = sortValue(obj[key]);
|
|
64
|
+
return acc;
|
|
65
|
+
}, {});
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** round 1 用: 確認フローの requestState を mint する。 */
|
|
71
|
+
export function mintConfirmState(action: string, args: Record<string, unknown>): Promise<string> {
|
|
72
|
+
return requestStateCodec.mint({
|
|
73
|
+
action,
|
|
74
|
+
argsDigest: digestArgs(action, args),
|
|
75
|
+
nonce: randomBytes(16).toString('hex'),
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 使用済み nonce(one-time-use 強制)。値は記録時刻 + 保持期間。 */
|
|
80
|
+
const usedNonces = new Map<string, number>();
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* nonce を消費する。未使用なら true を返して使用済みに登録し、
|
|
84
|
+
* 使用済み(replay)なら false を返す。
|
|
85
|
+
*/
|
|
86
|
+
export function consumeNonce(nonce: string, nowMs: number = Date.now()): boolean {
|
|
87
|
+
for (const [key, expiresAt] of usedNonces) {
|
|
88
|
+
if (nowMs > expiresAt) usedNonces.delete(key);
|
|
89
|
+
}
|
|
90
|
+
if (usedNonces.has(nonce)) return false;
|
|
91
|
+
usedNonces.set(nonce, nowMs + NONCE_RETENTION_MS);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 使用済み nonce をクリアする(テスト用)。 */
|
|
96
|
+
export function _resetUsedNonces(): void {
|
|
97
|
+
usedNonces.clear();
|
|
98
|
+
}
|
package/src/schema/index.ts
CHANGED
package/src/schema/ui.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
// === MCP Apps UI snapshot ===
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* スナップショット取得対象の MCP Apps リソース URI。
|
|
7
|
+
* `src/resources/app-resources.ts` の appResourceRegistry と一致させること
|
|
8
|
+
* (ドリフトは tests/get_ui_snapshot.test.ts で検出する)。
|
|
9
|
+
*/
|
|
10
|
+
export const UI_SNAPSHOT_RESOURCE_URIS = ['ui://order/confirm.html', 'ui://cancel/confirm.html'] as const;
|
|
11
|
+
|
|
12
|
+
export const GetUiSnapshotInputSchema = z.object({
|
|
13
|
+
resource_uri: z
|
|
14
|
+
.enum(UI_SNAPSHOT_RESOURCE_URIS)
|
|
15
|
+
.describe('スナップショットを取得する MCP Apps リソース URI(ウィジェット自身の URI を指定する)'),
|
|
16
|
+
});
|