@vellumai/assistant 0.10.2-dev.202606242041.1026b57 → 0.10.2-dev.202606242135.63f618e

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/openapi.yaml CHANGED
@@ -8408,6 +8408,22 @@ paths:
8408
8408
  anyOf:
8409
8409
  - type: number
8410
8410
  - type: "null"
8411
+ apiErrorCode:
8412
+ anyOf:
8413
+ - type: string
8414
+ - type: "null"
8415
+ apiErrorType:
8416
+ anyOf:
8417
+ - type: string
8418
+ - type: "null"
8419
+ apiErrorParam:
8420
+ anyOf:
8421
+ - type: string
8422
+ - type: "null"
8423
+ requestId:
8424
+ anyOf:
8425
+ - type: string
8426
+ - type: "null"
8411
8427
  additionalProperties: false
8412
8428
  - type: "null"
8413
8429
  required:
@@ -15352,6 +15368,22 @@ paths:
15352
15368
  anyOf:
15353
15369
  - type: number
15354
15370
  - type: "null"
15371
+ apiErrorCode:
15372
+ anyOf:
15373
+ - type: string
15374
+ - type: "null"
15375
+ apiErrorType:
15376
+ anyOf:
15377
+ - type: string
15378
+ - type: "null"
15379
+ apiErrorParam:
15380
+ anyOf:
15381
+ - type: string
15382
+ - type: "null"
15383
+ requestId:
15384
+ anyOf:
15385
+ - type: string
15386
+ - type: "null"
15355
15387
  additionalProperties: false
15356
15388
  - type: "null"
15357
15389
  required:
@@ -17809,6 +17841,22 @@ paths:
17809
17841
  anyOf:
17810
17842
  - type: number
17811
17843
  - type: "null"
17844
+ apiErrorCode:
17845
+ anyOf:
17846
+ - type: string
17847
+ - type: "null"
17848
+ apiErrorType:
17849
+ anyOf:
17850
+ - type: string
17851
+ - type: "null"
17852
+ apiErrorParam:
17853
+ anyOf:
17854
+ - type: string
17855
+ - type: "null"
17856
+ requestId:
17857
+ anyOf:
17858
+ - type: string
17859
+ - type: "null"
17812
17860
  additionalProperties: false
17813
17861
  - type: "null"
17814
17862
  required:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.2-dev.202606242041.1026b57",
3
+ "version": "0.10.2-dev.202606242135.63f618e",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -182,6 +182,7 @@ describe("Invariant 2: no generic plaintext secret read API", () => {
182
182
  "daemon/handlers/config-slack-channel.ts", // Slack channel config credential management
183
183
  "providers/platform-proxy/context.ts", // managed proxy API key lookup for provider initialization
184
184
  "platform/client.ts", // platform client credential store fallback for standalone CLI auth
185
+ "mcp/mcp-header-store.ts", // MCP static auth header persistence (credential store CRUD + legacy migration)
185
186
  "mcp/mcp-oauth-provider.ts", // MCP OAuth token/client/discovery persistence
186
187
  "runtime/routes/integrations/slack/token.ts", // shared Slack token resolver (bot/user token lookup for CLI use routes)
187
188
  "mcp/client.ts", // MCP client cached-token lookup
@@ -25,18 +25,15 @@
25
25
  import { describe, expect, test } from "bun:test";
26
26
 
27
27
  import { buildProviderErrorResponsePayload } from "../memory/llm-request-log-store.js";
28
- import {
29
- AssistantError,
30
- ErrorCode,
31
- ProviderError,
32
- } from "../util/errors.js";
28
+ import { AssistantError, ErrorCode, ProviderError } from "../util/errors.js";
33
29
 
34
- function persisted(err: Error): { error: Record<string, unknown> } {
30
+ function persisted(err: Error): {
31
+ error: Record<string, unknown>;
32
+ rawResponse?: unknown;
33
+ } {
35
34
  // Round-trip through JSON to assert on the actual stored shape, not the
36
35
  // in-memory object reference.
37
- return JSON.parse(
38
- JSON.stringify(buildProviderErrorResponsePayload(err)),
39
- );
36
+ return JSON.parse(JSON.stringify(buildProviderErrorResponsePayload(err)));
40
37
  }
41
38
 
42
39
  describe("buildProviderErrorResponsePayload", () => {
@@ -60,6 +57,34 @@ describe("buildProviderErrorResponsePayload", () => {
60
57
  });
61
58
  });
62
59
 
60
+ test("ProviderError serializes upstream provider error metadata when present", () => {
61
+ const err = new ProviderError(
62
+ "OpenAI API error (401): Invalid API key provided",
63
+ "openai",
64
+ 401,
65
+ {
66
+ apiErrorCode: "invalid_api_key",
67
+ apiErrorType: "invalid_request_error",
68
+ apiErrorParam: "api_key",
69
+ requestId: "req_abc123",
70
+ },
71
+ );
72
+ const got = persisted(err);
73
+ expect(got).toEqual({
74
+ error: {
75
+ name: "ProviderError",
76
+ message: "OpenAI API error (401): Invalid API key provided",
77
+ code: ErrorCode.PROVIDER_ERROR,
78
+ provider: "openai",
79
+ statusCode: 401,
80
+ apiErrorCode: "invalid_api_key",
81
+ apiErrorType: "invalid_request_error",
82
+ apiErrorParam: "api_key",
83
+ requestId: "req_abc123",
84
+ },
85
+ });
86
+ });
87
+
63
88
  test("ProviderError without optional metadata omits statusCode + retryAfterMs", () => {
64
89
  const err = new ProviderError(
65
90
  "Gemini API error: surprise internal state",
@@ -127,6 +152,43 @@ describe("buildProviderErrorResponsePayload", () => {
127
152
  });
128
153
  });
129
154
 
155
+ test("captured JSON rawBody is attached as a parsed rawResponse sibling", () => {
156
+ // So the inspector's Raw tab can render the actual upstream provider JSON
157
+ // (like a successful row) instead of only the extracted error fields.
158
+ const err = new ProviderError(
159
+ "Together AI API error (400): Model 'MiniMax-M3' is not supported.",
160
+ "together",
161
+ 400,
162
+ {
163
+ apiErrorCode: "model_not_supported",
164
+ rawBody: JSON.stringify({
165
+ detail: "Model 'MiniMax-M3' is not supported.",
166
+ }),
167
+ },
168
+ );
169
+ const got = persisted(err);
170
+ expect(got.error.apiErrorCode).toBe("model_not_supported");
171
+ expect(got.rawResponse).toEqual({
172
+ detail: "Model 'MiniMax-M3' is not supported.",
173
+ });
174
+ });
175
+
176
+ test("non-JSON rawBody (HTML/text error page) is kept verbatim as a string", () => {
177
+ const err = new ProviderError("Bad gateway", "openai", 400, {
178
+ rawBody: "<html><body>upstream timeout</body></html>",
179
+ });
180
+ const got = persisted(err);
181
+ expect(got.rawResponse).toBe("<html><body>upstream timeout</body></html>");
182
+ });
183
+
184
+ test("no captured rawBody omits the rawResponse sibling entirely", () => {
185
+ const err = new ProviderError("rate limited", "anthropic", 429, {
186
+ retryAfterMs: 1500,
187
+ });
188
+ const got = persisted(err);
189
+ expect("rawResponse" in got).toBe(false);
190
+ });
191
+
130
192
  test("ProviderError with statusCode 0 is still recorded (not coerced to undefined)", () => {
131
193
  // Defensive: `if (err.statusCode !== undefined)` correctly admits 0.
132
194
  // A raw `if (err.statusCode)` would drop it, so the test guards against
@@ -58,6 +58,16 @@ let lastConstructorOptions: Record<string, unknown> | null = null;
58
58
  let shouldThrow: Error | null = null;
59
59
  const DEFAULT_SDK_TIMEOUT_MS = 1_860_000;
60
60
 
61
+ // Each provider installs a `fetch` wrapper to capture raw error bodies, so the
62
+ // constructor options carry a `fetch` function; assert the meaningful options
63
+ // via objectContaining and confirm `fetch` is wired.
64
+ function expectOpenAIConstructorOptions(
65
+ expected: Record<string, unknown>,
66
+ ): void {
67
+ expect(lastConstructorOptions).toEqual(expect.objectContaining(expected));
68
+ expect(typeof lastConstructorOptions?.fetch).toBe("function");
69
+ }
70
+
61
71
  function userMsg(text: string): Message {
62
72
  return { role: "user", content: [{ type: "text", text }] };
63
73
  }
@@ -309,7 +319,7 @@ describe("OpenAIProvider", () => {
309
319
  });
310
320
 
311
321
  expect(compatible.name).toBe("ollama");
312
- expect(lastConstructorOptions).toEqual({
322
+ expectOpenAIConstructorOptions({
313
323
  apiKey: "sk-local",
314
324
  baseURL: "http://127.0.0.1:11434/v1",
315
325
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -322,7 +332,7 @@ describe("OpenAIProvider", () => {
322
332
  delete process.env.OLLAMA_BASE_URL;
323
333
  const ollama = new OllamaProvider("llama3.2");
324
334
  expect(ollama.name).toBe("ollama");
325
- expect(lastConstructorOptions).toEqual({
335
+ expectOpenAIConstructorOptions({
326
336
  apiKey: "ollama",
327
337
  baseURL: "http://127.0.0.1:11434/v1",
328
338
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -342,7 +352,7 @@ describe("OpenAIProvider", () => {
342
352
  process.env.OLLAMA_BASE_URL = " ";
343
353
  const ollama = new OllamaProvider("llama3.2");
344
354
  expect(ollama.name).toBe("ollama");
345
- expect(lastConstructorOptions).toEqual({
355
+ expectOpenAIConstructorOptions({
346
356
  apiKey: "ollama",
347
357
  baseURL: "http://127.0.0.1:11434/v1",
348
358
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -1260,7 +1270,7 @@ describe("custom baseURL initialization", () => {
1260
1270
  });
1261
1271
 
1262
1272
  expect(managed.name).toBe("openai");
1263
- expect(lastConstructorOptions).toEqual({
1273
+ expectOpenAIConstructorOptions({
1264
1274
  apiKey: "ast-key-123",
1265
1275
  baseURL: "https://platform.example.com/v1/runtime-proxy/openai",
1266
1276
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -1270,7 +1280,7 @@ describe("custom baseURL initialization", () => {
1270
1280
  test("OpenAIProvider without baseURL calls provider directly", () => {
1271
1281
  new OpenAIProvider("sk-user-key", "gpt-4o");
1272
1282
 
1273
- expect(lastConstructorOptions).toEqual({
1283
+ expectOpenAIConstructorOptions({
1274
1284
  apiKey: "sk-user-key",
1275
1285
  baseURL: undefined,
1276
1286
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -1282,7 +1292,7 @@ describe("custom baseURL initialization", () => {
1282
1292
  streamTimeoutMs: 300_000,
1283
1293
  });
1284
1294
 
1285
- expect(lastConstructorOptions).toEqual({
1295
+ expectOpenAIConstructorOptions({
1286
1296
  apiKey: "sk-user-key",
1287
1297
  baseURL: undefined,
1288
1298
  timeout: 360_000,
@@ -1299,7 +1309,7 @@ describe("custom baseURL initialization", () => {
1299
1309
  );
1300
1310
 
1301
1311
  expect(managed.name).toBe("fireworks");
1302
- expect(lastConstructorOptions).toEqual({
1312
+ expectOpenAIConstructorOptions({
1303
1313
  apiKey: "ast-key-123",
1304
1314
  baseURL: "https://platform.example.com/v1/runtime-proxy/fireworks",
1305
1315
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -1312,7 +1322,7 @@ describe("custom baseURL initialization", () => {
1312
1322
  "accounts/fireworks/models/llama-v3p1-70b-instruct",
1313
1323
  );
1314
1324
 
1315
- expect(lastConstructorOptions).toEqual({
1325
+ expectOpenAIConstructorOptions({
1316
1326
  apiKey: "fw-user-key",
1317
1327
  baseURL: "https://api.fireworks.ai/inference/v1",
1318
1328
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -1325,7 +1335,7 @@ describe("custom baseURL initialization", () => {
1325
1335
  });
1326
1336
 
1327
1337
  expect(managed.name).toBe("openrouter");
1328
- expect(lastConstructorOptions).toEqual({
1338
+ expectOpenAIConstructorOptions({
1329
1339
  apiKey: "ast-key-123",
1330
1340
  baseURL: "https://platform.example.com/v1/runtime-proxy/openrouter",
1331
1341
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -1335,7 +1345,7 @@ describe("custom baseURL initialization", () => {
1335
1345
  test("OpenRouterProvider without custom baseURL uses default OpenRouter URL", () => {
1336
1346
  new OpenRouterProvider("or-user-key", "openai/gpt-4o");
1337
1347
 
1338
- expect(lastConstructorOptions).toEqual({
1348
+ expectOpenAIConstructorOptions({
1339
1349
  apiKey: "or-user-key",
1340
1350
  baseURL: "https://openrouter.ai/api/v1",
1341
1351
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -1348,7 +1358,7 @@ describe("custom baseURL initialization", () => {
1348
1358
  });
1349
1359
 
1350
1360
  expect(managed.name).toBe("minimax");
1351
- expect(lastConstructorOptions).toEqual({
1361
+ expectOpenAIConstructorOptions({
1352
1362
  apiKey: "ast-key-123",
1353
1363
  baseURL: "https://platform.example.com/v1/runtime-proxy/minimax",
1354
1364
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -1358,7 +1368,7 @@ describe("custom baseURL initialization", () => {
1358
1368
  test("MinimaxProvider without custom baseURL uses default MiniMax URL", () => {
1359
1369
  new MinimaxProvider("mm-user-key", "MiniMax-M2.7");
1360
1370
 
1361
- expect(lastConstructorOptions).toEqual({
1371
+ expectOpenAIConstructorOptions({
1362
1372
  apiKey: "mm-user-key",
1363
1373
  baseURL: "https://api.minimax.io/v1",
1364
1374
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -24,6 +24,16 @@ let lastConstructorOptions: Record<string, unknown> | null = null;
24
24
  let shouldThrow: Error | null = null;
25
25
  const DEFAULT_SDK_TIMEOUT_MS = 1_860_000;
26
26
 
27
+ // Each provider installs a `fetch` wrapper to capture raw error bodies, so the
28
+ // constructor options carry a `fetch` function; assert the meaningful options
29
+ // via objectContaining and confirm `fetch` is wired.
30
+ function expectOpenAIConstructorOptions(
31
+ expected: Record<string, unknown>,
32
+ ): void {
33
+ expect(lastConstructorOptions).toEqual(expect.objectContaining(expected));
34
+ expect(typeof lastConstructorOptions?.fetch).toBe("function");
35
+ }
36
+
27
37
  // Simulate OpenAI.APIError
28
38
  class FakeAPIError extends Error {
29
39
  status: number;
@@ -218,7 +228,7 @@ describe("OpenAIResponsesProvider", () => {
218
228
  providerLabel: "Managed OpenAI",
219
229
  });
220
230
 
221
- expect(lastConstructorOptions).toEqual({
231
+ expectOpenAIConstructorOptions({
222
232
  apiKey: "sk-custom",
223
233
  baseURL: "https://proxy.example.com/v1",
224
234
  timeout: DEFAULT_SDK_TIMEOUT_MS,
@@ -230,7 +240,7 @@ describe("OpenAIResponsesProvider", () => {
230
240
  streamTimeoutMs: 300_000,
231
241
  });
232
242
 
233
- expect(lastConstructorOptions).toEqual({
243
+ expectOpenAIConstructorOptions({
234
244
  apiKey: "sk-custom",
235
245
  baseURL: undefined,
236
246
  timeout: 360_000,
@@ -837,9 +837,10 @@ describe("RetryProvider — streaming response handling", () => {
837
837
 
838
838
  test("does NOT retry OpenAI/Gemini-shaped 'Request was aborted' (no inner-timeout rewrite at those catch-sites)", async () => {
839
839
  // The OpenAI chat-completions, OpenAI responses, and Gemini catch-sites
840
- // format their errors as `"<Provider> API error (undefined): Request
841
- // was aborted."` (note the `(undefined)` parenthetical that the
842
- // Anthropic catch-site intentionally omits) and — unlike the Anthropic
840
+ // format their errors as `"<Provider> API error (<status>): Request
841
+ // was aborted."` (the OpenAI catch-sites render a missing status as
842
+ // `(unknown status)`; the Anthropic catch-site intentionally omits the
843
+ // parenthetical) and — unlike the Anthropic
843
844
  // catch-site — they do NOT rewrite their inner-streamTimeoutMs
844
845
  // deadline failures. A provider-agnostic transport-abort predicate
845
846
  // would burn three retries on what is by construction a deterministic
@@ -848,7 +849,7 @@ describe("RetryProvider — streaming response handling", () => {
848
849
  // wasted retry budget for non-Anthropic providers until their
849
850
  // catch-sites grow the same `innerTimeoutFired` distinction.
850
851
  const openaiAbortError = new ProviderError(
851
- "OpenAI API error (undefined): Request was aborted.",
852
+ "OpenAI API error (unknown status): Request was aborted.",
852
853
  "openai",
853
854
  undefined,
854
855
  );
@@ -87,6 +87,10 @@ export const LLMCallErrorSchema = z.object({
87
87
  provider: z.string().nullish(),
88
88
  statusCode: z.number().nullish(),
89
89
  retryAfterMs: z.number().nullish(),
90
+ apiErrorCode: z.string().nullish(),
91
+ apiErrorType: z.string().nullish(),
92
+ apiErrorParam: z.string().nullish(),
93
+ requestId: z.string().nullish(),
90
94
  });
91
95
 
92
96
  export type LLMCallError = z.infer<typeof LLMCallErrorSchema>;
@@ -7,6 +7,7 @@
7
7
 
8
8
  import { getConfig, invalidateConfigCache } from "../config/loader.js";
9
9
  import { getMcpServerManager } from "../mcp/manager.js";
10
+ import { migrateLegacyMcpHeaders } from "../mcp/mcp-header-store.js";
10
11
  import { createMcpToolsFromServer } from "../tools/mcp/mcp-tool-factory.js";
11
12
  import { registerMcpTools, unregisterAllMcpTools } from "../tools/registry.js";
12
13
  import { getLogger } from "../util/logger.js";
@@ -55,6 +56,15 @@ async function doReload(): Promise<McpReloadResult> {
55
56
  try {
56
57
  const manager = getMcpServerManager();
57
58
 
59
+ // 0. Migrate any legacy plaintext headers from config.json into
60
+ // the credential store before loading config for server startup.
61
+ // No-ops when no legacy headers remain; errors are logged, not thrown.
62
+ try {
63
+ await migrateLegacyMcpHeaders();
64
+ } catch (err) {
65
+ log.warn({ err }, "Legacy MCP header migration failed — continuing");
66
+ }
67
+
58
68
  // 1. Validate new config before tearing down existing servers.
59
69
  // If the config is broken we abort early, preserving the current
60
70
  // working MCP setup instead of leaving zero servers.
@@ -68,6 +68,7 @@ mock.module("../../daemon/mcp-reload-service.js", () => ({
68
68
 
69
69
  mock.module("../../config/env-registry.js", () => ({
70
70
  getIsContainerized: () => false,
71
+ getWorkspaceDirOverride: () => undefined,
71
72
  }));
72
73
 
73
74
  mock.module("../../util/logger.js", () => ({
package/src/mcp/client.ts CHANGED
@@ -8,6 +8,7 @@ import { getIsPlatform } from "../config/env-registry.js";
8
8
  import type { McpTransport } from "../config/schemas/mcp.js";
9
9
  import { getSecureKeyAsync } from "../security/secure-keys.js";
10
10
  import { getLogger } from "../util/logger.js";
11
+ import { getMcpHeaders } from "./mcp-header-store.js";
11
12
  import { McpOAuthProvider } from "./mcp-oauth-provider.js";
12
13
 
13
14
  const log = getLogger("mcp-client");
@@ -108,8 +109,21 @@ export class McpClient {
108
109
  }
109
110
  }
110
111
 
112
+ // Resolve static auth headers from credential store, falling back to
113
+ // any legacy headers in the transport config for backward compatibility.
114
+ let effectiveConfig = transportConfig;
115
+ if (isHttpTransport) {
116
+ const storedHeaders = await getMcpHeaders(this.serverId);
117
+ if (storedHeaders) {
118
+ effectiveConfig = {
119
+ ...transportConfig,
120
+ headers: { ...transportConfig.headers, ...storedHeaders },
121
+ } as McpTransport;
122
+ }
123
+ }
124
+
111
125
  log.info({ serverId: this.serverId }, "Connecting to MCP server");
112
- this.transport = this.createTransport(transportConfig);
126
+ this.transport = this.createTransport(effectiveConfig);
113
127
 
114
128
  try {
115
129
  await Promise.race([
@@ -21,6 +21,7 @@ import {
21
21
  setMcpAuthError,
22
22
  setMcpAuthPending,
23
23
  } from "./mcp-auth-state.js";
24
+ import { getMcpHeaders } from "./mcp-header-store.js";
24
25
  import {
25
26
  type McpOAuthCallbackTransport,
26
27
  McpOAuthProvider,
@@ -80,6 +81,10 @@ export async function orchestrateMcpOAuthConnect(args: {
80
81
  // Register the pending callback in the daemon heap
81
82
  const { codePromise } = await provider.startCallbackServer();
82
83
 
84
+ // Resolve effective headers: credential store takes precedence, then config
85
+ const storedHeaders = await getMcpHeaders(serverId);
86
+ const effectiveHeaders = storedHeaders ?? transport.headers;
87
+
83
88
  // Build the MCP transport and client
84
89
  const serverUrl = new URL(transport.url);
85
90
  const TransportClass =
@@ -88,7 +93,7 @@ export async function orchestrateMcpOAuthConnect(args: {
88
93
  : StreamableHTTPClientTransport;
89
94
  const mcpTransport = new TransportClass(serverUrl, {
90
95
  authProvider: provider,
91
- requestInit: transport.headers ? { headers: transport.headers } : undefined,
96
+ requestInit: effectiveHeaders ? { headers: effectiveHeaders } : undefined,
92
97
  });
93
98
  const client = new Client({ name: "vellum-assistant", version: "1.0.0" });
94
99
 
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Credential-store-backed persistence for MCP server static auth headers.
3
+ *
4
+ * Follows the same pattern as mcp-oauth-provider.ts: headers are stored in
5
+ * the secure credential store (CES or encrypted file fallback) rather than
6
+ * in plaintext config.json, keeping secrets out of workspace config files.
7
+ *
8
+ * Key format: mcp:{serverId}:headers — stores JSON-serialized Record<string, string>.
9
+ */
10
+
11
+ import { loadRawConfig, saveRawConfig } from "../config/loader.js";
12
+ import {
13
+ deleteSecureKeyAsync,
14
+ getSecureKeyAsync,
15
+ setSecureKeyAsync,
16
+ } from "../security/secure-keys.js";
17
+ import { getLogger } from "../util/logger.js";
18
+
19
+ const log = getLogger("mcp-header-store");
20
+
21
+ function headersKey(serverId: string): string {
22
+ return `mcp:${serverId}:headers`;
23
+ }
24
+
25
+ /**
26
+ * Retrieve stored static auth headers for an MCP server.
27
+ * Returns undefined if none are stored or if the credential store is unreachable.
28
+ */
29
+ export async function getMcpHeaders(
30
+ serverId: string,
31
+ ): Promise<Record<string, string> | undefined> {
32
+ const raw = await getSecureKeyAsync(headersKey(serverId));
33
+ if (!raw) return undefined;
34
+ try {
35
+ return JSON.parse(raw) as Record<string, string>;
36
+ } catch {
37
+ log.warn({ serverId }, "Failed to parse stored MCP headers");
38
+ return undefined;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Store static auth headers for an MCP server in the credential store.
44
+ */
45
+ export async function setMcpHeaders(
46
+ serverId: string,
47
+ headers: Record<string, string>,
48
+ ): Promise<boolean> {
49
+ const ok = await setSecureKeyAsync(
50
+ headersKey(serverId),
51
+ JSON.stringify(headers),
52
+ );
53
+ if (!ok) {
54
+ log.warn({ serverId }, "Failed to persist MCP headers to secure storage");
55
+ return false;
56
+ }
57
+ log.info({ serverId }, "MCP static auth headers saved to credential store");
58
+ return true;
59
+ }
60
+
61
+ /**
62
+ * Delete stored static auth headers for an MCP server.
63
+ */
64
+ export async function deleteMcpHeaders(serverId: string): Promise<boolean> {
65
+ const result = await deleteSecureKeyAsync(headersKey(serverId));
66
+ if (result === "error") {
67
+ log.warn({ serverId }, "Failed to delete MCP headers from secure storage");
68
+ return false;
69
+ }
70
+ return true;
71
+ }
72
+
73
+ /**
74
+ * One-time lazy migration: move any plaintext headers from config.json
75
+ * transport entries into the credential store and strip them from config.
76
+ * Safe to call on every MCP reload — no-ops when no legacy headers remain.
77
+ */
78
+ export async function migrateLegacyMcpHeaders(): Promise<void> {
79
+ const raw = loadRawConfig();
80
+ const mcpConfig = raw.mcp as
81
+ | { servers?: Record<string, Record<string, unknown>> }
82
+ | undefined;
83
+ const servers = mcpConfig?.servers;
84
+ if (!servers) {
85
+ return;
86
+ }
87
+
88
+ let configDirty = false;
89
+ for (const [id, server] of Object.entries(servers)) {
90
+ const transport = server?.transport as Record<string, unknown> | undefined;
91
+ if (
92
+ !transport ||
93
+ (transport.type !== "sse" && transport.type !== "streamable-http")
94
+ ) {
95
+ continue;
96
+ }
97
+ const legacyHeaders = transport.headers as
98
+ | Record<string, string>
99
+ | undefined;
100
+ if (!legacyHeaders || Object.keys(legacyHeaders).length === 0) {
101
+ continue;
102
+ }
103
+
104
+ // Only migrate if credential store doesn't already have headers for
105
+ // this server (idempotent — safe to re-run after partial failure).
106
+ const existing = await getMcpHeaders(id);
107
+ if (existing) {
108
+ // Credential store already has headers; just strip the config copy.
109
+ delete transport.headers;
110
+ configDirty = true;
111
+ continue;
112
+ }
113
+
114
+ const ok = await setMcpHeaders(id, legacyHeaders);
115
+ if (ok) {
116
+ delete transport.headers;
117
+ configDirty = true;
118
+ log.info(
119
+ { serverId: id },
120
+ "Migrated legacy MCP headers to credential store",
121
+ );
122
+ } else {
123
+ log.warn(
124
+ { serverId: id },
125
+ "Skipping legacy header migration — credential store write failed; will retry on next reload",
126
+ );
127
+ }
128
+ }
129
+
130
+ if (configDirty) {
131
+ saveRawConfig(raw);
132
+ log.info("Config updated: legacy MCP headers removed after migration");
133
+ }
134
+ }
@@ -94,14 +94,21 @@ export type CompactionAgentLogRow = LogMetaRow & {
94
94
  * can either stringify it directly (daemon-path `recordRequestLog`) or
95
95
  * store it on a pending-log queue that stringifies later (wake-path
96
96
  * `PendingLog.rawResponse`), without double-encoding.
97
+ *
98
+ * When the provider captured the verbatim upstream body, it is attached as a
99
+ * top-level `rawResponse` sibling so the inspector's Raw tab can show the
100
+ * actual provider payload (parsed JSON, or the raw string for non-JSON error
101
+ * pages) — matching the success path, where Raw shows the real provider JSON.
97
102
  */
98
103
  export function buildProviderErrorResponsePayload(err: Error): {
99
104
  error: Record<string, unknown>;
105
+ rawResponse?: unknown;
100
106
  } {
101
107
  const payload: Record<string, unknown> = {
102
108
  name: err.name,
103
109
  message: err.message,
104
110
  };
111
+ let rawResponse: unknown;
105
112
  if (err instanceof ProviderError) {
106
113
  payload.code = err.code;
107
114
  payload.provider = err.provider;
@@ -111,10 +118,28 @@ export function buildProviderErrorResponsePayload(err: Error): {
111
118
  if (err.retryAfterMs !== undefined) {
112
119
  payload.retryAfterMs = err.retryAfterMs;
113
120
  }
121
+ if (err.apiErrorCode !== undefined) payload.apiErrorCode = err.apiErrorCode;
122
+ if (err.apiErrorType !== undefined) payload.apiErrorType = err.apiErrorType;
123
+ if (err.apiErrorParam !== undefined)
124
+ payload.apiErrorParam = err.apiErrorParam;
125
+ if (err.requestId !== undefined) payload.requestId = err.requestId;
126
+ if (err.rawBody !== undefined) rawResponse = parseRawBody(err.rawBody);
114
127
  } else if (err instanceof AssistantError) {
115
128
  payload.code = err.code;
116
129
  }
117
- return { error: payload };
130
+ return rawResponse !== undefined
131
+ ? { error: payload, rawResponse }
132
+ : { error: payload };
133
+ }
134
+
135
+ /** Parse a captured upstream body as JSON, falling back to the raw string for
136
+ * non-JSON error pages (HTML, plain text) or a truncated/invalid prefix. */
137
+ function parseRawBody(rawBody: string): unknown {
138
+ try {
139
+ return JSON.parse(rawBody);
140
+ } catch {
141
+ return rawBody;
142
+ }
118
143
  }
119
144
 
120
145
  export function recordRequestLog(