@saturn-universe/protocol 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,342 @@
1
+ import { z } from 'zod';
2
+ import { contextExtensionRefPattern, MAX_RUN_PROGRESS_PAGE_SIZE, MAX_SESSION_EXPORT_LIMIT, MAX_SESSION_HISTORY_PAGE_SIZE, MAX_SESSION_LIST_LIMIT, RuntimeError, validatePlannerConfig, validateTeamConfig, } from '@saturn-universe/core';
3
+ import { encodeIpcFrame, maxFrameBytes } from './ipc-framing.js';
4
+ import { eventPositionSchema as position } from './wire-shapes.js';
5
+ export { encodeIpcFrame, IpcFrameReader, maxFrameBytes, maxReplyBodyBytes } from './ipc-framing.js';
6
+ export { parseSessionExportResult, parseSessionListResult, parseSessionSummaryResult, } from './session-results.js';
7
+ export { parseRunProgressResult } from './run-event-results.js';
8
+ export { parseHostStatusResult } from './host-status.js';
9
+ export { validHostCommandResult } from './host-results.js';
10
+ export * from './endpoint.js';
11
+ export { contextExtensionRefPattern, DEFAULT_MODE_REF, DEFAULT_SESSION_EXPORT_LIMIT, DEFAULT_SESSION_LIST_LIMIT, isEventPosition, isTerminalRunEventType, isTerminalRunStatus, matchesModeSelector, MAX_RUN_PROGRESS_PAGE_SIZE, MAX_SESSION_HISTORY_PAGE_SIZE, mergeAgentContextMetrics, modeSelectorPattern, resolveModeSelector, validatePlannerConfig, } from '@saturn-universe/core';
12
+ const id = z.string().min(1).max(200);
13
+ const brandedId = () => id.transform((value) => value);
14
+ const positive = z.number().int().positive().safe();
15
+ const nonnegative = z.number().int().nonnegative().safe();
16
+ const schema = z.record(z.string(), z.json());
17
+ const model = z.strictObject({ providerId: id, modelId: id, profileRef: id });
18
+ const responses = z.strictObject({
19
+ storage: z.literal('local_stateless'),
20
+ reasoning: z
21
+ .strictObject({
22
+ effort: z.string().optional(),
23
+ summary: z.string().optional(),
24
+ context: z.string().optional(),
25
+ })
26
+ .optional(),
27
+ parallelToolCalls: z.boolean().optional(),
28
+ metadata: z.record(z.string(), z.string()).optional(),
29
+ extensionOptions: schema.optional(),
30
+ });
31
+ const team = z.strictObject({
32
+ rootId: id.optional(),
33
+ members: z.array(z.strictObject({
34
+ id,
35
+ parent: id,
36
+ task: z.string(),
37
+ sandboxProfile: z.enum(['default', 'readonly', 'build']).optional(),
38
+ workSubpath: z.string().optional(),
39
+ })),
40
+ concurrency: positive.optional(),
41
+ });
42
+ const teamHint = z.strictObject({
43
+ force: z.boolean().optional(),
44
+ concurrency: positive.optional(),
45
+ maxMembers: positive.optional(),
46
+ });
47
+ const searchTrigger = z.enum(['planning_phase', 'consecutive_failures', 'stagnation', 'model_fork']);
48
+ const search = z.strictObject({
49
+ mode: z.enum(['off', 'selective']),
50
+ triggers: z.array(searchTrigger).optional(),
51
+ branchFactor: positive.optional(),
52
+ maxRollouts: positive.optional(),
53
+ maxDepth: positive.optional(),
54
+ concurrency: positive.optional(),
55
+ maxBudgetRatio: z.number().gt(0).lte(1).optional(),
56
+ maxBranchSteps: positive.optional(),
57
+ isolation: z.enum(['readonly', 'isolated']).optional(),
58
+ maxCopyBytes: positive.optional(),
59
+ });
60
+ const planner = z.strictObject({
61
+ mode: z.enum(['auto', 'force_team']),
62
+ maxMembers: positive.optional(),
63
+ concurrency: positive.optional(),
64
+ search: search.optional(),
65
+ });
66
+ const continuation = z.strictObject({
67
+ enabled: z.boolean().optional(),
68
+ maxTurns: z.number().int().nonnegative().safe().optional(),
69
+ });
70
+ const config = z.strictObject({
71
+ modeRef: id,
72
+ model: model.optional(),
73
+ policyVersion: id,
74
+ toolSetVersion: id,
75
+ streamText: z.boolean().optional(),
76
+ workerReasoningEffort: id.optional(),
77
+ disabledSkills: z.array(z.string().trim().min(1).max(128)).max(64).optional(),
78
+ limits: z.strictObject({
79
+ maxModelAttempts: nonnegative,
80
+ maxToolCalls: nonnegative,
81
+ maxSteps: nonnegative,
82
+ maxTotalTokens: nonnegative,
83
+ subagentMaxModelAttempts: nonnegative.optional(),
84
+ wallTimeMs: positive.optional(),
85
+ subagentWallTimeMs: positive.optional(),
86
+ modelTimeoutMs: positive,
87
+ streamIdleTimeoutMs: positive.optional(),
88
+ requestTotalTimeoutMs: positive.optional(),
89
+ toolTimeoutMs: positive,
90
+ shellTimeoutMs: positive.optional(),
91
+ maxParallelTools: positive,
92
+ }),
93
+ retry: z.strictObject({
94
+ modelMaxAttemptsPerCall: positive,
95
+ toolMaxAttemptsPerCall: positive,
96
+ baseDelayMs: positive,
97
+ maxDelayMs: positive,
98
+ }),
99
+ responses,
100
+ team: team.optional(),
101
+ teamMaxDepth: positive.optional(),
102
+ agentDepth: nonnegative.optional(),
103
+ teamAsyncCoordinator: z.boolean().optional(),
104
+ coordinatorPollIntervalMs: nonnegative.optional(),
105
+ workerSoftCheckpointMs: nonnegative.optional(),
106
+ teamMaxActiveDepth1: positive.optional(),
107
+ teamMaxConcurrency: positive.optional(),
108
+ teamHint: teamHint.optional(),
109
+ planner: planner.optional(),
110
+ continuation: continuation.optional(),
111
+ search: search.optional(),
112
+ });
113
+ const artifact = z
114
+ .strictObject({
115
+ artifactId: z.string().regex(/^sha256:[a-f0-9]{64}$/),
116
+ sha256: z.string().regex(/^[a-f0-9]{64}$/),
117
+ mediaType: id.regex(/^\S+$/),
118
+ byteLength: z.number().int().nonnegative().safe(),
119
+ })
120
+ .refine((value) => value.artifactId === `sha256:${value.sha256}`);
121
+ const content = z.array(z.discriminatedUnion('type', [
122
+ z.strictObject({ type: z.literal('text'), text: z.string() }),
123
+ z.strictObject({ type: z.literal('image'), artifact, alt: z.string().optional() }),
124
+ z.strictObject({ type: z.literal('file'), artifact, name: id }),
125
+ ]));
126
+ const failure = z.strictObject({ code: id, message: z.string(), retryable: z.boolean() });
127
+ const toolResult = z.strictObject({
128
+ toolCallId: brandedId(),
129
+ effect: z.enum(['none', 'applied', 'unknown']),
130
+ evidenceRef: z.string().optional(),
131
+ outcome: z.discriminatedUnion('status', [
132
+ z.strictObject({ status: z.literal('success'), content, data: z.json().optional() }),
133
+ z.strictObject({
134
+ status: z.enum(['error', 'denied', 'cancelled']),
135
+ error: failure,
136
+ data: z.json().optional(),
137
+ }),
138
+ ]),
139
+ });
140
+ export function parseReconciliationToolResult(value) {
141
+ const result = toolResult.safeParse(value);
142
+ return result.success ? result.data : undefined;
143
+ }
144
+ const decision = z.discriminatedUnion('kind', [
145
+ z.strictObject({ kind: z.literal('completed'), result: toolResult, evidenceRef: id }),
146
+ z.strictObject({ kind: z.literal('not_applied'), evidenceRef: id }),
147
+ z.strictObject({ kind: z.literal('abandon_unknown'), acceptedBy: id, reason: z.string() }),
148
+ ]);
149
+ const commandSchema = z.discriminatedUnion('type', [
150
+ z.strictObject({
151
+ type: z.literal('surface.compact'),
152
+ runId: brandedId(),
153
+ throughTurnId: brandedId().optional(),
154
+ summary: z.string().trim().min(1).max(4096).optional(),
155
+ }),
156
+ z.strictObject({ type: z.literal('session.usage'), sessionId: brandedId() }),
157
+ z.strictObject({
158
+ type: z.literal('session.list'),
159
+ workspaceId: brandedId().optional(),
160
+ limit: z.number().int().min(1).max(MAX_SESSION_LIST_LIMIT).optional(),
161
+ }),
162
+ z.strictObject({
163
+ type: z.literal('session.export'),
164
+ sessionId: brandedId(),
165
+ after: position.optional(),
166
+ through: position.optional(),
167
+ limit: z.number().int().min(1).max(MAX_SESSION_EXPORT_LIMIT).optional(),
168
+ }),
169
+ z.strictObject({
170
+ type: z.literal('run.progress'),
171
+ runId: brandedId(),
172
+ after: position,
173
+ limit: z.number().int().min(1).max(MAX_RUN_PROGRESS_PAGE_SIZE),
174
+ interactive: z.boolean().optional(),
175
+ }),
176
+ z.strictObject({ type: z.literal('workspace.create'), rootUri: z.string().min(1) }),
177
+ z.strictObject({
178
+ type: z.literal('session.create'),
179
+ workspaceId: brandedId(),
180
+ title: z.string().min(1).max(1000),
181
+ }),
182
+ z.strictObject({ type: z.literal('workspace.query') }),
183
+ z.strictObject({ type: z.literal('session.query'), sessionId: brandedId() }),
184
+ z.strictObject({
185
+ type: z.literal('session.btw'),
186
+ sessionId: brandedId(),
187
+ agentSessionId: brandedId().optional(),
188
+ question: z.string().trim().min(1),
189
+ }),
190
+ z.strictObject({
191
+ type: z.literal('session.history'),
192
+ sessionId: brandedId(),
193
+ agentSessionId: brandedId().optional(),
194
+ through: position.optional(),
195
+ before: position.optional(),
196
+ limit: z.number().int().min(1).max(MAX_SESSION_HISTORY_PAGE_SIZE),
197
+ }),
198
+ z.strictObject({
199
+ type: z.literal('session.history.message'),
200
+ sessionId: brandedId(),
201
+ agentSessionId: brandedId().optional(),
202
+ position,
203
+ offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
204
+ }),
205
+ z.strictObject({ type: z.literal('run.model'), runId: brandedId() }),
206
+ z.strictObject({ type: z.literal('run.timeline'), runId: brandedId(), after: position }),
207
+ z.strictObject({ type: z.literal('run.query'), runId: brandedId() }),
208
+ z.strictObject({ type: z.literal('team.query'), runId: brandedId() }),
209
+ z.strictObject({ type: z.literal('team.inbox'), runId: brandedId(), memberId: id.optional() }),
210
+ z.strictObject({ type: z.literal('surface.query'), agentSessionId: brandedId() }),
211
+ z.strictObject({ type: z.literal('context.query'), runId: brandedId() }),
212
+ z.strictObject({ type: z.literal('host.status') }),
213
+ z.strictObject({ type: z.literal('host.shutdown') }),
214
+ z.strictObject({
215
+ type: z.literal('run.submit'),
216
+ input: z.strictObject({
217
+ workspaceId: brandedId(),
218
+ sessionId: brandedId(),
219
+ content: content.min(1),
220
+ config: config.partial().optional(),
221
+ model: model.optional(),
222
+ profile: id.optional(),
223
+ taskProfile: id.optional(),
224
+ skillRefs: z.array(z.string().regex(contextExtensionRefPattern)).max(16).optional(),
225
+ workingDirectoryUri: z.string().optional(),
226
+ planner: planner.optional(),
227
+ teamHint: teamHint.optional(),
228
+ teamPreset: id.optional(),
229
+ permissionMode: z.enum(['strict', 'default', 'full']).optional(),
230
+ }),
231
+ }),
232
+ z.strictObject({ type: z.literal('run.cancel'), runId: brandedId(), reason: z.string() }),
233
+ z.strictObject({
234
+ type: z.literal('run.steer'),
235
+ runId: brandedId(),
236
+ agentSessionId: brandedId().optional(),
237
+ content: z.string().trim().min(1),
238
+ }),
239
+ z.strictObject({ type: z.literal('run.resume'), runId: brandedId() }),
240
+ z.strictObject({
241
+ type: z.literal('tool.approval.resolve'),
242
+ resume: z.boolean().optional(),
243
+ decision: z.strictObject({
244
+ approvalId: brandedId(),
245
+ toolCallId: brandedId(),
246
+ approved: z.boolean(),
247
+ decidedBy: id,
248
+ decidedAt: z.string().datetime(),
249
+ reason: z.string(),
250
+ }),
251
+ }),
252
+ z.strictObject({ type: z.literal('tool.reconcile'), toolCallId: brandedId(), decision }),
253
+ ]);
254
+ const requestSchema = z.strictObject({
255
+ protocolVersion: z.literal(1),
256
+ requestId: id,
257
+ commandId: brandedId(),
258
+ command: commandSchema,
259
+ });
260
+ export function parseTeamConfig(value) {
261
+ const decoded = team.safeParse(value);
262
+ if (!decoded.success)
263
+ throw new RuntimeError('INVALID_TEAM_CONFIG', 'Invalid team configuration shape');
264
+ const { rootId, members, concurrency } = decoded.data;
265
+ const config = {
266
+ ...(rootId === undefined ? {} : { rootId }),
267
+ members,
268
+ ...(concurrency === undefined ? {} : { concurrency }),
269
+ };
270
+ validateTeamConfig(config);
271
+ return config;
272
+ }
273
+ export function parsePlannerConfig(value) {
274
+ const decoded = planner.safeParse(value);
275
+ if (!decoded.success)
276
+ throw new RuntimeError('INVALID_TEAM_CONFIG', 'Invalid planner configuration shape');
277
+ const { mode, maxMembers, concurrency, search: rawSearch } = decoded.data;
278
+ const normalizedSearch = rawSearch
279
+ ? {
280
+ mode: rawSearch.mode,
281
+ ...(rawSearch.triggers === undefined ? {} : { triggers: rawSearch.triggers }),
282
+ ...(rawSearch.branchFactor === undefined ? {} : { branchFactor: rawSearch.branchFactor }),
283
+ ...(rawSearch.maxRollouts === undefined ? {} : { maxRollouts: rawSearch.maxRollouts }),
284
+ ...(rawSearch.maxDepth === undefined ? {} : { maxDepth: rawSearch.maxDepth }),
285
+ ...(rawSearch.concurrency === undefined ? {} : { concurrency: rawSearch.concurrency }),
286
+ ...(rawSearch.maxBudgetRatio === undefined ? {} : { maxBudgetRatio: rawSearch.maxBudgetRatio }),
287
+ ...(rawSearch.maxBranchSteps === undefined ? {} : { maxBranchSteps: rawSearch.maxBranchSteps }),
288
+ ...(rawSearch.isolation === undefined ? {} : { isolation: rawSearch.isolation }),
289
+ ...(rawSearch.maxCopyBytes === undefined ? {} : { maxCopyBytes: rawSearch.maxCopyBytes }),
290
+ }
291
+ : undefined;
292
+ const config = {
293
+ mode,
294
+ ...(maxMembers === undefined ? {} : { maxMembers }),
295
+ ...(concurrency === undefined ? {} : { concurrency }),
296
+ ...(normalizedSearch === undefined ? {} : { search: normalizedSearch }),
297
+ };
298
+ validatePlannerConfig(config);
299
+ return config;
300
+ }
301
+ export function decodeCommand(text) {
302
+ if (new TextEncoder().encode(text).byteLength > maxFrameBytes)
303
+ throw new RuntimeError('INVALID_COMMAND', 'frame exceeds 8 MiB');
304
+ let value;
305
+ try {
306
+ value = JSON.parse(text);
307
+ }
308
+ catch {
309
+ throw new RuntimeError('INVALID_COMMAND', 'invalid JSON');
310
+ }
311
+ const decoded = requestSchema.safeParse(value);
312
+ if (!decoded.success)
313
+ throw new RuntimeError('INVALID_COMMAND', 'invalid protocol version or command');
314
+ // JSON cannot contain undefined; Zod optional output types include it explicitly.
315
+ // ProtocolSchemaMatchesCore checks equality of the normalized wire shapes.
316
+ return decoded.data;
317
+ }
318
+ export function encodeReply(reply) {
319
+ return encodeIpcFrame(reply);
320
+ }
321
+ const replySchema = z.discriminatedUnion('ok', [
322
+ z.strictObject({ requestId: id, ok: z.literal(true), result: z.json() }),
323
+ z.strictObject({ requestId: id, ok: z.literal(false), error: failure }),
324
+ ]);
325
+ export function decodeReply(text) {
326
+ let value;
327
+ try {
328
+ value = JSON.parse(text);
329
+ }
330
+ catch {
331
+ throw new RuntimeError('INVALID_REPLY', 'invalid Host reply');
332
+ }
333
+ const decoded = replySchema.safeParse(value);
334
+ if (!decoded.success)
335
+ throw new RuntimeError('INVALID_REPLY', 'invalid Host reply');
336
+ return decoded.data;
337
+ }
338
+ export * from './provider-credentials.js';
339
+ export * from './skills.js';
340
+ export * from './mcp-config.js';
341
+ export { redactExportValue } from './redaction.js';
342
+ export { geminiModelPath, lookupModelMetadata, normalizeProviderBaseUrl, normalizeProviderProtocol, providerCredentialKey, providerIdPattern, providerPresets, providerProtocols, } from '@saturn-universe/core';
@@ -0,0 +1,10 @@
1
+ export declare const maxFrameBytes: number;
2
+ export declare const maxReplyBodyBytes: number;
3
+ export declare function encodeIpcFrame(value: unknown): string;
4
+ export declare class IpcFrameReader {
5
+ private readonly maxBodyBytes;
6
+ private buffer;
7
+ constructor(maxBodyBytes: number);
8
+ append(chunk: string): void;
9
+ take(): string | undefined | null;
10
+ }
@@ -0,0 +1,29 @@
1
+ export const maxFrameBytes = 8 * 1024 * 1024;
2
+ const delimiter = '\n';
3
+ export const maxReplyBodyBytes = maxFrameBytes - Buffer.byteLength(delimiter);
4
+ export function encodeIpcFrame(value) {
5
+ return JSON.stringify(value) + delimiter;
6
+ }
7
+ export class IpcFrameReader {
8
+ maxBodyBytes;
9
+ buffer = '';
10
+ constructor(maxBodyBytes) {
11
+ this.maxBodyBytes = maxBodyBytes;
12
+ }
13
+ append(chunk) {
14
+ this.buffer += chunk;
15
+ }
16
+ // Undefined means incomplete. Null means oversized.
17
+ take() {
18
+ const end = this.buffer.indexOf(delimiter);
19
+ const body = end < 0 ? this.buffer : this.buffer.slice(0, end);
20
+ if (Buffer.byteLength(body) > this.maxBodyBytes) {
21
+ this.buffer = '';
22
+ return null;
23
+ }
24
+ if (end < 0)
25
+ return undefined;
26
+ this.buffer = this.buffer.slice(end + delimiter.length);
27
+ return body;
28
+ }
29
+ }
@@ -0,0 +1,34 @@
1
+ export declare const mcpServerNamePattern: RegExp;
2
+ export declare const mcpEnvVarNamePattern: RegExp;
3
+ export declare const mcpHeaderNamePattern: RegExp;
4
+ export declare const PROJECT_MCP_CONFIG_FILENAME = ".mcp.json";
5
+ export declare const MAX_PROJECT_MCP_SERVERS = 16;
6
+ export declare function projectMcpConfigPath(root: string): string;
7
+ export type NormalizedMcpServerConfig = ({
8
+ readonly transport: 'stdio';
9
+ readonly command: string;
10
+ readonly args?: readonly string[];
11
+ readonly env?: Readonly<Record<string, string>>;
12
+ } | {
13
+ readonly transport: 'http';
14
+ readonly url: string;
15
+ readonly headers?: Readonly<Record<string, string>>;
16
+ }) & {
17
+ readonly tools?: readonly string[];
18
+ readonly read_only_tools?: readonly string[];
19
+ readonly timeout_ms?: number;
20
+ };
21
+ export declare function normalizeMcpServerEntry(raw: unknown): NormalizedMcpServerConfig;
22
+ export declare function parseProjectMcpJson(text: string): Record<string, NormalizedMcpServerConfig>;
23
+ export declare function expandMcpEnvString(input: string, lookup: (name: string) => string | undefined): {
24
+ readonly value: string;
25
+ readonly missingVars: readonly string[];
26
+ readonly substitutedValues: readonly string[];
27
+ };
28
+ export declare function expandMcpServerConfig(server: NormalizedMcpServerConfig, lookup: (name: string) => string | undefined): {
29
+ readonly config: NormalizedMcpServerConfig;
30
+ readonly missingVars: readonly string[];
31
+ readonly expandedSecrets: readonly string[];
32
+ };
33
+ export declare function normalizeWorkspaceTrustPath(workspaceRoot: string): string;
34
+ export declare function redactMcpServerForDisplay(server: NormalizedMcpServerConfig): NormalizedMcpServerConfig;
@@ -0,0 +1,268 @@
1
+ import path from 'node:path';
2
+ export const mcpServerNamePattern = /^[a-zA-Z0-9_-]{1,64}$/;
3
+ export const mcpEnvVarNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
4
+ export const mcpHeaderNamePattern = /^[A-Za-z0-9-]+$/;
5
+ export const PROJECT_MCP_CONFIG_FILENAME = '.mcp.json';
6
+ export const MAX_PROJECT_MCP_SERVERS = 16;
7
+ export function projectMcpConfigPath(root) {
8
+ return path.join(root, PROJECT_MCP_CONFIG_FILENAME);
9
+ }
10
+ function isPlainRecord(value) {
11
+ if (!value || typeof value !== 'object' || Array.isArray(value))
12
+ return false;
13
+ const proto = Object.getPrototypeOf(value);
14
+ return proto === null || proto === Object.prototype;
15
+ }
16
+ function parseStringArray(value, field) {
17
+ if (value === undefined)
18
+ return undefined;
19
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {
20
+ throw new Error(`Invalid MCP ${field}: expected an array of strings.`);
21
+ }
22
+ return value;
23
+ }
24
+ function parseStringMap(value, field, keyPattern) {
25
+ if (value === undefined)
26
+ return undefined;
27
+ if (!isPlainRecord(value)) {
28
+ throw new Error(`Invalid MCP ${field}: expected an object map.`);
29
+ }
30
+ const out = {};
31
+ for (const [key, entry] of Object.entries(value)) {
32
+ if (!keyPattern.test(key) || typeof entry !== 'string') {
33
+ throw new Error(`Invalid MCP ${field} entry "${key}".`);
34
+ }
35
+ out[key] = entry;
36
+ }
37
+ return Object.keys(out).length ? out : undefined;
38
+ }
39
+ function parseTimeoutMs(value) {
40
+ if (value === undefined)
41
+ return undefined;
42
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > 600000) {
43
+ throw new Error('Invalid MCP timeout_ms: expected an integer between 1 and 600000.');
44
+ }
45
+ return value;
46
+ }
47
+ export function normalizeMcpServerEntry(raw) {
48
+ if (!isPlainRecord(raw)) {
49
+ throw new Error('MCP server configuration must be a JSON object.');
50
+ }
51
+ const rawTransport = typeof raw.transport === 'string'
52
+ ? raw.transport.trim().toLowerCase()
53
+ : typeof raw.type === 'string'
54
+ ? raw.type.trim().toLowerCase()
55
+ : undefined;
56
+ let transport;
57
+ if (rawTransport === 'stdio') {
58
+ transport = 'stdio';
59
+ }
60
+ else if (rawTransport === 'http' ||
61
+ rawTransport === 'streamable-http' ||
62
+ rawTransport === 'streamable_http' ||
63
+ rawTransport === 'streamablehttp') {
64
+ transport = 'http';
65
+ }
66
+ else if (rawTransport === undefined) {
67
+ if (typeof raw.command === 'string')
68
+ transport = 'stdio';
69
+ else if (typeof raw.url === 'string')
70
+ transport = 'http';
71
+ else
72
+ throw new Error('MCP server configuration must specify transport/type, command, or url.');
73
+ }
74
+ else {
75
+ throw new Error(`Unsupported MCP transport/type: ${rawTransport}`);
76
+ }
77
+ const tools = parseStringArray(raw.tools, 'tools');
78
+ const readOnlyTools = parseStringArray(raw.read_only_tools ?? raw.readOnlyTools, 'read_only_tools');
79
+ const timeoutMs = parseTimeoutMs(raw.timeout_ms ?? raw.timeoutMs);
80
+ const shared = {
81
+ ...(tools ? { tools } : {}),
82
+ ...(readOnlyTools ? { read_only_tools: readOnlyTools } : {}),
83
+ ...(timeoutMs !== undefined ? { timeout_ms: timeoutMs } : {}),
84
+ };
85
+ if (transport === 'stdio') {
86
+ if (typeof raw.command !== 'string' || !raw.command.trim()) {
87
+ throw new Error('stdio MCP server requires a non-empty command.');
88
+ }
89
+ const args = parseStringArray(raw.args, 'args');
90
+ const env = parseStringMap(raw.env, 'env', mcpEnvVarNamePattern);
91
+ return {
92
+ transport: 'stdio',
93
+ command: raw.command,
94
+ ...(args ? { args } : {}),
95
+ ...(env ? { env } : {}),
96
+ ...shared,
97
+ };
98
+ }
99
+ if (typeof raw.url !== 'string' || !raw.url.trim()) {
100
+ throw new Error('http MCP server requires a valid url.');
101
+ }
102
+ const trimmedUrl = raw.url.trim();
103
+ const hasTemplateInSchemeOrRest = /\$\{[A-Za-z_][A-Za-z0-9_]*(?::-[^}]*)?\}/.test(trimmedUrl);
104
+ if (!/^https?:\/\//i.test(trimmedUrl)) {
105
+ throw new Error('http MCP server url must use http:// or https://.');
106
+ }
107
+ if (!hasTemplateInSchemeOrRest) {
108
+ const parsedUrl = new URL(trimmedUrl);
109
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
110
+ throw new Error('http MCP server url must use http:// or https://.');
111
+ }
112
+ }
113
+ const headers = parseStringMap(raw.headers, 'headers', mcpHeaderNamePattern);
114
+ return {
115
+ transport: 'http',
116
+ url: trimmedUrl,
117
+ ...(headers ? { headers } : {}),
118
+ ...shared,
119
+ };
120
+ }
121
+ export function parseProjectMcpJson(text) {
122
+ let parsed;
123
+ try {
124
+ parsed = JSON.parse(text);
125
+ }
126
+ catch {
127
+ throw new Error('Invalid .mcp.json: malformed JSON.');
128
+ }
129
+ if (!isPlainRecord(parsed) || !isPlainRecord(parsed.mcpServers)) {
130
+ throw new Error('Invalid .mcp.json: expected a top-level "mcpServers" object.');
131
+ }
132
+ const entries = Object.entries(parsed.mcpServers);
133
+ if (entries.length > MAX_PROJECT_MCP_SERVERS) {
134
+ throw new Error(`Invalid .mcp.json: at most ${MAX_PROJECT_MCP_SERVERS} MCP servers are supported.`);
135
+ }
136
+ const servers = {};
137
+ for (const [name, entry] of entries) {
138
+ if (!mcpServerNamePattern.test(name)) {
139
+ throw new Error(`Invalid MCP server name "${name}" in .mcp.json.`);
140
+ }
141
+ servers[name] = normalizeMcpServerEntry(entry);
142
+ }
143
+ return servers;
144
+ }
145
+ const envPlaceholderPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
146
+ export function expandMcpEnvString(input, lookup) {
147
+ const missingVars = [];
148
+ const substitutedValues = [];
149
+ const value = input.replace(envPlaceholderPattern, (_match, varName, fallback) => {
150
+ const resolved = lookup(varName);
151
+ if (fallback !== undefined) {
152
+ const chosen = resolved !== undefined && resolved !== '' ? resolved : fallback;
153
+ if (resolved !== undefined && resolved !== '')
154
+ substitutedValues.push(resolved);
155
+ return chosen;
156
+ }
157
+ if (resolved === undefined) {
158
+ if (!missingVars.includes(varName))
159
+ missingVars.push(varName);
160
+ return '';
161
+ }
162
+ if (resolved !== '')
163
+ substitutedValues.push(resolved);
164
+ return resolved;
165
+ });
166
+ return { value, missingVars, substitutedValues };
167
+ }
168
+ export function expandMcpServerConfig(server, lookup) {
169
+ const missing = new Set();
170
+ const secrets = new Set();
171
+ const expand = (raw) => {
172
+ const res = expandMcpEnvString(raw, lookup);
173
+ for (const v of res.missingVars)
174
+ missing.add(v);
175
+ for (const s of res.substitutedValues)
176
+ secrets.add(s);
177
+ return res.value;
178
+ };
179
+ const shared = {
180
+ ...(server.tools ? { tools: server.tools } : {}),
181
+ ...(server.read_only_tools ? { read_only_tools: server.read_only_tools } : {}),
182
+ ...(server.timeout_ms !== undefined ? { timeout_ms: server.timeout_ms } : {}),
183
+ };
184
+ if (server.transport === 'stdio') {
185
+ const command = expand(server.command);
186
+ const args = server.args?.map(expand);
187
+ const env = server.env
188
+ ? Object.fromEntries(Object.entries(server.env).map(([k, v]) => [k, expand(v)]))
189
+ : undefined;
190
+ return {
191
+ config: {
192
+ transport: 'stdio',
193
+ command,
194
+ ...(args ? { args } : {}),
195
+ ...(env ? { env } : {}),
196
+ ...shared,
197
+ },
198
+ missingVars: [...missing],
199
+ expandedSecrets: [...secrets],
200
+ };
201
+ }
202
+ const url = expand(server.url);
203
+ const headers = server.headers
204
+ ? Object.fromEntries(Object.entries(server.headers).map(([k, v]) => [k, expand(v)]))
205
+ : undefined;
206
+ return {
207
+ config: {
208
+ transport: 'http',
209
+ url,
210
+ ...(headers ? { headers } : {}),
211
+ ...shared,
212
+ },
213
+ missingVars: [...missing],
214
+ expandedSecrets: [...secrets],
215
+ };
216
+ }
217
+ export function normalizeWorkspaceTrustPath(workspaceRoot) {
218
+ const resolved = path.resolve(workspaceRoot);
219
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
220
+ }
221
+ function redactValueForDisplay(value) {
222
+ const ref = /^\$\{([A-Za-z_][A-Za-z0-9_]*)(:-[^}]*)?\}$/.exec(value);
223
+ if (!ref)
224
+ return '[redacted]';
225
+ return ref[2] ? '${' + ref[1] + ':-[redacted]}' : value;
226
+ }
227
+ function redactMcpUrl(address, headers = {}) {
228
+ try {
229
+ const url = new URL(address);
230
+ const parts = url.pathname.split('/');
231
+ const sensitive = /^(?:access[-_]?token|token|api[-_]?key|key|auth|secret|password|credential)$/i;
232
+ const credentials = Object.values(headers).flatMap((value) => [value, value.replace(/^Bearer\s+/i, '')]);
233
+ const pathname = parts.map((part, index) => {
234
+ const decoded = decodeURIComponent(part);
235
+ if (sensitive.test(parts[index - 1] ?? '') ||
236
+ /(?:token|api[-_]?key|secret|password|credential)[=:]/i.test(decoded) ||
237
+ /^(?:sk[-_]|gh[pousr]_|github_pat_|xox[baprs]-|eyJ)/i.test(decoded) ||
238
+ /^[A-Za-z0-9_+~.=-]{24,}$/.test(decoded) ||
239
+ decoded.includes('${') ||
240
+ credentials.some((value) => value && decoded.includes(value)))
241
+ return '[redacted]';
242
+ return part;
243
+ });
244
+ return url.origin + pathname.join('/') + (url.search ? '?[redacted]' : '');
245
+ }
246
+ catch {
247
+ return '[redacted]';
248
+ }
249
+ }
250
+ export function redactMcpServerForDisplay(server) {
251
+ if (server.transport === 'stdio') {
252
+ if (!server.env)
253
+ return server;
254
+ return {
255
+ ...server,
256
+ env: Object.fromEntries(Object.entries(server.env).map(([k, v]) => [k, redactValueForDisplay(v)])),
257
+ };
258
+ }
259
+ return {
260
+ ...server,
261
+ url: redactMcpUrl(server.url, server.headers),
262
+ ...(server.headers
263
+ ? {
264
+ headers: Object.fromEntries(Object.entries(server.headers).map(([k, v]) => [k, redactValueForDisplay(v)])),
265
+ }
266
+ : {}),
267
+ };
268
+ }