rebut-mcp 0.3.3 → 0.4.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.
@@ -40,6 +40,18 @@ rebut set profile PROFILE_ID
40
40
 
41
41
  Preferences affect new collection. Explicit `collect --profile` wins; `review` retains the frozen bundle's profile. The default is `astra-medium`. Allowlisting does not grant provider model access.
42
42
 
43
+ Use a client-specific preference to share one Rebut configuration and ledger while selecting different default profiles for Codex and Claude Code.
44
+
45
+ ```sh
46
+ rebut set profile claude-medium --client codex
47
+ rebut set profile astra-medium --client claude
48
+ rebut set profile --client codex --clear
49
+ ```
50
+
51
+ The clear command restores the shared preference for that client. In a terminal or an agent command, pass `collect --client codex` or `collect --client claude` to select the corresponding default. An explicit `collect --profile` wins. An unavailable client default stops default collection. Existing frozen bundles keep their profile and provider. Run `rebut doctor --client codex` or `--client claude` to see the preference.
52
+
53
+ Refresh existing registrations with `rebut setup --client codex --replace` or `rebut setup --client claude --replace` and restart the host. In local environment-variable mode, refresh the registration again when a default change switches the required key variable. `rebut profile set --model` defines a profile's model. Choosing that profile as a default uses its current model, reasoning, and rates. Before rolling back to a version without client defaults, clear both client overrides and use the older CLI to register both MCP hosts again.
54
+
43
55
  The shipped `astra-medium` profile uses GPT-6.2 Astra (`gpt-6.2-astra`) with medium reasoning. The example uses [short-context Standard rates](https://developers.openai.com/api/docs/models/gpt-6.2-astra) of $8 input and $40 output per million tokens. Existing Workers and local profile overrides retain their stored settings. To migrate them, inspect `rebut profile list` and update the model to `gpt-6.2-astra`, reasoning to `medium`, and both rates together in one profile update with the current `--if-revision`, and price version `openai-standard-2026-11-18`. If a client explicitly selects the old model ID, update that preference or select `astra-medium` by profile ID.
44
56
 
45
57
  The OS owner manages local profiles. Worker changes require migration `0002`, `ADMIN_TOKEN_SHA256`, and a separate administrator token. Listing profiles makes no paid model call.
@@ -73,6 +73,14 @@ Select files explicitly. The collector rejects unsafe files, symlinks, FIFOs, an
73
73
 
74
74
  Select paid reviews explicitly. Check for `completed` and compare the returned model and input hash with the frozen bundle/profile, then verify each finding against the source. For independent reviews, supply the same frozen material without sharing reviewers' results. After timeout/unknown, retain the ID and backend rather than submitting a new ID. Follow [recovery](operations.md#unknown-recovery).
75
75
 
76
+ ### Review independently with two profiles
77
+
78
+ Use `review_pair` in Codex or Claude Code when the user explicitly selects two paid reviews. Pass the complete collected schema 2 bundle as `first`, and pass a distinct `request_id` and the second `profile` and its `provider` as `second`. For example, collect `first` with `astra-medium` / `openai` and pass `{"request_id":"review-002","profile":"claude-medium","provider":"anthropic"}` as `second`. Confirm the profiles with `rebut profile list`.
79
+
80
+ Both requests use the same evidence, with each input hash pinned to its provider. Budget and concurrency limits apply to each request, so only one may be admitted. Local concurrency defaults to one. Run `rebut set max-concurrent 2` and restart the MCP host to enable parallel local review. Rebut rejects the pair before dispatch if the local limit is below two. Each result includes its request ID and `has_review`. The pair is `partial` when it includes one review body and `incomplete` when it includes none. When both requests completed earlier and neither body can be replayed, the status is `completed_without_review`. If the response is lost, use `review_status` with both original IDs on the same backend before considering any further paid call. Status lookups do not replay review bodies.
81
+
82
+ The tool is available in the Rebut client in local and Worker modes. For an existing Codex registration, run `rebut setup --client codex --replace` and restart the host. Restart Claude Code to refresh the tool list. When local reviewers use different providers, the Rebut process needs both keys. Environment-based host registration forwards only the preferred provider variable by default.
83
+
76
84
  ## Optional Worker deployment
77
85
 
78
86
  Use a Worker to share budgets and request history across devices. Deployment requires a source checkout, your Cloudflare account, and D1.
@@ -40,6 +40,18 @@ rebut set profile PROFILE_ID
40
40
 
41
41
  設定は新規収集に適用します。明示した `collect --profile` が優先され、`review` は固定バンドルのプロファイルを維持します。既定は `astra-medium` です。許可リストはプロバイダーのモデル権限を与えません。
42
42
 
43
+ 1 つの設定と台帳を共有しながら、Codex と Claude Code に別々の既定レビュープロファイルを設定できます。
44
+
45
+ ```sh
46
+ rebut set profile claude-medium --client codex
47
+ rebut set profile astra-medium --client claude
48
+ rebut set profile --client codex --clear
49
+ ```
50
+
51
+ `--clear` はそのクライアントを共有の既定値に戻します。シェルやエージェントから `collect --client codex` または `collect --client claude` を指定するとクライアント別の既定値が適用されます。明示した `collect --profile` が優先されます。既定のプロファイルが使用できない場合は既定値での収集が失敗し、既存のバンドルのプロファイルとプロバイダーは保持されます。`rebut doctor --client codex` または `--client claude` で設定を確認できます。
52
+
53
+ 既存の登録を `rebut setup --client codex --replace` または `rebut setup --client claude --replace` で更新し、ホストを再起動してください。ローカルの環境変数方式で必要なキー変数が変わった場合は再登録します。モデルは `rebut profile set --model` でプロファイルに定義します。既定値に選んだプロファイルのモデル・推論・料金が適用されます。 クライアント別の既定値をサポートしない版へ戻す場合は、両方の設定を先に解除し、旧版の CLI で両方の MCP ホストを再登録してください。
54
+
43
55
  同梱の `astra-medium` プロファイルは GPT-6.2 Astra(`gpt-6.2-astra`)と medium の推論を使用します。例の[短いコンテキストの Standard 料金](https://developers.openai.com/api/docs/models/gpt-6.2-astra)は100万トークン当たり入力 $8、出力 $40 です。既存の Worker とローカルのプロファイル上書きは保存済み設定を維持します。移行するには `rebut profile list` を確認し、モデル `gpt-6.2-astra`、推論 `medium`、両方の料金と料金バージョン `openai-standard-2026-11-18` を、現在の `--if-revision` で一度に更新してください。旧モデル ID を明示しているクライアントでは、その設定を更新するか、プロファイル ID で `astra-medium` を選択してください。
44
56
 
45
57
  ローカルは OS 所有者が管理します。Worker の変更には `0002`、`ADMIN_TOKEN_SHA256`、別の管理者トークンが必要です。一覧取得は有料モデルを呼びません。
@@ -73,6 +73,16 @@ rebut status review-001
73
73
 
74
74
  有料レビューを明示選択します。`completed` を確認し、返されたモデル・入力ハッシュを固定バンドルとプロファイルに照合して、各指摘を原資料で確認します。独立レビューには同じ固定資料を渡し、各レビュアーの結果を混ぜません。timeout/unknown 後は同じ ID・バックエンドを保ち、新しい ID で再実行せず[復旧](operations.md#unknown-復旧)に従ってください。
75
75
 
76
+ ### 2 つのプロファイルで独立レビューする
77
+
78
+ ユーザーが 2 件の有料レビューを明示的に選んだ場合は、Codex または Claude Code で `review_pair` を使います。`first` には収集したスキーマ 2 のバンドル全体を、`second` には別の `request_id` と 2 つ目の `profile`、その `provider` を渡します。たとえば `first` を `astra-medium` / `openai` で収集し、`second` に `{"request_id":"review-002","profile":"claude-medium","provider":"anthropic"}` を渡せます。プロファイルは `rebut profile list` で確認してください。
79
+
80
+ 2 件は同じ資料を使い、入力ハッシュはそれぞれのプロバイダーに固定されます。予算と同時実行上限はリクエストごとに適用され、片方だけ受け付けられる場合があります。ローカルの既定の同時実行上限は 1 です。ローカルで並列レビューを使うには `rebut set max-concurrent 2` を実行して MCP ホストを再起動します。ローカルの上限が 2 未満なら送信前に拒否されます。各結果にリクエスト ID と `has_review` が含まれ、本文が 1 件なら `partial`、0 件なら `incomplete` です。両方がすでに完了し、本文を再取得できない場合は `completed_without_review` です。応答が失われたら、同じバックエンドで元の 2 つの ID を使って `review_status` を呼び出してから、追加の有料呼び出しを検討します。状態照会で本文は再取得できません。
81
+
82
+ このツールは Rebut クライアントのローカルモードと Worker モードで使えます。既存の Codex 登録は `rebut setup --client codex --replace` で更新してホストを再起動してください。Claude Code は再起動してツール一覧を更新します。
83
+
84
+ ローカルで異なるプロバイダーを使う場合、Rebut プロセスには両方のキーが必要です。環境変数を使ったホスト登録は、既定では優先プロバイダーの変数だけを渡します。
85
+
76
86
  ## 任意の Worker デプロイ
77
87
 
78
88
  複数端末で予算・リクエスト台帳を共有する場合に使います。ソース、自分の Cloudflare アカウント、D1 が必要です。
@@ -40,6 +40,18 @@ rebut set profile PROFILE_ID
40
40
 
41
41
  환경설정은 새 수집에 적용합니다. 명시적 `collect --profile`이 우선하며 `review`는 번들에 고정한 프로필을 유지합니다. 기본은 `astra-medium`입니다. 프로필 허용 목록은 공급자의 모델 사용 권한을 보장하지 않습니다.
42
42
 
43
+ 설정과 장부를 공유하면서 Codex와 Claude Code의 기본 리뷰 프로필을 각각 지정할 수 있습니다.
44
+
45
+ ```sh
46
+ rebut set profile claude-medium --client codex
47
+ rebut set profile astra-medium --client claude
48
+ rebut set profile --client codex --clear
49
+ ```
50
+
51
+ `--clear`는 해당 호스트를 공통 기본값으로 되돌립니다. 터미널이나 에이전트 명령에서 `collect --client codex` 또는 `collect --client claude`를 사용하면 해당 기본값을 적용하며, `collect --profile`로 명시한 값이 우선합니다. 호스트 기본값을 사용할 수 없으면 기본값으로 번들을 수집할 수 없고, 기존 번들의 프로필과 공급자는 유지됩니다. `rebut doctor --client codex` 또는 `--client claude`로 설정을 확인합니다.
52
+
53
+ 기존 등록은 `rebut setup --client codex --replace` 또는 `rebut setup --client claude --replace`로 갱신한 뒤 호스트를 다시 시작합니다. 로컬 환경변수 방식에서 필요한 키 변수가 바뀌면 다시 등록합니다. 프로필에서 사용할 모델은 `rebut profile set --model`로 정의합니다. 기본값으로 선택한 프로필의 모델·추론·요율이 사용됩니다. 호스트별 기본값을 지원하지 않는 버전으로 되돌릴 때는 두 호스트의 기본값을 먼저 지우고, 이전 CLI로 두 MCP 호스트를 다시 등록합니다.
54
+
43
55
  기본 제공 `astra-medium` 프로필은 GPT-6.2 Astra(`gpt-6.2-astra`)와 medium 추론을 사용합니다. 예제의 [짧은 컨텍스트 Standard 요율](https://developers.openai.com/api/docs/models/gpt-6.2-astra)은 100만 토큰당 입력 $8, 출력 $40입니다. 기존 Worker와 로컬 프로필 오버라이드는 저장된 설정을 유지합니다. 전환하려면 `rebut profile list`를 확인하고 모델 `gpt-6.2-astra`, 추론 `medium`, 두 요율과 가격 버전 `openai-standard-2026-11-18`을 현재 `--if-revision`으로 한 번에 갱신합니다. 클라이언트가 이전 모델 ID를 명시했다면 해당 설정을 갱신하거나 프로필 ID로 `astra-medium`을 선택합니다.
44
56
 
45
57
  로컬 프로필은 OS 소유자가 관리합니다. Worker 변경에는 `0002` 마이그레이션과 `ADMIN_TOKEN_SHA256`, 별도 관리자 토큰이 필요합니다. 조회는 유료 모델을 호출하지 않습니다.
@@ -73,6 +73,14 @@ rebut status review-001
73
73
 
74
74
  유료 검토는 명시적으로 선택합니다. 응답이 `completed`인지 확인하고 모델·입력 해시를 고정 번들·프로필과 대조한 뒤 각 지적을 원본에서 확인하세요. 독립 리뷰에는 같은 고정 자료를 제공하고 서로의 결과를 섞지 마세요. timeout/unknown 뒤에는 같은 ID·백엔드를 유지하며 새 ID로 다시 호출하지 않습니다. [복구 절차](operations.md#unknown-복구)를 따르세요.
75
75
 
76
+ ### 두 프로필로 독립 리뷰하기
77
+
78
+ Codex 또는 Claude Code에서 두 프로필로 유료 리뷰를 실행하겠다고 명시한 경우 `review_pair`를 사용합니다. `first`에는 수집한 스키마 2 번들 전체를 넣고, `second`에는 별도의 `request_id`와 두 번째 `profile`, 해당 프로필의 `provider`를 넣습니다. 예를 들어 `first`를 `astra-medium` / `openai`로 수집했다면 `second`에 `{"request_id":"review-002","profile":"claude-medium","provider":"anthropic"}`을 전달할 수 있습니다. 두 프로필의 실제 설정은 `rebut profile list`에서 확인합니다.
79
+
80
+ 두 요청은 같은 검토 자료를 사용하고 각 공급자에 맞춰 입력 해시를 고정합니다. 각 요청에 예산과 동시 실행 한도가 적용되므로 한쪽만 접수될 수 있습니다. 로컬에서 병렬 리뷰를 쓰려면 `rebut set max-concurrent 2`를 실행하고 MCP 호스트를 다시 시작합니다. 기본 한도는 1이며, 로컬 한도가 2보다 작으면 두 요청을 전송하기 전에 거부합니다. 두 결과에는 각 요청 ID와 `has_review`가 표시됩니다. 본문이 하나면 `partial`, 둘 다 없으면 `incomplete`입니다. 두 요청이 모두 이미 완료됐고 본문을 다시 받을 수 없으면 `completed_without_review`입니다. 응답이 끊기면 같은 백엔드에서 원래 두 ID로 `review_status`를 조회한 뒤에 추가 유료 호출 여부를 판단합니다. 상태 조회로 결과 본문을 다시 받을 수 없습니다.
81
+
82
+ 이 도구는 로컬과 Worker 모드의 Rebut 클라이언트에서 제공됩니다. 기존 Codex 등록은 `rebut setup --client codex --replace`로 갱신하고 호스트를 다시 시작하세요. Claude Code는 호스트를 다시 시작해 도구 목록을 갱신하세요. 로컬에서 서로 다른 공급자를 쓰려면 Rebut 프로세스가 두 키에 모두 접근할 수 있어야 합니다. 환경변수 방식의 호스트 등록은 기본적으로 선호 공급자의 변수만 전달합니다.
83
+
76
84
  ## 선택적 Worker 배포
77
85
 
78
86
  여러 기기가 예산·요청 장부를 공유할 때 사용합니다. 소스 체크아웃과 자신의 Cloudflare 계정·D1이 필요합니다.
@@ -40,6 +40,18 @@ rebut set profile PROFILE_ID
40
40
 
41
41
  偏好应用于新收集的材料。显式 `collect --profile` 优先,`review` 保留冻结材料的配置档。默认 `astra-medium`,允许列表不授予供应商模型权限。
42
42
 
43
+ Codex 和 Claude Code 可以共享同一配置与账本,同时各自设置默认审查配置。
44
+
45
+ ```sh
46
+ rebut set profile claude-medium --client codex
47
+ rebut set profile astra-medium --client claude
48
+ rebut set profile --client codex --clear
49
+ ```
50
+
51
+ `--clear` 将该客户端恢复为共享默认配置。在终端或代理命令中用 `collect --client codex` 或 `collect --client claude` 选择对应默认值,显式传入的 `collect --profile` 优先。客户端默认配置不可用时,按默认值收集会失败。已有冻结审查包保留原来的配置和供应商。可用 `rebut doctor --client codex` 或 `--client claude` 查看设置。
52
+
53
+ 更新现有注册时,运行 `rebut setup --client codex --replace` 或 `rebut setup --client claude --replace`,然后重启宿主。本地环境变量模式下,如果所需密钥变量变化,请重新注册。通过 `rebut profile set --model` 定义配置中的模型。选为默认值后,将使用该配置的模型、推理设置和费率。 回退到不支持客户端默认值的版本前,先清除两个客户端的覆盖值,再用旧版 CLI 重新注册两个 MCP 宿主。
54
+
43
55
  随附的 `astra-medium` 配置档使用 GPT-6.2 Astra(`gpt-6.2-astra`)和 medium 推理。示例采用[短上下文 Standard 费率](https://developers.openai.com/api/docs/models/gpt-6.2-astra),每百万令牌输入 $8、输出 $40。现有 Worker 和本地配置档覆盖项保留已保存的设置。迁移时请查看 `rebut profile list`,使用当前的 `--if-revision` 一次性更新模型 `gpt-6.2-astra`、推理级别 `medium`、两项费率和价格版本 `openai-standard-2026-11-18`。如果客户端显式选择了旧模型 ID,请更新该偏好,或通过配置档 ID 选择 `astra-medium`。
44
56
 
45
57
  本地配置档由 OS 所有者管理。Worker 更改需要 `0002` 迁移、`ADMIN_TOKEN_SHA256` 和独立管理员令牌。列表查询不调用付费模型。
@@ -73,6 +73,16 @@ rebut status review-001
73
73
 
74
74
  明确选择付费审查。确认 `completed`,将返回的模型和输入哈希与冻结材料及配置档对照,再逐条核对原始证据。独立审查应使用同一份冻结材料,不共享各审查者结果。timeout/unknown 后保留原 ID 与后端,不以新 ID 重试,按[恢复流程](operations.md#unknown-恢复)处理。
75
75
 
76
+ ### 用两个配置进行独立审查
77
+
78
+ 用户明确选择两次付费审查时,可在 Codex 或 Claude Code 中使用 `review_pair`。`first` 传入收集好的完整 schema 2 审查包,`second` 传入不同的 `request_id`、第二个 `profile` 和对应的 `provider`。例如,使用 `astra-medium` / `openai` 收集 `first`,再将 `{"request_id":"review-002","profile":"claude-medium","provider":"anthropic"}` 传给 `second`。请用 `rebut profile list` 确认配置。
79
+
80
+ 两个请求使用相同材料,各自的输入哈希绑定对应供应商。每个请求分别受预算和并发限制,因此可能只接收一个。本地默认并发上限为 1。运行 `rebut set max-concurrent 2` 并重启 MCP 宿主,即可启用本地并行审查。本地并发上限低于 2 时,Rebut 会在发送前拒绝该调用。各结果包含请求 ID 和 `has_review`。只收到一份审查正文时为 `partial`,两份都缺失时为 `incomplete`。如果两个请求均已完成且正文无法重放,则返回 `completed_without_review`。连接中断后,请在同一后端用原来的两个 ID 查询 `review_status`,再判断是否需要新的付费调用。状态查询无法重放审查正文。
81
+
82
+ 该工具由本地模式和 Worker 模式下的 Rebut 客户端提供。已有 Codex 注册时,运行 `rebut setup --client codex --replace` 并重启宿主。请重启 Claude Code 更新工具列表。
83
+
84
+ 本地使用不同供应商时,Rebut 进程必须能访问两把密钥。通过环境变量注册宿主时,默认只转发首选供应商的变量。
85
+
76
86
  ## 可选 Worker 部署
77
87
 
78
88
  需要跨设备共享预算和请求账本时使用。部署需要源码、自己的 Cloudflare 账户和 D1。
@@ -0,0 +1,24 @@
1
+ # Rebut 0.4.0
2
+
3
+ Codex와 Claude Code에서 두 프로필을 선택해 같은 변경을 병렬로 검토할 수 있습니다. 각 호스트의 단일 리뷰 기본 프로필도 따로 지정할 수 있습니다.
4
+
5
+ ## 병렬 리뷰
6
+
7
+ - 두 건의 유료 리뷰를 명시적으로 선택했다면 `review_pair`를 사용합니다. 수집한 스키마 2 번들을 `first`로 넘기고, `second`에 두 번째 프로필, 공급자, 별도 요청 ID를 지정합니다. 두 리뷰는 같은 자료를 서로 독립적으로 검토합니다. [#69](https://github.com/abruption/rebut/pull/69)
8
+ - 예산이나 동시 실행 한도에 따라 한쪽만 접수될 수 있습니다. 두 요청이 모두 접수된 경우에도 한쪽 결과가 불확실하면 반환된 본문만 확인할 수 있습니다. 응답이 끊기면 같은 백엔드에서 두 요청의 원래 ID로 `review_status`를 조회합니다. 상태 조회로 리뷰 본문을 다시 받을 수 없습니다.
9
+ - 로컬 한도가 2 미만이면 두 요청을 보내기 전에 거부합니다. 기본 한도는 1입니다. 병렬 리뷰를 쓰려면 `rebut set max-concurrent 2`를 실행한 뒤 MCP 호스트를 다시 시작합니다. 로컬에서 서로 다른 공급자를 쓰려면 Rebut 프로세스에 두 키가 필요하며, 환경변수 방식 등록은 기본적으로 선호 공급자의 변수만 전달합니다.
10
+
11
+ ## 호스트별 단일 리뷰 기본값
12
+
13
+ ```sh
14
+ rebut set profile claude-medium --client codex
15
+ rebut set profile astra-medium --client claude
16
+ ```
17
+
18
+ `rebut collect --client codex` 또는 `--client claude`로 해당 기본값을 사용합니다. 명시적으로 전달한 `--profile`이 우선하며, 호스트를 지정하지 않으면 공통 기본값을 사용합니다. 지정된 호스트의 기본 프로필을 사용할 수 없으면 수집에 실패합니다. 기존 번들의 프로필과 공급자는 유지됩니다. [#71](https://github.com/abruption/rebut/pull/71)
19
+
20
+ CLI를 갱신한 후 기존 등록은 `rebut setup --client codex --replace` 또는 `rebut setup --client claude --replace`로 갱신하고 호스트를 다시 시작합니다. Worker 모드에서도 두 기능은 CLI에서 동작하므로 새 기능을 쓰기 위한 Worker 재배포나 D1 마이그레이션은 필요하지 않습니다. 구버전으로 되돌리려면 0.4.0에서 `rebut set profile --client codex --clear`와 `rebut set profile --client claude --clear`를 실행하고, 이전 CLI를 설치한 뒤 두 호스트를 다시 등록합니다. [한국어 설정 안내](../guide/ko/configuration.md)
21
+
22
+ ## npm 발행 검증
23
+
24
+ npm 게시 후 공개 파일이 잠시 다운로드되지 않으면 검증 단계가 최대 25회, 전체 7분 이내로 재시도합니다. 파일 해시가 다르거나 영구 오류가 발생하면 즉시 실패합니다. [#67](https://github.com/abruption/rebut/pull/67)
package/lib/cli.mjs CHANGED
@@ -178,7 +178,7 @@ async function connectRemote(options2) {
178
178
  reconnectionDelayGrowFactor: 1
179
179
  }
180
180
  });
181
- const client = new Client({ name: "rebut-mcp", version: "0.3.3" });
181
+ const client = new Client({ name: "rebut-mcp", version: "0.4.0" });
182
182
  const close = client.close.bind(client);
183
183
  let closing;
184
184
  client.close = () => closing ??= (async () => {
@@ -203,6 +203,7 @@ async function connectRemote(options2) {
203
203
  }
204
204
 
205
205
  // src/client/settings.ts
206
+ var ProfileId = z2.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/);
206
207
  var SettingsSchema = z2.object({
207
208
  schemaVersion: z2.literal(1),
208
209
  mode: z2.enum(["local", "worker"]).optional(),
@@ -213,7 +214,11 @@ var SettingsSchema = z2.object({
213
214
  vaultwardenApiKeyItem: z2.string().min(1).max(200).refine((s) => !/[\x00-\x1f\x7f]/.test(s)).optional(),
214
215
  defaultModel: z2.string().regex(/^[a-zA-Z0-9._:-]{1,100}$/).optional(),
215
216
  defaultReasoning: z2.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).optional(),
216
- defaultProfile: z2.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/).optional(),
217
+ defaultProfile: ProfileId.optional(),
218
+ clientProfiles: z2.strictObject({
219
+ codex: ProfileId.optional(),
220
+ claude: ProfileId.optional()
221
+ }).optional(),
217
222
  vaultwardenAdminItem: z2.string().min(1).max(200).refine((s) => !/[\x00-\x1f\x7f]/.test(s)).default("Rebut \u2014 MCP Admin Token"),
218
223
  endpoint: z2.string().max(2048).optional(),
219
224
  secretStore: z2.enum(["keychain", "vaultwarden", "env"]),
@@ -293,8 +298,7 @@ async function createSettingsDirectory(path2) {
293
298
  await lstat(ancestor);
294
299
  break;
295
300
  } catch (error) {
296
- if (error.code !== "ENOENT")
297
- unsafeSettings();
301
+ if (error.code !== "ENOENT") unsafeSettings();
298
302
  ancestor = dirname(ancestor);
299
303
  }
300
304
  }
@@ -557,10 +561,215 @@ import {
557
561
  fromJsonSchema
558
562
  } from "@modelcontextprotocol/server";
559
563
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
564
+
565
+ // src/client/review-pair.ts
566
+ import { z as z4 } from "zod";
567
+
568
+ // src/contracts.ts
569
+ import { z as z3 } from "zod";
570
+ var MAX_INPUT_BYTES = 128e3;
571
+ var safePath = (path2) => path2.length > 0 && path2.length <= 512 && !/^[\/\\]|^[A-Za-z]:|[\\\x00-\x1f\x7f]/.test(path2) && path2.split("/").every((part) => part !== "" && part !== "." && part !== "..");
572
+ var PathSchema = z3.string().refine(safePath, "Expected a safe relative path");
573
+ var SafeId = z3.string().min(1).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/);
574
+ var ReviewInputSchema = z3.strictObject({
575
+ schema_version: z3.union([z3.literal(1), z3.literal(2)]).describe(
576
+ "Use 2 for new supplier-pinned bundles. Legacy 1 new requests are OpenAI only."
577
+ ),
578
+ provider: z3.enum(["openai", "anthropic"]).optional().describe(
579
+ "Required and hash-pinned for schema_version 2. Legacy schema 1 new requests are OpenAI only."
580
+ ),
581
+ request_id: SafeId.max(80),
582
+ profile: SafeId.max(64),
583
+ input_sha256: z3.string().regex(/^[a-f0-9]{64}$/),
584
+ task_kind: z3.enum(["code", "design", "text"]),
585
+ requirements: z3.string().max(16e3),
586
+ files: z3.array(
587
+ z3.strictObject({
588
+ path: PathSchema,
589
+ start_line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
590
+ content: z3.string()
591
+ })
592
+ ).max(40),
593
+ diff: z3.string().max(1e5)
594
+ }).superRefine((value, ctx) => {
595
+ if (value.schema_version === 2 && value.provider === void 0 || value.schema_version === 1 && value.provider !== void 0)
596
+ ctx.addIssue({
597
+ code: "custom",
598
+ message: "Schema 2 requires provider; legacy schema 1 must omit it"
599
+ });
600
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_INPUT_BYTES)
601
+ ctx.addIssue({ code: "custom", message: "Input exceeds byte limit" });
602
+ if (new Set(value.files.map((file) => file.path)).size !== value.files.length)
603
+ ctx.addIssue({ code: "custom", message: "File paths must be unique" });
604
+ if (!value.diff.trim() && !value.files.some((file) => file.content.trim()))
605
+ ctx.addIssue({ code: "custom", message: "Source content is required" });
606
+ for (const file of value.files) {
607
+ if (!Number.isSafeInteger(
608
+ file.start_line + file.content.split("\n").length - 1
609
+ ))
610
+ ctx.addIssue({
611
+ code: "custom",
612
+ message: "Source line range exceeds safe integers"
613
+ });
614
+ }
615
+ });
616
+ function inputProvider(input) {
617
+ if (input.schema_version === 1) return "openai";
618
+ if (input.provider !== "openai" && input.provider !== "anthropic")
619
+ throw new Error("Provider pin required");
620
+ return input.provider;
621
+ }
622
+ async function inputHash(input) {
623
+ const bytes = new TextEncoder().encode(
624
+ JSON.stringify({
625
+ schema_version: input.schema_version,
626
+ ...input.schema_version === 2 ? { provider: inputProvider(input) } : {},
627
+ task_kind: input.task_kind,
628
+ requirements: input.requirements,
629
+ files: input.files.map(({ path: path2, start_line, content }) => ({
630
+ path: path2,
631
+ start_line,
632
+ content
633
+ })),
634
+ diff: input.diff
635
+ })
636
+ );
637
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
638
+ return Array.from(
639
+ new Uint8Array(digest),
640
+ (byte) => byte.toString(16).padStart(2, "0")
641
+ ).join("");
642
+ }
643
+ function profileProvider(profile) {
644
+ const provider = profile.provider ?? "openai";
645
+ if (provider !== "openai" && provider !== "anthropic")
646
+ throw new Error("Invalid provider");
647
+ return provider;
648
+ }
649
+ var ReviewSchema = z3.strictObject({
650
+ summary: z3.string().min(1).max(16e3),
651
+ additional_evidence: z3.array(z3.string().max(8e3)).max(40),
652
+ findings: z3.array(
653
+ z3.strictObject({
654
+ severity: z3.enum(["critical", "high", "medium", "low"]),
655
+ title: z3.string().min(1).max(1e3),
656
+ explanation: z3.string().min(1).max(16e3),
657
+ path: PathSchema,
658
+ line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
659
+ end_line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
660
+ counterexample: z3.string().min(1).max(16e3),
661
+ remediation: z3.string().min(1).max(16e3)
662
+ })
663
+ ).max(100)
664
+ });
665
+
666
+ // src/client/review-pair.ts
667
+ var ReviewPairSchema = z4.strictObject({
668
+ first: ReviewInputSchema.describe(
669
+ "An unchanged schema version 2 bundle from rebut collect."
670
+ ),
671
+ second: z4.strictObject({
672
+ request_id: ReviewInputSchema.shape.request_id,
673
+ profile: ReviewInputSchema.shape.profile,
674
+ provider: ReviewInputSchema.shape.provider.unwrap()
675
+ }).describe(
676
+ "Explicit second reviewer. Rebut copies the first bundle's evidence and computes a supplier-pinned hash."
677
+ )
678
+ });
679
+ function toolResult(value, isError = false) {
680
+ return {
681
+ ...isError ? { isError: true } : {},
682
+ content: [{ type: "text", text: JSON.stringify(value) }]
683
+ };
684
+ }
685
+ function registerReviewPair(server, callReview, localMaxConcurrent) {
686
+ server.registerTool(
687
+ "review_pair",
688
+ {
689
+ description: "Use only when the user explicitly opts in to two paid reviews with distinct profiles. Dispatches through the active backend in parallel and shares its budget and concurrency limits. Keep both request IDs. After a lost response, call review_status for each original ID on this backend. Never start replacement paid requests automatically.",
690
+ inputSchema: ReviewPairSchema
691
+ },
692
+ async ({ first, second }, extra) => {
693
+ if (first.schema_version !== 2 || first.request_id === second.request_id || first.profile === second.profile) {
694
+ return toolResult(
695
+ {
696
+ status: "invalid_review_pair",
697
+ message: "Use a schema version 2 first bundle, distinct request IDs, and distinct profiles."
698
+ },
699
+ true
700
+ );
701
+ }
702
+ if (await inputHash(first) !== first.input_sha256)
703
+ return toolResult({ status: "input_hash_mismatch" }, true);
704
+ const candidate = { ...first, ...second };
705
+ const parsed = ReviewInputSchema.safeParse(candidate);
706
+ if (!parsed.success)
707
+ return toolResult({ status: "invalid_second_bundle" }, true);
708
+ const secondary = {
709
+ ...parsed.data,
710
+ input_sha256: await inputHash(parsed.data)
711
+ };
712
+ if (localMaxConcurrent !== void 0 && localMaxConcurrent < 2)
713
+ return toolResult(
714
+ {
715
+ status: "pair_concurrency_unavailable",
716
+ message: "Local parallel review requires a concurrency limit of at least 2. Use rebut set max-concurrent 2 to opt in."
717
+ },
718
+ true
719
+ );
720
+ const signal = extra.mcpReq.signal;
721
+ if (signal.aborted)
722
+ return toolResult(
723
+ { status: "review_pair_cancelled_before_dispatch" },
724
+ true
725
+ );
726
+ const reviews = await Promise.all(
727
+ [first, secondary].map(async (input) => {
728
+ const identity = {
729
+ request_id: input.request_id,
730
+ profile: input.profile,
731
+ provider: input.provider,
732
+ input_sha256: input.input_sha256
733
+ };
734
+ try {
735
+ const response = await callReview(input, signal);
736
+ const [content] = response.content;
737
+ const result = content?.type === "text" && content.text ? JSON.parse(content.text) : void 0;
738
+ if (response.content.length === 1 && typeof result?.status === "string")
739
+ return {
740
+ ...identity,
741
+ has_review: !response.isError && result.status === "completed" && typeof result.review?.summary === "string",
742
+ result
743
+ };
744
+ } catch {
745
+ }
746
+ return {
747
+ ...identity,
748
+ has_review: false,
749
+ result: {
750
+ status: "unknown",
751
+ result_replay_available: false,
752
+ message: "Query review_status with this original request ID on the same backend."
753
+ }
754
+ };
755
+ })
756
+ );
757
+ const returned = reviews.filter(({ has_review }) => has_review).length;
758
+ let status = "incomplete";
759
+ if (returned === 2) status = "completed";
760
+ else if (returned === 1) status = "partial";
761
+ else if (reviews.every(({ result }) => result.status === "completed"))
762
+ status = "completed_without_review";
763
+ return toolResult({ status, reviews });
764
+ }
765
+ );
766
+ }
767
+
768
+ // src/client/stdio.ts
560
769
  var REVIEW_GUIDANCE = "Use only when the user explicitly opts in to a review using the frozen profile provider. Keep the original request_id and backend after uncertainty and query review_status before another paid invocation. Do not automatically change reviewers, providers, or keys. Project default real API tests: luna-test (gpt-6-luna).";
561
770
  async function serveStdio(options2) {
562
771
  const remote = await connectRemote(options2);
563
- const server = new McpServer({ name: "rebut-mcp", version: "0.3.3" });
772
+ const server = new McpServer({ name: "rebut-mcp", version: "0.4.0" });
564
773
  let finish;
565
774
  const finished = new Promise((resolve6) => {
566
775
  finish = resolve6;
@@ -590,7 +799,7 @@ async function serveStdio(options2) {
590
799
  title: tool.title,
591
800
  description: tool.name === "review" ? `${tool.description ?? ""}
592
801
 
593
- ${REVIEW_GUIDANCE}${options2.preferredProfile ? "\nPreferred profile for new reviews: " + options2.preferredProfile.id + " (model " + options2.preferredProfile.model + ", reasoning " + (options2.preferredProfile.reasoning ?? "provider default") + "). Explicit request profile remains authoritative." : ""}`.trim() : tool.description,
802
+ ${REVIEW_GUIDANCE}${options2.preferredProfile ? "\nPreferred profile for new reviews: " + options2.preferredProfile.id + " (model " + options2.preferredProfile.model + ", reasoning " + (options2.preferredProfile.reasoning ?? "provider default") + "). Explicit request profile remains authoritative." : options2.clientProfileUnavailable ? "\nCould not resolve the configured client default. Select an enabled profile explicitly." : options2.reviewUnavailable ? "\nThe shared review preference is unavailable." : ""}${options2.client ? "\nFor new bundles, use rebut collect --client " + options2.client + " to apply this client default." : ""}`.trim() : tool.description,
594
803
  inputSchema: fromJsonSchema(
595
804
  tool.inputSchema
596
805
  ),
@@ -630,6 +839,10 @@ ${REVIEW_GUIDANCE}${options2.preferredProfile ? "\nPreferred profile for new rev
630
839
  )) {
631
840
  throw new Error(REMOTE_FAILURE_MESSAGE);
632
841
  }
842
+ registerReviewPair(
843
+ server,
844
+ (input, signal) => remote.callTool({ name: "review", arguments: input }, { signal })
845
+ );
633
846
  await server.connect(new StdioServerTransport());
634
847
  await finished;
635
848
  } catch {
@@ -749,7 +962,7 @@ async function readConfig(path2) {
749
962
  await file?.close();
750
963
  }
751
964
  }
752
- function safePath(path2) {
965
+ function safePath2(path2) {
753
966
  if (/[\x00-\x1f\x7f]|\$\{/.test(path2))
754
967
  fail(
755
968
  "INVALID_PATH",
@@ -760,7 +973,7 @@ function safePath(path2) {
760
973
  function desired(options2) {
761
974
  const env = {};
762
975
  if (options2.configDir !== void 0)
763
- env.REBUT_CONFIG_DIR = safePath(options2.configDir);
976
+ env.REBUT_CONFIG_DIR = safePath2(options2.configDir);
764
977
  if (options2.forwardApiKeyEnv) {
765
978
  const name = options2.apiKeyEnv ?? "REBUT_OPENAI_API_KEY";
766
979
  if (![
@@ -773,8 +986,8 @@ function desired(options2) {
773
986
  } else if (options2.forwardTokenEnv) env.REBUT_TOKEN = "${REBUT_TOKEN:-}";
774
987
  return {
775
988
  type: "stdio",
776
- command: safePath(options2.nodePath ?? process.execPath),
777
- args: [safePath(options2.entrypoint), "mcp"],
989
+ command: safePath2(options2.nodePath ?? process.execPath),
990
+ args: [safePath2(options2.entrypoint), "mcp", "--client", "claude"],
778
991
  timeout: CODEX_TOOL_TIMEOUT_SECONDS * 1e3,
779
992
  ...Object.keys(env).length ? { env } : {}
780
993
  };
@@ -797,7 +1010,7 @@ function equivalent(a, b) {
797
1010
  function recognized(value) {
798
1011
  if (typeof value !== "object" || !value || Array.isArray(value)) return false;
799
1012
  const v = value;
800
- return (v.type === void 0 || v.type === "stdio") && typeof v.command === "string" && isAbsolute(v.command) && Array.isArray(v.args) && v.args.length === 2 && typeof v.args[0] === "string" && /(?:^|[\\/])bin[\\/]rebut\.mjs$/.test(v.args[0]) && v.args[1] === "mcp";
1013
+ return (v.type === void 0 || v.type === "stdio") && typeof v.command === "string" && isAbsolute(v.command) && Array.isArray(v.args) && (v.args.length === 2 || v.args.length === 4 && v.args[2] === "--client" && v.args[3] === "claude") && typeof v.args[0] === "string" && /(?:^|[\\/])bin[\\/]rebut\.mjs$/.test(v.args[0]) && v.args[1] === "mcp";
801
1014
  }
802
1015
  async function update(options2, remove) {
803
1016
  if (!options2.claudeConfig && process.env.CLAUDE_CONFIG_DIR)
@@ -805,7 +1018,7 @@ async function update(options2, remove) {
805
1018
  "CONFIG_PATH_REQUIRED",
806
1019
  "Set --claude-config PATH explicitly when CLAUDE_CONFIG_DIR is in use."
807
1020
  );
808
- const configPath = safePath(
1021
+ const configPath = safePath2(
809
1022
  options2.claudeConfig ?? join3(homedir3(), ".claude.json")
810
1023
  );
811
1024
  let temporary;
@@ -872,110 +1085,10 @@ var setupClaude = (options2) => update(options2, false);
872
1085
  var removeClaude = (options2) => update(options2, true);
873
1086
 
874
1087
  // src/review.ts
875
- import { z as z5 } from "zod";
876
-
877
- // src/anthropic.ts
878
- import { z as z4 } from "zod";
879
-
880
- // src/contracts.ts
881
- import { z as z3 } from "zod";
882
- var MAX_INPUT_BYTES = 128e3;
883
- var safePath2 = (path2) => path2.length > 0 && path2.length <= 512 && !/^[\/\\]|^[A-Za-z]:|[\\\x00-\x1f\x7f]/.test(path2) && path2.split("/").every((part) => part !== "" && part !== "." && part !== "..");
884
- var PathSchema = z3.string().refine(safePath2, "Expected a safe relative path");
885
- var SafeId = z3.string().min(1).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/);
886
- var ReviewInputSchema = z3.strictObject({
887
- schema_version: z3.union([z3.literal(1), z3.literal(2)]).describe(
888
- "Use 2 for new supplier-pinned bundles. Legacy 1 new requests are OpenAI only."
889
- ),
890
- provider: z3.enum(["openai", "anthropic"]).optional().describe(
891
- "Required and hash-pinned for schema_version 2. Legacy schema 1 new requests are OpenAI only."
892
- ),
893
- request_id: SafeId.max(80),
894
- profile: SafeId.max(64),
895
- input_sha256: z3.string().regex(/^[a-f0-9]{64}$/),
896
- task_kind: z3.enum(["code", "design", "text"]),
897
- requirements: z3.string().max(16e3),
898
- files: z3.array(
899
- z3.strictObject({
900
- path: PathSchema,
901
- start_line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
902
- content: z3.string()
903
- })
904
- ).max(40),
905
- diff: z3.string().max(1e5)
906
- }).superRefine((value, ctx) => {
907
- if (value.schema_version === 2 && value.provider === void 0 || value.schema_version === 1 && value.provider !== void 0)
908
- ctx.addIssue({
909
- code: "custom",
910
- message: "Schema 2 requires provider; legacy schema 1 must omit it"
911
- });
912
- if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_INPUT_BYTES)
913
- ctx.addIssue({ code: "custom", message: "Input exceeds byte limit" });
914
- if (new Set(value.files.map((file) => file.path)).size !== value.files.length)
915
- ctx.addIssue({ code: "custom", message: "File paths must be unique" });
916
- if (!value.diff.trim() && !value.files.some((file) => file.content.trim()))
917
- ctx.addIssue({ code: "custom", message: "Source content is required" });
918
- for (const file of value.files) {
919
- if (!Number.isSafeInteger(
920
- file.start_line + file.content.split("\n").length - 1
921
- ))
922
- ctx.addIssue({
923
- code: "custom",
924
- message: "Source line range exceeds safe integers"
925
- });
926
- }
927
- });
928
- function inputProvider(input) {
929
- if (input.schema_version === 1) return "openai";
930
- if (input.provider !== "openai" && input.provider !== "anthropic")
931
- throw new Error("Provider pin required");
932
- return input.provider;
933
- }
934
- async function inputHash(input) {
935
- const bytes = new TextEncoder().encode(
936
- JSON.stringify({
937
- schema_version: input.schema_version,
938
- ...input.schema_version === 2 ? { provider: inputProvider(input) } : {},
939
- task_kind: input.task_kind,
940
- requirements: input.requirements,
941
- files: input.files.map(({ path: path2, start_line, content }) => ({
942
- path: path2,
943
- start_line,
944
- content
945
- })),
946
- diff: input.diff
947
- })
948
- );
949
- const digest = await crypto.subtle.digest("SHA-256", bytes);
950
- return Array.from(
951
- new Uint8Array(digest),
952
- (byte) => byte.toString(16).padStart(2, "0")
953
- ).join("");
954
- }
955
- function profileProvider(profile) {
956
- const provider = profile.provider ?? "openai";
957
- if (provider !== "openai" && provider !== "anthropic")
958
- throw new Error("Invalid provider");
959
- return provider;
960
- }
961
- var ReviewSchema = z3.strictObject({
962
- summary: z3.string().min(1).max(16e3),
963
- additional_evidence: z3.array(z3.string().max(8e3)).max(40),
964
- findings: z3.array(
965
- z3.strictObject({
966
- severity: z3.enum(["critical", "high", "medium", "low"]),
967
- title: z3.string().min(1).max(1e3),
968
- explanation: z3.string().min(1).max(16e3),
969
- path: PathSchema,
970
- line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
971
- end_line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
972
- counterexample: z3.string().min(1).max(16e3),
973
- remediation: z3.string().min(1).max(16e3)
974
- })
975
- ).max(100)
976
- });
1088
+ import { z as z6 } from "zod";
977
1089
 
978
1090
  // src/anthropic.ts
1091
+ import { z as z5 } from "zod";
979
1092
  var ANTHROPIC_VERSION = "2026-10-21";
980
1093
  var record = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
981
1094
  var counter = (v) => Number.isSafeInteger(v) && v >= 0;
@@ -1046,7 +1159,7 @@ function buildAnthropicBody(input, profile, instructions) {
1046
1159
  format: {
1047
1160
  type: "json_schema",
1048
1161
  schema: anthropicSchema(
1049
- z4.toJSONSchema(ReviewSchema, { target: "draft-7" })
1162
+ z5.toJSONSchema(ReviewSchema, { target: "draft-7" })
1050
1163
  )
1051
1164
  }
1052
1165
  }
@@ -1146,7 +1259,7 @@ function buildReviewBody(input, profile) {
1146
1259
  type: "json_schema",
1147
1260
  name: "rebut_review",
1148
1261
  strict: true,
1149
- schema: z5.toJSONSchema(ReviewSchema, { target: "draft-7" })
1262
+ schema: z6.toJSONSchema(ReviewSchema, { target: "draft-7" })
1150
1263
  }
1151
1264
  }
1152
1265
  };
@@ -1167,12 +1280,12 @@ function estimateReservation(input, profile, serializedBody) {
1167
1280
  profile
1168
1281
  );
1169
1282
  }
1170
- var count = z5.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
1171
- var UsageSchema = z5.object({
1283
+ var count = z6.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
1284
+ var UsageSchema = z6.object({
1172
1285
  input_tokens: count,
1173
1286
  output_tokens: count,
1174
- input_tokens_details: z5.object({ cached_tokens: count }),
1175
- output_tokens_details: z5.object({ reasoning_tokens: count }),
1287
+ input_tokens_details: z6.object({ cached_tokens: count }),
1288
+ output_tokens_details: z6.object({ reasoning_tokens: count }),
1176
1289
  total_tokens: count
1177
1290
  }).refine(
1178
1291
  (v) => v.input_tokens_details.cached_tokens <= v.input_tokens && v.output_tokens_details.reasoning_tokens <= v.output_tokens && Number.isSafeInteger(v.input_tokens + v.output_tokens) && v.total_tokens === v.input_tokens + v.output_tokens
@@ -1199,7 +1312,7 @@ function evidenceRanges(input) {
1199
1312
  }
1200
1313
  if (line.startsWith("+++ ") && oldRemaining === 0 && newRemaining === 0) {
1201
1314
  const candidate = line.slice(4).split(" ")[0].replace(/^b\//, "");
1202
- path2 = safePath2(candidate) && candidate !== "/dev/null" ? candidate : void 0;
1315
+ path2 = safePath(candidate) && candidate !== "/dev/null" ? candidate : void 0;
1203
1316
  } else if (line.startsWith("@@ ")) {
1204
1317
  const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
1205
1318
  oldRemaining = match ? Number(match[2] ?? 1) : 0;
@@ -1574,14 +1687,25 @@ function equivalent2(a, b) {
1574
1687
  function desired2(options2) {
1575
1688
  return {
1576
1689
  command: options2.nodePath ?? process.execPath,
1577
- args: [resolve3(options2.entrypoint), "mcp"],
1690
+ args: [resolve3(options2.entrypoint), "mcp", "--client", "codex"],
1578
1691
  startup_timeout_sec: 60,
1579
1692
  tool_timeout_sec: CODEX_TOOL_TIMEOUT_SECONDS,
1580
- enabled_tools: ["review", "review_status"],
1693
+ enabled_tools: ["review", "review_status", "review_pair"],
1581
1694
  ...options2.forwardApiKeyEnv ? { env_vars: [options2.apiKeyEnv ?? "REBUT_OPENAI_API_KEY"] } : options2.forwardTokenEnv ? { env_vars: ["REBUT_TOKEN"] } : {},
1582
1695
  ...options2.configDir !== void 0 ? { env: { REBUT_CONFIG_DIR: resolve3(options2.configDir) } } : {}
1583
1696
  };
1584
1697
  }
1698
+ function providerKeyVars(value) {
1699
+ return value === void 0 || Array.isArray(value) && value.length === 1 && (value[0] === "REBUT_OPENAI_API_KEY" || value[0] === "OPENAI_API_KEY" || value[0] === "REBUT_ANTHROPIC_API_KEY");
1700
+ }
1701
+ function matchesRemoval(existing, desired3, entrypoint) {
1702
+ if (!table(existing)) return false;
1703
+ const { env_vars: existingVars, ...registered } = existing;
1704
+ const { env_vars: desiredVars, ...expected } = desired3;
1705
+ if (!equivalent2(existingVars, desiredVars) && !(providerKeyVars(existingVars) && providerKeyVars(desiredVars)))
1706
+ return false;
1707
+ return equivalent2(registered, expected) || equivalent2(registered, { ...expected, args: [resolve3(entrypoint), "mcp"] });
1708
+ }
1585
1709
  function headers(source) {
1586
1710
  const result = [];
1587
1711
  let quote = "", triple = false, lineStart = true;
@@ -1699,7 +1823,7 @@ async function update2(options2, remove) {
1699
1823
  if (!remove && equivalent2(existing, replacement) || remove && existing === void 0) {
1700
1824
  return { configPath, changed: false };
1701
1825
  }
1702
- if (existing !== void 0 && !equivalent2(existing, replacement) && !options2.replace) {
1826
+ if (existing !== void 0 && !equivalent2(existing, replacement) && !(remove && matchesRemoval(existing, replacement, options2.entrypoint)) && !options2.replace) {
1703
1827
  throw new CodexSetupError(
1704
1828
  "SERVER_CONFLICT",
1705
1829
  "Codex already has a different rebut server. Use --replace to replace it."
@@ -1762,7 +1886,7 @@ function redact(text) {
1762
1886
  );
1763
1887
  }
1764
1888
  async function readSafe(root, relative) {
1765
- if (!safePath2(relative) || relative.split("/").some((_, i, a) => forbidden.test(a.slice(0, i + 1).join("/"))))
1889
+ if (!safePath(relative) || relative.split("/").some((_, i, a) => forbidden.test(a.slice(0, i + 1).join("/"))))
1766
1890
  throw new Error("Disallowed source path");
1767
1891
  const parts = relative.split("/");
1768
1892
  let current = root;
@@ -1839,15 +1963,15 @@ async function collect(root, files, requirements, request_id, profile = "astra-m
1839
1963
  }
1840
1964
 
1841
1965
  // src/client/profiles.ts
1842
- import { z as z6 } from "zod";
1843
- var Id = z6.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/);
1844
- var RecordSchema = z6.strictObject({
1966
+ import { z as z7 } from "zod";
1967
+ var Id = z7.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/);
1968
+ var RecordSchema = z7.strictObject({
1845
1969
  id: Id,
1846
- revision: z6.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
1847
- enabled: z6.boolean(),
1970
+ revision: z7.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
1971
+ enabled: z7.boolean(),
1848
1972
  profile: ProfileSchema.optional()
1849
1973
  }).refine((record3) => !record3.enabled || record3.profile !== void 0);
1850
- var ListSchema = z6.strictObject({ profiles: z6.array(RecordSchema) }).refine(
1974
+ var ListSchema = z7.strictObject({ profiles: z7.array(RecordSchema) }).refine(
1851
1975
  ({ profiles }) => new Set(profiles.map((record3) => record3.id)).size === profiles.length
1852
1976
  );
1853
1977
  var FAILURE = "Profile request failed; no automatic retry was made.";
@@ -2108,8 +2232,8 @@ async function profileCommand(args, deps) {
2108
2232
  command === "set" ? "PUT" : "DELETE",
2109
2233
  { expected_revision: revision, ...profile ? { profile } : {} }
2110
2234
  );
2111
- const parsed = z6.strictObject({
2112
- status: z6.literal("updated"),
2235
+ const parsed = z7.strictObject({
2236
+ status: z7.literal("updated"),
2113
2237
  record: RecordSchema.refine((record3) => record3.revision > 0)
2114
2238
  }).safeParse(payload);
2115
2239
  if (!parsed.success || parsed.data.record.id !== id)
@@ -2126,7 +2250,7 @@ import { homedir as homedir5 } from "node:os";
2126
2250
  import { dirname as dirname5, join as join5, resolve as resolve4 } from "node:path";
2127
2251
  import { McpServer as McpServer2 } from "@modelcontextprotocol/server";
2128
2252
  import { StdioServerTransport as StdioServerTransport2 } from "@modelcontextprotocol/server/stdio";
2129
- import { z as z7 } from "zod";
2253
+ import { z as z8 } from "zod";
2130
2254
 
2131
2255
  // src/ledger.ts
2132
2256
  function monthlyCycleInsert(day, now) {
@@ -2736,7 +2860,7 @@ async function openLocalRuntime(settings, options2 = {}) {
2736
2860
  }
2737
2861
  };
2738
2862
  }
2739
- var toolResult = (value) => ({
2863
+ var toolResult2 = (value) => ({
2740
2864
  content: [
2741
2865
  {
2742
2866
  type: "text",
@@ -2744,13 +2868,14 @@ var toolResult = (value) => ({
2744
2868
  }
2745
2869
  ]
2746
2870
  });
2747
- async function localMcpServer(runtime, settings) {
2871
+ async function localMcpServer(runtime, settings, client) {
2872
+ const clientProfile = client && settings.clientProfiles?.[client];
2748
2873
  const records = await runtime.profiles.list();
2749
- const hasPreference = !!(settings.defaultModel || settings.defaultReasoning || settings.defaultProfile);
2874
+ const hasPreference = !!(settings.defaultModel || settings.defaultReasoning || settings.defaultProfile || clientProfile);
2750
2875
  let preferred, unavailable = false;
2751
2876
  try {
2752
2877
  preferred = resolveProfile(records, {
2753
- profile: settings.defaultProfile,
2878
+ profile: clientProfile ?? settings.defaultProfile,
2754
2879
  provider: settings.provider,
2755
2880
  model: settings.defaultModel || settings.defaultReasoning ? settings.defaultModel ?? records.find(
2756
2881
  (r) => r.id === (settings.provider === "anthropic" ? "claude-medium" : "astra-medium") && r.enabled
@@ -2760,61 +2885,63 @@ async function localMcpServer(runtime, settings) {
2760
2885
  } catch {
2761
2886
  unavailable = hasPreference;
2762
2887
  }
2763
- const server = new McpServer2({ name: "rebut-mcp", version: "0.3.3" });
2764
- server.registerTool(
2765
- "review",
2766
- {
2767
- description: `Explicit opt-in provider review. Local per-device ledger; budgets are not shared with another machine or Worker. Keep the original request_id and backend after uncertainty; never replay another backend's uncertain request here. ${preferred ? "Preferred profile: " + preferred : unavailable ? "Configured profile is unavailable." : "Select an enabled profile explicitly."}`,
2768
- inputSchema: ReviewInputSchema
2769
- },
2770
- async (input, extra) => {
2771
- try {
2772
- return toolResult(await runtime.review(input, extra.mcpReq.signal));
2773
- } catch (error) {
2774
- if (error instanceof ProviderKeyUnavailable)
2775
- return {
2776
- isError: true,
2777
- ...toolResult({
2778
- status: "provider_key_unavailable",
2779
- message: "Check local credentials with rebut doctor and query the original ID before any further paid invocation."
2780
- })
2781
- };
2888
+ const server = new McpServer2({ name: "rebut-mcp", version: "0.4.0" });
2889
+ const review = async (input, signal) => {
2890
+ try {
2891
+ return toolResult2(await runtime.review(input, signal));
2892
+ } catch (error) {
2893
+ if (error instanceof ProviderKeyUnavailable)
2782
2894
  return {
2783
2895
  isError: true,
2784
- ...toolResult({
2785
- status: "request_failed",
2786
- message: "Query review_status with the same request_id before any further paid invocation."
2896
+ ...toolResult2({
2897
+ status: "provider_key_unavailable",
2898
+ message: "Check local credentials with rebut doctor and query the original ID before any further paid invocation."
2787
2899
  })
2788
2900
  };
2789
- }
2901
+ return {
2902
+ isError: true,
2903
+ ...toolResult2({
2904
+ status: "request_failed",
2905
+ message: "Query review_status with the same request_id before any further paid invocation."
2906
+ })
2907
+ };
2790
2908
  }
2909
+ };
2910
+ server.registerTool(
2911
+ "review",
2912
+ {
2913
+ description: `Explicit opt-in provider review. Local per-device ledger; budgets are not shared with another machine or Worker. Keep the original request_id and backend after uncertainty; never replay another backend's uncertain request here. ${preferred ? "Preferred profile: " + preferred : unavailable ? "Configured profile is unavailable." : "Select an enabled profile explicitly."}${client ? " For new bundles, use rebut collect --client " + client + " to apply this client default." : ""}`,
2914
+ inputSchema: ReviewInputSchema
2915
+ },
2916
+ (input, extra) => review(input, extra.mcpReq.signal)
2791
2917
  );
2792
2918
  server.registerTool(
2793
2919
  "review_status",
2794
2920
  {
2795
2921
  description: "Read local metadata only; no paid execution and no review-body replay.",
2796
- inputSchema: z7.object({
2797
- request_id: z7.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/)
2922
+ inputSchema: z8.object({
2923
+ request_id: z8.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/)
2798
2924
  }).strict()
2799
2925
  },
2800
2926
  async ({ request_id }) => {
2801
2927
  try {
2802
- return toolResult(await runtime.status(request_id));
2928
+ return toolResult2(await runtime.status(request_id));
2803
2929
  } catch {
2804
2930
  return {
2805
2931
  isError: true,
2806
- ...toolResult({ status: "status_unavailable" })
2932
+ ...toolResult2({ status: "status_unavailable" })
2807
2933
  };
2808
2934
  }
2809
2935
  }
2810
2936
  );
2937
+ registerReviewPair(server, review, runtime.config.limits.maxConcurrent);
2811
2938
  return server;
2812
2939
  }
2813
- async function serveLocalStdio(settings) {
2940
+ async function serveLocalStdio(settings, client) {
2814
2941
  const runtime = await openLocalRuntime(settings);
2815
2942
  let server;
2816
2943
  try {
2817
- server = await localMcpServer(runtime, settings);
2944
+ server = await localMcpServer(runtime, settings, client);
2818
2945
  } catch (error) {
2819
2946
  await runtime.close();
2820
2947
  throw error;
@@ -2868,7 +2995,8 @@ rebut set request-budget USD
2868
2995
  rebut set vaultwarden-admin-item NAME
2869
2996
  rebut set model MODEL
2870
2997
  rebut set reasoning EFFORT
2871
- rebut set profile PROFILE_ID
2998
+ rebut set profile PROFILE_ID [--client codex|claude]
2999
+ rebut set profile --client codex|claude --clear
2872
3000
  rebut set admin-token [--stdin]
2873
3001
  rebut profile list
2874
3002
  rebut profile set ID [--provider openai|anthropic] --model MODEL --reasoning EFFORT --max-output-tokens N --input-usd-per-million USD --output-usd-per-million USD --price-version VERSION [--if-revision N]
@@ -2876,12 +3004,12 @@ rebut profile remove ID [--if-revision N]
2876
3004
  rebut set token [--stdin] Hidden input; never pass a token as an argument
2877
3005
  rebut setup --client codex|claude [--codex-home PATH | --claude-config PATH] [--replace]
2878
3006
  rebut remove --client codex|claude [--codex-home PATH | --claude-config PATH] [--replace]
2879
- rebut mcp Start the local server or Worker bridge
2880
- rebut doctor [--connect] [--provider] Check selected backend; --connect lists tools, never calls a model
3007
+ rebut mcp [--client codex|claude] Start the local server or Worker bridge
3008
+ rebut doctor [--connect] [--provider] [--client codex|claude] Check selected backend; --connect lists tools, never calls a model
2881
3009
  rebut status --pending Local reserved/unknown metadata only
2882
3010
  rebut status REQUEST_ID Free metadata query
2883
3011
  rebut review Explicit paid review; JSON bundle on stdin
2884
- rebut collect --root PATH --request-id ID --requirements TEXT [--profile ID] -- FILE...
3012
+ rebut collect --root PATH --request-id ID --requirements TEXT [--profile ID] [--client codex|claude] -- FILE...
2885
3013
  rebut --version
2886
3014
 
2887
3015
  New installs run locally with your selected provider API key. Host registration does not select the provider. No Cloudflare account is required.
@@ -2905,6 +3033,11 @@ function options(args, opts, positionals = false) {
2905
3033
  throw new CliError("Invalid arguments. Run rebut --help.");
2906
3034
  }
2907
3035
  }
3036
+ function selectedClient(value) {
3037
+ if (value === void 0 || value === "codex" || value === "claude")
3038
+ return value;
3039
+ throw new CliError("Specify --client codex or claude.");
3040
+ }
2908
3041
  async function stdin(max = 16e4) {
2909
3042
  const chunks = [];
2910
3043
  let size = 0;
@@ -3013,6 +3146,47 @@ async function runCli(args) {
3013
3146
  );
3014
3147
  return;
3015
3148
  }
3149
+ if (key === "profile") {
3150
+ const parsed = options(
3151
+ values,
3152
+ {
3153
+ client: { type: "string" },
3154
+ clear: { type: "boolean" }
3155
+ },
3156
+ true
3157
+ );
3158
+ const client = selectedClient(parsed.values.client);
3159
+ const [value2] = parsed.positionals;
3160
+ if (parsed.values.clear) {
3161
+ if (!client || parsed.positionals.length)
3162
+ throw new CliError(
3163
+ "Use rebut set profile --client codex|claude --clear."
3164
+ );
3165
+ if (settings.clientProfiles) {
3166
+ delete settings.clientProfiles[client];
3167
+ if (!settings.clientProfiles.codex && !settings.clientProfiles.claude)
3168
+ delete settings.clientProfiles;
3169
+ }
3170
+ } else {
3171
+ if (parsed.positionals.length !== 1 || !value2 || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(value2))
3172
+ throw new CliError("Expected one valid profile ID.");
3173
+ if (client)
3174
+ settings.clientProfiles = {
3175
+ ...settings.clientProfiles,
3176
+ [client]: value2
3177
+ };
3178
+ else {
3179
+ settings.defaultProfile = value2;
3180
+ delete settings.defaultModel;
3181
+ delete settings.defaultReasoning;
3182
+ }
3183
+ }
3184
+ await writeSettings(settings);
3185
+ process.stdout.write(
3186
+ "Profile preference saved. Restart the MCP host. Re-register existing hosts to enable client selection or refresh forwarded API key environment variables.\n"
3187
+ );
3188
+ return;
3189
+ }
3016
3190
  if (values.length !== 1)
3017
3191
  throw new CliError(
3018
3192
  "Expected one configuration value. Tokens must use hidden input."
@@ -3094,12 +3268,6 @@ async function runCli(args) {
3094
3268
  throw new CliError("Invalid reasoning effort.");
3095
3269
  settings.defaultReasoning = value;
3096
3270
  delete settings.defaultProfile;
3097
- } else if (key === "profile") {
3098
- if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(value))
3099
- throw new CliError("Invalid profile ID.");
3100
- settings.defaultProfile = value;
3101
- delete settings.defaultModel;
3102
- delete settings.defaultReasoning;
3103
3271
  } else throw new CliError("Unknown configuration key.");
3104
3272
  await writeSettings(settings);
3105
3273
  process.stdout.write(
@@ -3114,9 +3282,8 @@ async function runCli(args) {
3114
3282
  "claude-config": { type: "string" },
3115
3283
  replace: { type: "boolean" }
3116
3284
  });
3117
- const client = parsed.values.client;
3118
- if (client !== "codex" && client !== "claude")
3119
- throw new CliError("Specify --client codex or claude.");
3285
+ const client = selectedClient(parsed.values.client);
3286
+ if (!client) throw new CliError("Specify --client codex or claude.");
3120
3287
  if (client === "claude" && parsed.values["codex-home"] || client === "codex" && parsed.values["claude-config"])
3121
3288
  throw new CliError("Use only the selected host configuration option.");
3122
3289
  if (command === "setup" && mode === "worker" && !settings.endpoint)
@@ -3125,10 +3292,17 @@ async function runCli(args) {
3125
3292
  process.argv[1] || fileURLToPath(new URL("../bin/rebut.mjs", import.meta.url))
3126
3293
  );
3127
3294
  let keyProvider = settings.provider ?? "openai";
3128
- if (command === "setup" && mode === "local" && settings.secretStore === "env") {
3295
+ let forwardApiKeyEnv = mode === "local" && settings.secretStore === "env";
3296
+ if (command === "setup" && forwardApiKeyEnv) {
3129
3297
  try {
3130
- keyProvider = (await preferred()).provider;
3298
+ keyProvider = (await preferred(void 0, client)).provider;
3131
3299
  } catch {
3300
+ if (settings.clientProfiles?.[client]) {
3301
+ forwardApiKeyEnv = false;
3302
+ process.stderr.write(
3303
+ "Client default could not be resolved. No provider key variable was added to the registration.\n"
3304
+ );
3305
+ }
3132
3306
  }
3133
3307
  }
3134
3308
  const value = {
@@ -3137,7 +3311,7 @@ async function runCli(args) {
3137
3311
  entrypoint,
3138
3312
  replace: parsed.values.replace,
3139
3313
  forwardTokenEnv: mode === "worker" && settings.secretStore === "env",
3140
- forwardApiKeyEnv: mode === "local" && settings.secretStore === "env",
3314
+ forwardApiKeyEnv,
3141
3315
  apiKeyEnv: providerEnvName(settings, keyProvider),
3142
3316
  configDir: process.env.REBUT_CONFIG_DIR
3143
3317
  };
@@ -3153,7 +3327,8 @@ async function runCli(args) {
3153
3327
  root: { type: "string" },
3154
3328
  "request-id": { type: "string" },
3155
3329
  requirements: { type: "string" },
3156
- profile: { type: "string" }
3330
+ profile: { type: "string" },
3331
+ client: { type: "string" }
3157
3332
  },
3158
3333
  true
3159
3334
  );
@@ -3161,7 +3336,16 @@ async function runCli(args) {
3161
3336
  throw new CliError(
3162
3337
  "Collect requires root, request-id, requirements and explicit source files."
3163
3338
  );
3164
- const chosen = await preferred(p.values.profile);
3339
+ const client = selectedClient(p.values.client);
3340
+ if (!client && p.values.profile === void 0 && (settings.clientProfiles?.codex || settings.clientProfiles?.claude)) {
3341
+ process.stderr.write(
3342
+ "No client selected. This bundle uses the shared review preference. Pass --client codex or --client claude to use a client default.\n"
3343
+ );
3344
+ }
3345
+ const chosen = await preferred(
3346
+ p.values.profile,
3347
+ client
3348
+ );
3165
3349
  output(
3166
3350
  await collect(
3167
3351
  p.values.root,
@@ -3174,7 +3358,8 @@ async function runCli(args) {
3174
3358
  );
3175
3359
  return;
3176
3360
  }
3177
- async function preferred(explicitProfile) {
3361
+ async function preferred(explicitProfile, client) {
3362
+ const selectedProfile = explicitProfile ?? (client && settings.clientProfiles?.[client]);
3178
3363
  if (mode === "worker" && !settings.endpoint)
3179
3364
  throw new CliError(
3180
3365
  "Set the Worker endpoint before selecting server models."
@@ -3188,7 +3373,7 @@ async function runCli(args) {
3188
3373
  )?.profile?.model;
3189
3374
  const id = resolveProfile(
3190
3375
  records,
3191
- explicitProfile !== void 0 ? { profile: explicitProfile } : {
3376
+ selectedProfile !== void 0 ? { profile: selectedProfile } : {
3192
3377
  provider: settings.provider,
3193
3378
  profile: settings.defaultProfile,
3194
3379
  model: settings.defaultModel || settings.defaultReasoning ? model : void 0,
@@ -3266,40 +3451,46 @@ async function runCli(args) {
3266
3451
  if (command === "doctor") {
3267
3452
  const p = options(rest, {
3268
3453
  connect: { type: "boolean" },
3269
- provider: { type: "boolean" }
3454
+ provider: { type: "boolean" },
3455
+ client: { type: "string" }
3270
3456
  });
3457
+ const client = selectedClient(p.values.client);
3458
+ const clientProfile = client && settings.clientProfiles?.[client];
3271
3459
  if (p.values.provider && mode !== "local")
3272
3460
  throw new CliError(
3273
3461
  "Provider metadata diagnostics are local mode only; Worker credentials stay on the Worker."
3274
3462
  );
3275
3463
  let chosen;
3276
- if (mode === "local" && (p.values.connect || p.values.provider)) {
3464
+ if ((mode === "local" || client !== void 0) && (p.values.connect || p.values.provider)) {
3277
3465
  try {
3278
- chosen = await preferred();
3466
+ chosen = await preferred(void 0, client);
3279
3467
  } catch {
3280
3468
  }
3281
3469
  }
3282
- const activeProvider = chosen?.provider ?? settings.provider ?? "openai";
3283
- let credentialAvailable = false;
3470
+ const activeProvider = chosen?.provider ?? (clientProfile ? void 0 : settings.provider ?? "openai");
3471
+ let credentialAvailable;
3284
3472
  let providerKey;
3285
- try {
3286
- providerKey = await loadToken(
3287
- settings,
3288
- mode === "local" ? "provider" : "review",
3289
- activeProvider
3290
- );
3291
- credentialAvailable = true;
3292
- } catch {
3473
+ if (mode === "worker" || activeProvider) {
3474
+ credentialAvailable = false;
3475
+ try {
3476
+ providerKey = await loadToken(
3477
+ settings,
3478
+ mode === "local" ? "provider" : "review",
3479
+ activeProvider
3480
+ );
3481
+ credentialAvailable = true;
3482
+ } catch {
3483
+ }
3293
3484
  }
3294
3485
  const report = {
3295
3486
  configPath: settingsPath(),
3296
3487
  mode,
3297
3488
  provider: activeProvider,
3298
- ...mode === "local" ? {
3489
+ ...mode === "local" || client !== void 0 ? {
3299
3490
  profileResolution: !(p.values.connect || p.values.provider) ? "not_checked" : chosen ? "resolved" : "unavailable"
3300
3491
  } : {},
3301
3492
  keyConfigurationProvider: settings.provider ?? "openai",
3302
- ...mode === "local" && settings.secretStore === "env" ? { apiKeyEnv: providerEnvName(settings, activeProvider) } : {},
3493
+ ...mode === "local" && settings.secretStore === "env" && activeProvider ? { apiKeyEnv: providerEnvName(settings, activeProvider) } : {},
3303
3494
  ...mode === "local" ? {
3304
3495
  ledgerPath: join6(resolve5(localDirectory()), "ledger.sqlite"),
3305
3496
  budgetScope: "this local data directory only"
@@ -3307,12 +3498,14 @@ async function runCli(args) {
3307
3498
  endpointConfigured: !!settings.endpoint,
3308
3499
  secretStore: settings.secretStore,
3309
3500
  credentialAvailable,
3310
- defaultModel: settings.defaultModel,
3311
- defaultReasoning: settings.defaultReasoning,
3312
- defaultProfile: settings.defaultProfile
3501
+ ...client ? { client } : {},
3502
+ defaultModel: clientProfile ? void 0 : settings.defaultModel,
3503
+ defaultReasoning: clientProfile ? void 0 : settings.defaultReasoning,
3504
+ defaultProfile: clientProfile ?? settings.defaultProfile,
3505
+ clientProfiles: settings.clientProfiles
3313
3506
  };
3314
3507
  if (p.values.provider) {
3315
- chosen ??= await preferred();
3508
+ chosen ??= await preferred(void 0, client);
3316
3509
  report.providerDiagnostic = providerKey ? await providerDiagnostic(chosen, providerKey) : {
3317
3510
  provider: chosen.provider,
3318
3511
  model: chosen.model,
@@ -3321,6 +3514,8 @@ async function runCli(args) {
3321
3514
  report.providerDiagnosticScope = "Metadata reachability only; not generation permission, credits, rate limits, geo, structured-output support, or quality.";
3322
3515
  }
3323
3516
  if (p.values.connect) {
3517
+ if (mode === "local" && clientProfile && !chosen)
3518
+ throw new CliError("The configured client profile is unavailable.");
3324
3519
  if (mode === "worker" && !settings.endpoint || !credentialAvailable)
3325
3520
  throw new CliError(
3326
3521
  "Endpoint or credentials unavailable. Check your selected secret store."
@@ -3328,35 +3523,35 @@ async function runCli(args) {
3328
3523
  if (mode === "local") {
3329
3524
  const version = await packageVersion();
3330
3525
  report.localTools = await withLocal(async (runtime) => {
3331
- const server = await localMcpServer(runtime, settings);
3526
+ const server = await localMcpServer(runtime, settings, client);
3332
3527
  const { Client: Client2 } = await import("@modelcontextprotocol/client");
3333
3528
  const { InMemoryTransport } = await import("@modelcontextprotocol/server");
3334
3529
  const [host, local] = InMemoryTransport.createLinkedPair();
3335
- const client2 = new Client2({
3530
+ const mcpClient2 = new Client2({
3336
3531
  name: "rebut-local-doctor",
3337
3532
  version
3338
3533
  });
3339
3534
  try {
3340
- await Promise.all([client2.connect(host), server.connect(local)]);
3341
- return (await client2.listTools()).tools.map((t) => t.name);
3535
+ await Promise.all([mcpClient2.connect(host), server.connect(local)]);
3536
+ return (await mcpClient2.listTools()).tools.map((t) => t.name);
3342
3537
  } finally {
3343
- await client2.close();
3538
+ await mcpClient2.close();
3344
3539
  await server.close();
3345
3540
  }
3346
3541
  });
3347
3542
  output(report);
3348
3543
  return;
3349
3544
  }
3350
- const client = await connectRemote({
3545
+ const mcpClient = await connectRemote({
3351
3546
  endpoint: settings.endpoint,
3352
3547
  loadToken: () => loadToken(settings)
3353
3548
  });
3354
3549
  try {
3355
- report.remoteTools = (await client.listTools()).tools.map(
3550
+ report.remoteTools = (await mcpClient.listTools()).tools.map(
3356
3551
  (t) => t.name
3357
3552
  );
3358
3553
  } finally {
3359
- await client.close();
3554
+ await mcpClient.close();
3360
3555
  }
3361
3556
  }
3362
3557
  output(report);
@@ -3369,21 +3564,31 @@ async function runCli(args) {
3369
3564
  loadToken: () => loadToken(settings)
3370
3565
  };
3371
3566
  if (command === "mcp") {
3372
- if (rest.length) throw new CliError("Unexpected mcp arguments.");
3567
+ const parsed = options(rest, { client: { type: "string" } });
3568
+ const client = selectedClient(parsed.values.client);
3569
+ const clientProfile = client && settings.clientProfiles?.[client];
3373
3570
  if (mode === "local") {
3374
- await serveLocalStdio(settings);
3571
+ await serveLocalStdio(settings, client);
3375
3572
  return;
3376
3573
  }
3377
3574
  let preferredProfile;
3378
3575
  let reviewUnavailable = false;
3379
- if (settings.defaultModel || settings.defaultReasoning || settings.defaultProfile) {
3576
+ let clientProfileUnavailable = false;
3577
+ if (settings.defaultModel || settings.defaultReasoning || settings.defaultProfile || clientProfile) {
3380
3578
  try {
3381
- preferredProfile = await preferred();
3579
+ preferredProfile = await preferred(void 0, client);
3382
3580
  } catch {
3383
- reviewUnavailable = true;
3581
+ clientProfileUnavailable = clientProfile !== void 0;
3582
+ reviewUnavailable = !clientProfileUnavailable;
3384
3583
  }
3385
3584
  }
3386
- await serveStdio({ ...remote, preferredProfile, reviewUnavailable });
3585
+ await serveStdio({
3586
+ ...remote,
3587
+ client,
3588
+ preferredProfile,
3589
+ reviewUnavailable,
3590
+ clientProfileUnavailable
3591
+ });
3387
3592
  return;
3388
3593
  }
3389
3594
  if (command === "status" && rest.length === 1 && rest[0] === "--pending") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rebut-mcp",
3
- "version": "0.3.3",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "scripts": {