@jini-ai/mcp 0.7.1 → 0.7.3-next.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/CHANGELOG.md +1 -1
- package/dist/agent-install/antigravity/install.d.ts +15 -0
- package/dist/agent-install/antigravity/install.js +15 -0
- package/dist/agent-install/claude/install.d.ts +4 -0
- package/dist/agent-install/claude/install.js +11 -0
- package/dist/agent-install/cline/install.d.ts +4 -0
- package/dist/agent-install/cline/install.js +7 -0
- package/dist/agent-install/codex/install.d.ts +4 -0
- package/dist/agent-install/codex/install.js +10 -0
- package/dist/agent-install/cursor/install.d.ts +4 -0
- package/dist/agent-install/cursor/install.js +4 -0
- package/dist/agent-install/hermes/install.d.ts +4 -0
- package/dist/agent-install/hermes/install.js +26 -0
- package/dist/agent-install/index.d.ts +1 -1
- package/dist/agent-install/install.d.ts +1 -11
- package/dist/agent-install/install.js +29 -167
- package/dist/agent-install/kimi/install.d.ts +4 -0
- package/dist/agent-install/kimi/install.js +10 -0
- package/dist/agent-install/openclaw/install.d.ts +4 -0
- package/dist/agent-install/openclaw/install.js +4 -0
- package/dist/agent-install/opencode/install.d.ts +4 -0
- package/dist/agent-install/opencode/install.js +7 -0
- package/dist/agent-install/owned-json-install.d.ts +7 -0
- package/dist/agent-install/owned-json-install.js +4 -4
- package/dist/agent-install/pi/install.d.ts +4 -0
- package/dist/agent-install/pi/install.js +13 -0
- package/dist/agent-install/planner-shared.d.ts +40 -0
- package/dist/agent-install/planner-shared.js +52 -0
- package/dist/agent-install/trae/install.d.ts +4 -0
- package/dist/agent-install/trae/install.js +7 -0
- package/dist/agent-install/vibe/install.d.ts +4 -0
- package/dist/agent-install/vibe/install.js +30 -0
- package/dist/bin/serve.js +5 -3
- package/dist/client/client.js +11 -7
- package/dist/core/claude/config.d.ts +21 -0
- package/dist/core/claude/config.js +29 -0
- package/dist/core/config-shared.d.ts +27 -0
- package/dist/core/config-shared.js +64 -0
- package/dist/core/config.d.ts +60 -81
- package/dist/core/config.js +33 -192
- package/dist/core/opencode/config.d.ts +39 -0
- package/dist/core/opencode/config.js +74 -0
- package/dist/core/tokens.d.ts +38 -25
- package/dist/core/tokens.js +23 -54
- package/dist/federation/adapter.http.d.ts +8 -5
- package/dist/federation/adapter.http.js +12 -8
- package/dist/federation/admissions.d.ts +36 -0
- package/dist/federation/admissions.js +34 -0
- package/dist/federation/approvals/call-confirmation.js +2 -2
- package/dist/federation/approvals/remembered-approval.d.ts +11 -2
- package/dist/federation/approvals/remembered-approval.js +11 -8
- package/dist/federation/approvals/revocation-reason.d.ts +3 -1
- package/dist/federation/approvals/revocation-reason.js +1 -1
- package/dist/federation/approvals/revocation.js +3 -3
- package/dist/federation/approvals/scope-option.d.ts +3 -1
- package/dist/federation/approvals/scope-option.js +1 -1
- package/dist/federation/bootstrap.d.ts +1 -1
- package/dist/federation/bootstrap.js +4 -5
- package/dist/federation/config.d.ts +1 -1
- package/dist/federation/hosted/access.d.ts +53 -1
- package/dist/federation/hosted/access.js +94 -0
- package/dist/federation/hosted/connection-gate.js +1 -1
- package/dist/federation/hosted/index.d.ts +11 -3
- package/dist/federation/hosted/index.js +9 -3
- package/dist/federation/hosted/pinned-capability.d.ts +91 -0
- package/dist/federation/hosted/pinned-capability.js +73 -0
- package/dist/federation/hosted/probe.d.ts +67 -0
- package/dist/federation/hosted/probe.js +99 -0
- package/dist/federation/hosted/revocation.d.ts +5 -2
- package/dist/federation/hosted/revocation.js +1 -1
- package/dist/federation/hosted/store-config.d.ts +43 -0
- package/dist/federation/hosted/store-config.js +209 -0
- package/dist/federation/hosted/store-credentials.d.ts +74 -0
- package/dist/federation/hosted/store-credentials.js +228 -0
- package/dist/federation/hosted/store-input.d.ts +55 -0
- package/dist/federation/hosted/store-input.js +232 -0
- package/dist/federation/hosted/store-oauth-fields.d.ts +26 -0
- package/dist/federation/hosted/store-oauth-fields.js +246 -0
- package/dist/federation/hosted/store-view.d.ts +49 -0
- package/dist/federation/hosted/store-view.js +112 -0
- package/dist/federation/hosted/store.d.ts +13 -180
- package/dist/federation/hosted/store.js +33 -1252
- package/dist/federation/hosted/store.memory.d.ts +26 -1
- package/dist/federation/hosted/store.memory.js +71 -22
- package/dist/federation/hosted/store.save.d.ts +39 -0
- package/dist/federation/hosted/store.save.js +63 -0
- package/dist/federation/hosted/vault.d.ts +79 -1
- package/dist/federation/hosted/vault.js +107 -0
- package/dist/federation/hosted/vocabulary.d.ts +1 -1
- package/dist/federation/hosted/vocabulary.js +1 -1
- package/dist/federation/index.d.ts +1 -0
- package/dist/federation/index.js +1 -0
- package/dist/federation/mcp-protocol.d.ts +1 -1
- package/dist/federation/mcp-protocol.js +1 -1
- package/dist/federation/ports.d.ts +2 -2
- package/dist/federation/refusal-notice.d.ts +1 -1
- package/dist/federation/refusal-notice.js +1 -1
- package/dist/federation/registrations.d.ts +6 -6
- package/dist/federation/registrations.js +1 -1
- package/dist/federation/reload.js +37 -36
- package/dist/federation/stdio/adapter.stdio.js +27 -20
- package/dist/federation/stdio/default-connect.d.ts +2 -5
- package/dist/federation/stdio/default-connect.js +2 -1
- package/dist/federation/stdio/index.d.ts +1 -0
- package/dist/federation/stdio/index.js +1 -0
- package/dist/federation/stdio/smoke.d.ts +62 -0
- package/dist/federation/stdio/smoke.js +156 -0
- package/dist/federation/trust.d.ts +2 -2
- package/dist/federation/trust.js +4 -4
- package/dist/index.d.ts +3 -4
- package/dist/index.js +1 -1
- package/dist/server/adapters/sdk-server.d.ts +88 -0
- package/dist/server/adapters/sdk-server.js +27 -0
- package/dist/server/{sdk-transport.d.ts → adapters/sdk-transport.d.ts} +3 -3
- package/dist/server/{sdk-transport.js → adapters/sdk-transport.js} +2 -2
- package/dist/server/adapters/sdk-wire.d.ts +16 -0
- package/dist/server/adapters/sdk-wire.js +16 -0
- package/dist/server/call-progress.d.ts +48 -0
- package/dist/server/call-progress.js +60 -0
- package/dist/server/http-tool-server.adapter.js +209 -196
- package/dist/server/index.d.ts +1 -0
- package/dist/server/loopback-fetch.d.ts +5 -0
- package/dist/server/loopback-fetch.js +48 -0
- package/dist/server/resource-protocol.d.ts +1 -1
- package/dist/server/run-tool-host.js +3 -1
- package/dist/server/stdio-hosting.d.ts +8 -12
- package/dist/server/stdio-hosting.js +135 -126
- package/dist/server/tool-arguments.d.ts +9 -1
- package/dist/server/tool-arguments.js +18 -4
- package/dist/server/tool-protocol.d.ts +15 -3
- package/dist/server/tool-protocol.js +18 -21
- package/dist/server/tool-result-pages.js +37 -28
- package/dist/server/tool-server.d.ts +8 -46
- package/dist/server/tool-server.js +138 -128
- package/dist/server/tools/component-catalog-tools.d.ts +2 -2
- package/dist/server/tools/component-catalog-tools.js +2 -2
- package/dist/server/tools/delegated-tool.js +74 -57
- package/dist/server/tools/run-tools.d.ts +5 -5
- package/dist/server/tools/run-tools.js +5 -5
- package/dist/server/tools/tool-catalog-tools.d.ts +2 -2
- package/dist/server/tools/tool-catalog-tools.js +35 -12
- package/package.json +8 -9
package/dist/core/config.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import { inspect } from 'node:util';
|
|
2
|
-
import { redactSecrets } from '@jini-ai/core';
|
|
3
|
-
import { isLoopbackHostname } from '@jini-ai/platform/net';
|
|
4
1
|
/**
|
|
5
2
|
* @module @jini-ai/mcp/core/config
|
|
6
3
|
* Config schema + on-disk store for the external MCP servers the daemon connects
|
|
@@ -22,12 +19,15 @@ import { isLoopbackHostname } from '@jini-ai/platform/net';
|
|
|
22
19
|
// We deliberately keep the schema close to Claude Code's `.mcp.json` and
|
|
23
20
|
// Cursor's MCP config — those are the de-facto interchange formats — so
|
|
24
21
|
// users can copy-paste between tools without translation.
|
|
25
|
-
import { readFile } from 'node:fs/promises';
|
|
26
22
|
import { realpathSync } from 'node:fs';
|
|
27
23
|
import path from 'node:path';
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
24
|
+
import { afterSettled, orFallbackSync } from '@jini-ai/core/errors/idioms';
|
|
25
|
+
import { createConsoleLogger, pathContains } from '@jini-ai/core/primitives';
|
|
26
|
+
import { inferMcpAuthModeForUrl, isPlainObject } from './config-shared.js';
|
|
27
|
+
export { inferMcpAuthModeForUrl } from './config-shared.js';
|
|
28
|
+
export { buildClaudeMcpJson } from './claude/config.js';
|
|
29
|
+
export { buildOpenCodeMcpConfigContent } from './opencode/config.js';
|
|
30
|
+
/** Text I/O boundary; secret writes must be atomic and owner-only from creation. */
|
|
31
31
|
/** Shared atomic secret persistence (CR-006 / SEC-RB-002).
|
|
32
32
|
* The previous pattern in each of those stores wrote the temp file with
|
|
33
33
|
* default permissions and either never restricted it (config, OAuth client
|
|
@@ -53,10 +53,11 @@ import { trimCharsEnd } from '@jini-ai/core/text';
|
|
|
53
53
|
* flush can fail after replacement; it is reported rather than silently ignored.
|
|
54
54
|
*
|
|
55
55
|
*/
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
};
|
|
56
|
+
export const MCP_SECRET_WRITE_OPTIONS = { mode: 0o600, verifyOwnerOnly: true, createParent: true };
|
|
57
|
+
/** Adapt secret text to the atomic writer with MCP's owner-only policy; writer errors propagate. */
|
|
58
|
+
export function writeSecretText({ files, filePath, contents }, _optional = {}) {
|
|
59
|
+
return files.writer.writeText({ filePath, content: contents }, MCP_SECRET_WRITE_OPTIONS);
|
|
60
|
+
}
|
|
60
61
|
const VALID_TRANSPORTS = new Set([
|
|
61
62
|
'stdio',
|
|
62
63
|
'sse',
|
|
@@ -70,9 +71,6 @@ const SERVER_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
|
|
|
70
71
|
function configFile(dataDir) {
|
|
71
72
|
return path.join(dataDir, 'mcp-config.json');
|
|
72
73
|
}
|
|
73
|
-
function isPlainObject(v) {
|
|
74
|
-
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
|
75
|
-
}
|
|
76
74
|
function isKeepableMapEntry(entry) {
|
|
77
75
|
const [k, v] = entry;
|
|
78
76
|
if (k === '__proto__' || k === 'constructor' || !k.trim())
|
|
@@ -86,10 +84,11 @@ function isKeepableMapEntry(entry) {
|
|
|
86
84
|
return typeof v === 'string' && v.trim() !== '';
|
|
87
85
|
}
|
|
88
86
|
function sanitizeStringMap(raw) {
|
|
89
|
-
|
|
87
|
+
const input = { v: raw };
|
|
88
|
+
if (!isPlainObject(input))
|
|
90
89
|
return undefined;
|
|
91
90
|
const out = {};
|
|
92
|
-
for (const [k, v] of Object.entries(
|
|
91
|
+
for (const [k, v] of Object.entries(input.v).filter(isKeepableMapEntry))
|
|
93
92
|
out[k] = v;
|
|
94
93
|
return Object.keys(out).length > 0 ? out : undefined;
|
|
95
94
|
}
|
|
@@ -102,44 +101,21 @@ function sanitizeStringArray(raw) {
|
|
|
102
101
|
const out = raw.filter((v) => typeof v === 'string');
|
|
103
102
|
return out.length > 0 ? out : undefined;
|
|
104
103
|
}
|
|
105
|
-
// The shared classifier receives the URL parser's canonical hostname; IPv4-mapped
|
|
106
|
-
// IPv6 is deliberately not a loopback exception for default authentication.
|
|
107
|
-
/**
|
|
108
|
-
* Infer the appropriate `McpAuthMode` for a given server URL.
|
|
109
|
-
* Returns `'none'` for loopback targets (localhost, 127.x.x.x, ::1)
|
|
110
|
-
* and `'oauth'` for everything else, including when `rawUrl` is absent or unparseable.
|
|
111
|
-
* @param rawUrl The server URL string to inspect, if any.
|
|
112
|
-
* @returns The inferred `McpAuthMode`.
|
|
113
|
-
*/
|
|
114
|
-
export function inferMcpAuthModeForUrl({ rawUrl }) {
|
|
115
|
-
if (!rawUrl)
|
|
116
|
-
return 'oauth';
|
|
117
|
-
try {
|
|
118
|
-
return isLoopbackHostname({ hostname: new URL(rawUrl).hostname }) ? 'none' : 'oauth';
|
|
119
|
-
}
|
|
120
|
-
catch {
|
|
121
|
-
return 'oauth';
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
104
|
function sanitizeMcpAuthMode(raw) {
|
|
125
105
|
return typeof raw === 'string' && VALID_AUTH_MODES.has(raw)
|
|
126
106
|
? raw
|
|
127
107
|
: undefined;
|
|
128
108
|
}
|
|
129
|
-
// Only ever invoked for http/sse servers (the callers gate on transport), so
|
|
130
|
-
// there is no stdio short-circuit here — the token merge just needs the
|
|
131
|
-
// effective auth mode for a remote server.
|
|
132
|
-
function effectiveMcpAuthMode(server) {
|
|
133
|
-
return server.authMode ?? inferMcpAuthModeForUrl({ rawUrl: server.url });
|
|
134
|
-
}
|
|
135
109
|
/**
|
|
136
110
|
* Validate a single user-supplied entry. Drops invalid fields so a typo in
|
|
137
111
|
* one server doesn't tank the whole config. Returns null when the entry is
|
|
138
112
|
* unsalvageable (no id, or no transport-required fields).
|
|
139
113
|
*/
|
|
140
|
-
export function sanitizeMcpServer({ raw }) {
|
|
141
|
-
|
|
114
|
+
export function sanitizeMcpServer({ raw: value }) {
|
|
115
|
+
const input = { v: value };
|
|
116
|
+
if (!isPlainObject(input))
|
|
142
117
|
return null;
|
|
118
|
+
const raw = input.v;
|
|
143
119
|
const id = typeof raw.id === 'string' ? raw.id.trim() : '';
|
|
144
120
|
if (!SERVER_ID_PATTERN.test(id))
|
|
145
121
|
return null;
|
|
@@ -202,9 +178,11 @@ function sanitizeRemoteFields(raw) {
|
|
|
202
178
|
* @param raw The raw parsed JSON to sanitize.
|
|
203
179
|
* @returns A clean `McpConfig` guaranteed to have only valid, unique server entries.
|
|
204
180
|
*/
|
|
205
|
-
export function sanitizeMcpConfig({ raw }) {
|
|
206
|
-
|
|
181
|
+
export function sanitizeMcpConfig({ raw: value }) {
|
|
182
|
+
const input = { v: value };
|
|
183
|
+
if (!isPlainObject(input))
|
|
207
184
|
return { servers: [] };
|
|
185
|
+
const raw = input.v;
|
|
208
186
|
const list = Array.isArray(raw.servers) ? raw.servers : [];
|
|
209
187
|
const seen = new Set();
|
|
210
188
|
const out = [];
|
|
@@ -223,9 +201,9 @@ export function sanitizeMcpConfig({ raw }) {
|
|
|
223
201
|
* @param dataDir The resolved runtime data directory.
|
|
224
202
|
* @returns The sanitized `McpConfig`, never rejects on missing-file or corrupt-JSON.
|
|
225
203
|
*/
|
|
226
|
-
export async function readMcpConfig({ dataDir }, {
|
|
204
|
+
export async function readMcpConfig({ dataDir, files }, { report = createConsoleLogger({ prefix: '[mcp-config]' }) } = {}) {
|
|
227
205
|
try {
|
|
228
|
-
const raw = await
|
|
206
|
+
const raw = await files.readText({ filePath: configFile(dataDir) });
|
|
229
207
|
const parsed = JSON.parse(raw);
|
|
230
208
|
return sanitizeMcpConfig({ raw: parsed });
|
|
231
209
|
}
|
|
@@ -234,7 +212,8 @@ export async function readMcpConfig({ dataDir }, { filesystem = defaultFilesyste
|
|
|
234
212
|
if (e.code === 'ENOENT')
|
|
235
213
|
return { servers: [] };
|
|
236
214
|
if (e.name === 'SyntaxError') {
|
|
237
|
-
|
|
215
|
+
const logger = report;
|
|
216
|
+
logger.error({ message: `The MCP config file ${configFile(dataDir)} is not valid JSON; reading it as an empty server list.` }, { error: err });
|
|
238
217
|
return { servers: [] };
|
|
239
218
|
}
|
|
240
219
|
throw err;
|
|
@@ -248,15 +227,15 @@ const writeLocks = new Map();
|
|
|
248
227
|
* being written. This file may carry environment variables and
|
|
249
228
|
* `Authorization` header values (API keys, bearer tokens — see
|
|
250
229
|
* `McpServerConfig.env`/`.headers`), so it is written with owner-only
|
|
251
|
-
* (0600) permissions from the very first byte via
|
|
230
|
+
* (0600) permissions from the very first byte via the injected atomic writer
|
|
252
231
|
* rather than a post-rename chmod (CR-006 / SEC-RB-002).
|
|
253
232
|
* @param dataDir The resolved runtime data directory.
|
|
254
233
|
* @param body The raw config body to sanitize and persist.
|
|
255
234
|
* @returns The sanitized `McpConfig` that was written to disk.
|
|
256
235
|
*/
|
|
257
|
-
export async function writeMcpConfig({ dataDir, body },
|
|
236
|
+
export async function writeMcpConfig({ dataDir, body, files }, _optional = {}) {
|
|
258
237
|
const prev = writeLocks.get(dataDir) ?? Promise.resolve();
|
|
259
|
-
const task =
|
|
238
|
+
const task = afterSettled({ promise: prev }).then(() => doWrite(dataDir, body, files));
|
|
260
239
|
writeLocks.set(dataDir, task);
|
|
261
240
|
try {
|
|
262
241
|
return await task;
|
|
@@ -266,9 +245,9 @@ export async function writeMcpConfig({ dataDir, body }, { filesystem = defaultFi
|
|
|
266
245
|
writeLocks.delete(dataDir);
|
|
267
246
|
}
|
|
268
247
|
}
|
|
269
|
-
async function doWrite(dataDir, body,
|
|
248
|
+
async function doWrite(dataDir, body, files) {
|
|
270
249
|
const next = sanitizeMcpConfig({ raw: body });
|
|
271
|
-
await
|
|
250
|
+
await writeSecretText({ files, filePath: configFile(dataDir), contents: JSON.stringify(next, null, 2) });
|
|
272
251
|
return next;
|
|
273
252
|
}
|
|
274
253
|
// ───────────────────────────────────────────────────────────────────────
|
|
@@ -280,12 +259,7 @@ async function doWrite(dataDir, body, filesystem) {
|
|
|
280
259
|
* segments) when it does not exist yet, or the platform can't resolve it.
|
|
281
260
|
*/
|
|
282
261
|
function resolveRealOrLexical({ filePath: p }) {
|
|
283
|
-
|
|
284
|
-
return realpathSync.native(p);
|
|
285
|
-
}
|
|
286
|
-
catch {
|
|
287
|
-
return path.resolve(p);
|
|
288
|
-
}
|
|
262
|
+
return orFallbackSync({ work: () => realpathSync.native(p), fallback: undefined, step: 'Resolve MCP config path' }) ?? path.resolve(p);
|
|
289
263
|
}
|
|
290
264
|
/**
|
|
291
265
|
* True when `cwd` is a daemon-managed project directory under `projectsDir`
|
|
@@ -312,66 +286,6 @@ export function isManagedProjectCwd({ cwd, projectsDir }, { resolvePath = resolv
|
|
|
312
286
|
return false; // projects root, not a project
|
|
313
287
|
return pathContains({ root: resolvedProjectsDir, target: resolvedCwd }, { caseSensitive: path.sep !== '\\', separator: path.sep });
|
|
314
288
|
}
|
|
315
|
-
/**
|
|
316
|
-
* Project-cwd `.mcp.json` shape that Claude Code auto-loads on spawn (the
|
|
317
|
-
* same format Claude Desktop and Cursor use). Returns null when the user
|
|
318
|
-
* has no enabled servers — in that case the caller should NOT write the
|
|
319
|
-
* file (and should clean up any stale one).
|
|
320
|
-
*
|
|
321
|
-
* `tokens` is an optional map of `serverId -> bearer access token`, used
|
|
322
|
-
* for HTTP/SSE servers that completed the daemon's web OAuth flow. When a
|
|
323
|
-
* token is present we inject `Authorization: Bearer <token>` into the
|
|
324
|
-
* server's headers — this is what bypasses the per-spawn `mcp-remote`
|
|
325
|
-
* dance and lets Claude Code talk directly to the upstream MCP using
|
|
326
|
-
* pre-authenticated credentials. User-supplied headers always win on
|
|
327
|
-
* conflict so they can pin a specific token if they really want to.
|
|
328
|
-
*/
|
|
329
|
-
export function buildClaudeMcpJson({ servers }, { tokens = {} } = {}) {
|
|
330
|
-
const enabled = servers.filter((s) => s.enabled);
|
|
331
|
-
if (enabled.length === 0)
|
|
332
|
-
return null;
|
|
333
|
-
const out = {};
|
|
334
|
-
for (const s of enabled) {
|
|
335
|
-
out[s.id] = s.transport === 'stdio'
|
|
336
|
-
? { command: s.command, ...nonEmptyField({ key: 'args', value: s.args }), ...nonEmptyField({ key: 'env', value: s.env }) }
|
|
337
|
-
// type: 'sse' | 'http'
|
|
338
|
-
: { type: s.transport, url: s.url, ...remoteHeadersField({ server: s, tokens }) };
|
|
339
|
-
}
|
|
340
|
-
return { mcpServers: out };
|
|
341
|
-
}
|
|
342
|
-
/** `{ [key]: value }` when `value` has at least one element/key, else `{}` — for spreading optional fields. */
|
|
343
|
-
function nonEmptyField({ key, value }) {
|
|
344
|
-
return value && Object.keys(value).length > 0 ? { [key]: value } : {};
|
|
345
|
-
}
|
|
346
|
-
/** `{ headers }` for a remote server (user headers + its own stored OAuth bearer), or `{}` when empty. */
|
|
347
|
-
function remoteHeadersField({ server, tokens }, _options = {}) {
|
|
348
|
-
const bearer = effectiveMcpAuthMode(server) === 'oauth' && Object.hasOwn(tokens, server.id) ? tokens[server.id] : undefined;
|
|
349
|
-
return nonEmptyField({ key: 'headers', value: mergeAuthHeader(server.headers, bearer) });
|
|
350
|
-
}
|
|
351
|
-
/** Build a headers object that includes the daemon-issued bearer token when
|
|
352
|
-
* the user hasn't already supplied a NON-EMPTY Authorization header. A
|
|
353
|
-
* blank Authorization (empty string / whitespace only) is treated as
|
|
354
|
-
* "not pinned" — historically the template UI persisted empty values from
|
|
355
|
-
* unfilled fields, and we never want a blank Authorization to suppress a
|
|
356
|
-
* valid OAuth Bearer (the upstream MCP would refuse the connection and
|
|
357
|
-
* fall back to its in-tool re-auth dance). Real user-pinned values still
|
|
358
|
-
* win so manually-set PATs aren't silently overwritten. */
|
|
359
|
-
function mergeAuthHeader(existing, bearer) {
|
|
360
|
-
const merged = {};
|
|
361
|
-
let userAuth = false;
|
|
362
|
-
for (const [k, v] of Object.entries(existing ?? {})) {
|
|
363
|
-
const isAuth = k.toLowerCase() === 'authorization';
|
|
364
|
-
// empty / whitespace authorization is ignored, NOT carried through
|
|
365
|
-
if (isAuth && (typeof v !== 'string' || v.trim() === ''))
|
|
366
|
-
continue;
|
|
367
|
-
userAuth ||= isAuth;
|
|
368
|
-
merged[k] = v;
|
|
369
|
-
}
|
|
370
|
-
if (bearer && !userAuth) {
|
|
371
|
-
merged['Authorization'] = `Bearer ${bearer}`;
|
|
372
|
-
}
|
|
373
|
-
return merged;
|
|
374
|
-
}
|
|
375
289
|
/**
|
|
376
290
|
* Convert user-configured external MCP servers into the ACP `mcpServers` array.
|
|
377
291
|
* Only stdio servers are included — SSE/HTTP are dropped because ACP currently
|
|
@@ -392,77 +306,4 @@ export function buildAcpMcpServers({ servers }) {
|
|
|
392
306
|
.map(([name, value]) => ({ name, value })),
|
|
393
307
|
}));
|
|
394
308
|
}
|
|
395
|
-
export function buildOpenCodeMcpConfigContent({ servers }, options = {}) {
|
|
396
|
-
const tokens = options.tokens ?? {};
|
|
397
|
-
const resolvePath = options.resolvePath ?? (({ filePath }) => realpathSync.native(filePath));
|
|
398
|
-
const mcp = {};
|
|
399
|
-
for (const s of servers.filter((server) => server.enabled)) {
|
|
400
|
-
const entry = buildOpenCodeServerEntry({ server: s, tokens });
|
|
401
|
-
if (entry)
|
|
402
|
-
mcp[s.id] = entry;
|
|
403
|
-
}
|
|
404
|
-
const externalDirectory = buildOpenCodeExternalDirectoryAllowlist(options.allowedDirectories, resolvePath);
|
|
405
|
-
const config = { ...options.extraConfig, ...nonEmptyField({ key: 'mcp', value: mcp }) };
|
|
406
|
-
if (externalDirectory) {
|
|
407
|
-
const priorPermission = isPlainObject(config.permission) ? config.permission : {};
|
|
408
|
-
config.permission = {
|
|
409
|
-
...priorPermission,
|
|
410
|
-
external_directory: externalDirectory,
|
|
411
|
-
};
|
|
412
|
-
}
|
|
413
|
-
return Object.keys(config).length === 0 ? null : JSON.stringify(config);
|
|
414
|
-
}
|
|
415
|
-
/** One OpenCode `mcp` entry, or null when the server lacks its transport-required command/url. */
|
|
416
|
-
function buildOpenCodeServerEntry({ server: s, tokens }) {
|
|
417
|
-
if (s.transport === 'stdio') {
|
|
418
|
-
const cmd = typeof s.command === 'string' ? s.command.trim() : '';
|
|
419
|
-
if (!cmd)
|
|
420
|
-
return null;
|
|
421
|
-
return {
|
|
422
|
-
type: 'local',
|
|
423
|
-
command: [cmd, ...(Array.isArray(s.args) ? s.args : [])],
|
|
424
|
-
...nonEmptyField({ key: 'environment', value: { ...s.env } }),
|
|
425
|
-
enabled: true,
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
if (typeof s.url !== 'string' || !s.url.trim())
|
|
429
|
-
return null;
|
|
430
|
-
return { type: 'remote', url: s.url, ...remoteHeadersField({ server: s, tokens }), enabled: true };
|
|
431
|
-
}
|
|
432
|
-
function buildOpenCodeExternalDirectoryAllowlist(directories, resolvePath) {
|
|
433
|
-
const normalized = Array.from(new Set((directories ?? [])
|
|
434
|
-
.filter((dir) => typeof dir === 'string' && dir.trim().length > 0)
|
|
435
|
-
.filter((dir) => path.isAbsolute(dir))
|
|
436
|
-
.flatMap((dir) => normalizeAllowedDirectoryVariants(dir, resolvePath))));
|
|
437
|
-
if (normalized.length === 0)
|
|
438
|
-
return null;
|
|
439
|
-
const allowlist = {};
|
|
440
|
-
for (const dir of normalized) {
|
|
441
|
-
allowlist[dir] = 'allow';
|
|
442
|
-
allowlist[joinPermissionGlob(dir, '*')] = 'allow';
|
|
443
|
-
allowlist[joinPermissionGlob(dir, '**')] = 'allow';
|
|
444
|
-
}
|
|
445
|
-
return allowlist;
|
|
446
|
-
}
|
|
447
|
-
function normalizeAllowedDirectory(dir) {
|
|
448
|
-
const resolved = path.resolve(dir);
|
|
449
|
-
const root = path.parse(resolved).root;
|
|
450
|
-
if (resolved === root)
|
|
451
|
-
return root;
|
|
452
|
-
return trimCharsEnd({ text: resolved, chars: '\\/' });
|
|
453
|
-
}
|
|
454
|
-
function normalizeAllowedDirectoryVariants(dir, resolvePath) {
|
|
455
|
-
const normalized = normalizeAllowedDirectory(dir);
|
|
456
|
-
let real = null;
|
|
457
|
-
try {
|
|
458
|
-
real = normalizeAllowedDirectory(resolvePath({ filePath: dir }));
|
|
459
|
-
}
|
|
460
|
-
catch {
|
|
461
|
-
real = null;
|
|
462
|
-
}
|
|
463
|
-
return real && real !== normalized ? [normalized, real] : [normalized];
|
|
464
|
-
}
|
|
465
|
-
function joinPermissionGlob(dir, suffix) {
|
|
466
|
-
return dir.endsWith(path.sep) ? `${dir}${suffix}` : `${dir}${path.sep}${suffix}`;
|
|
467
|
-
}
|
|
468
309
|
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { McpServerConfig } from '../config.js';
|
|
2
|
+
/**
|
|
3
|
+
* OpenCode merges its config from multiple sources at boot — global
|
|
4
|
+
* `~/.config/opencode/opencode.json`, the `OPENCODE_CONFIG` file path, the
|
|
5
|
+
* project `opencode.json`, and the `OPENCODE_CONFIG_CONTENT` env var (an
|
|
6
|
+
* inline JSON string). The env-var path is what lets a launcher hand servers
|
|
7
|
+
* to a single `opencode run` invocation without writing into the user's
|
|
8
|
+
* global config or leaving a temp file around on crash. We also use the same
|
|
9
|
+
* payload to grant `external_directory` access to launcher-selected absolute
|
|
10
|
+
* paths (project cwd, staged skill dirs, etc.) so headless OpenCode runs do
|
|
11
|
+
* not auto-reject them.
|
|
12
|
+
*
|
|
13
|
+
* Returns `null` when nothing would be emitted — the caller must NOT set
|
|
14
|
+
* `OPENCODE_CONFIG_CONTENT` to `null`/empty in that case, because doing so
|
|
15
|
+
* would override the user's saved global config with an empty object. A
|
|
16
|
+
* null return means "leave the env untouched and let OpenCode read the
|
|
17
|
+
* user's home-dir config as-is."
|
|
18
|
+
*
|
|
19
|
+
* The OAuth Bearer merge mirrors `buildClaudeMcpJson` so a remote MCP
|
|
20
|
+
* server the daemon already authenticated against works the same way for
|
|
21
|
+
* OpenCode users without forcing them to re-authenticate inside OpenCode.
|
|
22
|
+
*/
|
|
23
|
+
/** Options for `buildOpenCodeMcpConfigContent`. */
|
|
24
|
+
export interface OpenCodeConfigBuildOptions {
|
|
25
|
+
/** Access tokens keyed by server id. */
|
|
26
|
+
tokens?: Record<string, string>;
|
|
27
|
+
/** Resolves symlinks for permission allowlists. */
|
|
28
|
+
resolvePath?: (args: {
|
|
29
|
+
filePath: string;
|
|
30
|
+
}) => string;
|
|
31
|
+
/** Absolute filesystem paths OpenCode's `external_directory` permission should allow. */
|
|
32
|
+
allowedDirectories?: string[];
|
|
33
|
+
/** Additional top-level keys merged into the emitted config object (e.g. `provider`). */
|
|
34
|
+
extraConfig?: Record<string, unknown>;
|
|
35
|
+
}
|
|
36
|
+
export declare function buildOpenCodeMcpConfigContent({ servers }: {
|
|
37
|
+
servers: McpServerConfig[];
|
|
38
|
+
}, options?: OpenCodeConfigBuildOptions): string | null;
|
|
39
|
+
//# sourceMappingURL=config.d.ts.map
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { trimCharsEnd } from '@jini-ai/core/text';
|
|
4
|
+
import { orFallbackSync } from '@jini-ai/core/errors/idioms';
|
|
5
|
+
import { isPlainObject, nonEmptyField, remoteHeadersField } from '../config-shared.js';
|
|
6
|
+
export function buildOpenCodeMcpConfigContent({ servers }, options = {}) {
|
|
7
|
+
const tokens = options.tokens ?? {};
|
|
8
|
+
const resolvePath = options.resolvePath ?? (({ filePath }) => realpathSync.native(filePath));
|
|
9
|
+
const mcp = {};
|
|
10
|
+
for (const s of servers.filter((server) => server.enabled)) {
|
|
11
|
+
const entry = buildOpenCodeServerEntry({ server: s, tokens });
|
|
12
|
+
if (entry)
|
|
13
|
+
mcp[s.id] = entry;
|
|
14
|
+
}
|
|
15
|
+
const externalDirectory = buildOpenCodeExternalDirectoryAllowlist(options.allowedDirectories, resolvePath);
|
|
16
|
+
const config = { ...options.extraConfig, ...nonEmptyField({ key: 'mcp', value: mcp }) };
|
|
17
|
+
if (externalDirectory) {
|
|
18
|
+
const permission = { v: config.permission };
|
|
19
|
+
const priorPermission = isPlainObject(permission) ? permission.v : {};
|
|
20
|
+
config.permission = {
|
|
21
|
+
...priorPermission,
|
|
22
|
+
external_directory: externalDirectory,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
return Object.keys(config).length === 0 ? null : JSON.stringify(config);
|
|
26
|
+
}
|
|
27
|
+
/** One OpenCode `mcp` entry, or null when the server lacks its transport-required command/url. */
|
|
28
|
+
function buildOpenCodeServerEntry({ server: s, tokens }) {
|
|
29
|
+
if (s.transport === 'stdio') {
|
|
30
|
+
const cmd = typeof s.command === 'string' ? s.command.trim() : '';
|
|
31
|
+
if (!cmd)
|
|
32
|
+
return null;
|
|
33
|
+
return {
|
|
34
|
+
type: 'local',
|
|
35
|
+
command: [cmd, ...(Array.isArray(s.args) ? s.args : [])],
|
|
36
|
+
...nonEmptyField({ key: 'environment', value: { ...s.env } }),
|
|
37
|
+
enabled: true,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
if (typeof s.url !== 'string' || !s.url.trim())
|
|
41
|
+
return null;
|
|
42
|
+
return { type: 'remote', url: s.url, ...remoteHeadersField({ server: s, tokens }), enabled: true };
|
|
43
|
+
}
|
|
44
|
+
function buildOpenCodeExternalDirectoryAllowlist(directories, resolvePath) {
|
|
45
|
+
const normalized = Array.from(new Set((directories ?? [])
|
|
46
|
+
.filter((dir) => typeof dir === 'string' && dir.trim().length > 0)
|
|
47
|
+
.filter((dir) => path.isAbsolute(dir))
|
|
48
|
+
.flatMap((dir) => normalizeAllowedDirectoryVariants(dir, resolvePath))));
|
|
49
|
+
if (normalized.length === 0)
|
|
50
|
+
return null;
|
|
51
|
+
const allowlist = {};
|
|
52
|
+
for (const dir of normalized) {
|
|
53
|
+
allowlist[dir] = 'allow';
|
|
54
|
+
allowlist[joinPermissionGlob(dir, '*')] = 'allow';
|
|
55
|
+
allowlist[joinPermissionGlob(dir, '**')] = 'allow';
|
|
56
|
+
}
|
|
57
|
+
return allowlist;
|
|
58
|
+
}
|
|
59
|
+
function normalizeAllowedDirectory(dir) {
|
|
60
|
+
const resolved = path.resolve(dir);
|
|
61
|
+
const root = path.parse(resolved).root;
|
|
62
|
+
if (resolved === root)
|
|
63
|
+
return root;
|
|
64
|
+
return trimCharsEnd({ text: resolved, chars: '\\/' });
|
|
65
|
+
}
|
|
66
|
+
function normalizeAllowedDirectoryVariants(dir, resolvePath) {
|
|
67
|
+
const normalized = normalizeAllowedDirectory(dir);
|
|
68
|
+
const real = orFallbackSync({ work: () => normalizeAllowedDirectory(resolvePath({ filePath: dir })), fallback: null, step: 'Resolve OpenCode directory alias' });
|
|
69
|
+
return real && real !== normalized ? [normalized, real] : [normalized];
|
|
70
|
+
}
|
|
71
|
+
function joinPermissionGlob(dir, suffix) {
|
|
72
|
+
return dir.endsWith(path.sep) ? `${dir}${suffix}` : `${dir}${path.sep}${suffix}`;
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=config.js.map
|
package/dist/core/tokens.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type Clock } from "@jini-ai/core/primitives";
|
|
2
|
-
import type
|
|
1
|
+
import { type Clock, type Logger } from "@jini-ai/core/primitives";
|
|
2
|
+
import { type McpConfigFilesPort } from './config.js';
|
|
3
3
|
/**
|
|
4
4
|
* Stored OAuth token for a single MCP server. Mirrors the relevant subset
|
|
5
5
|
* of an OAuth 2.0 token-endpoint response (RFC 6749 §5.1), plus the OAuth
|
|
@@ -40,20 +40,13 @@ export interface McpTokensFile {
|
|
|
40
40
|
/** keyed by McpServerConfig.id */
|
|
41
41
|
servers: Record<string, StoredMcpToken>;
|
|
42
42
|
}
|
|
43
|
-
/** Optional clock used when imported tokens have no saved timestamp. */
|
|
44
|
-
export interface McpTokenClockOptions {
|
|
45
|
-
clock?: Clock;
|
|
46
|
-
}
|
|
47
|
-
/** Injectable store boundaries; defaults use the Node filesystem and wall clock. */
|
|
48
|
-
export interface McpTokenStoreOptions extends McpTokenClockOptions {
|
|
49
|
-
filesystem?: McpConfigFilesystemPort;
|
|
50
|
-
}
|
|
51
43
|
/** Coerce a freeform JSON blob into the typed shape, dropping anything that
|
|
52
44
|
* doesn't deserialize cleanly. Used both at read time and as a defensive
|
|
53
45
|
* pass when third-party tooling has hand-edited the file. */
|
|
54
|
-
export declare function sanitizeTokensFile({ raw }: {
|
|
46
|
+
export declare function sanitizeTokensFile({ raw, clock }: {
|
|
55
47
|
raw: unknown;
|
|
56
|
-
|
|
48
|
+
clock: Clock;
|
|
49
|
+
}, _optional?: {}): McpTokensFile;
|
|
57
50
|
/**
|
|
58
51
|
* Read and sanitize the MCP token store from `<dataDir>/mcp-tokens.json`.
|
|
59
52
|
* Returns an empty store when the file does not exist or contains invalid JSON.
|
|
@@ -64,38 +57,58 @@ export declare function sanitizeTokensFile({ raw }: {
|
|
|
64
57
|
* @throws On unexpected read errors or a failed backup; the damaged file is left untouched.
|
|
65
58
|
* @complexity O(n) time and space in the token file length, including a backup write on corruption.
|
|
66
59
|
*/
|
|
67
|
-
export declare function readTokensFile({ dataDir }: {
|
|
60
|
+
export declare function readTokensFile({ dataDir, clock, files }: {
|
|
68
61
|
dataDir: string;
|
|
69
|
-
|
|
62
|
+
clock: Clock;
|
|
63
|
+
files: McpConfigFilesPort;
|
|
64
|
+
}, { report }?: {
|
|
65
|
+
report?: Pick<Logger, 'error'>;
|
|
66
|
+
}): Promise<McpTokensFile>;
|
|
70
67
|
/** Get the current token for a given server, or null when none is stored
|
|
71
68
|
* (or the persisted entry is malformed). */
|
|
72
|
-
export declare function getToken({ dataDir, serverId }: {
|
|
69
|
+
export declare function getToken({ dataDir, serverId, clock, files }: {
|
|
73
70
|
dataDir: string;
|
|
74
71
|
serverId: string;
|
|
75
|
-
|
|
72
|
+
clock: Clock;
|
|
73
|
+
files: McpConfigFilesPort;
|
|
74
|
+
}, { report }?: {
|
|
75
|
+
report?: Pick<Logger, 'error'>;
|
|
76
|
+
}): Promise<StoredMcpToken | null>;
|
|
76
77
|
/** Atomically merge a new token for `serverId` into the tokens file. */
|
|
77
|
-
export declare function setToken({ dataDir, serverId, token }: {
|
|
78
|
+
export declare function setToken({ dataDir, serverId, token, clock, files }: {
|
|
78
79
|
dataDir: string;
|
|
79
80
|
serverId: string;
|
|
80
81
|
token: StoredMcpToken;
|
|
81
|
-
|
|
82
|
+
clock: Clock;
|
|
83
|
+
files: McpConfigFilesPort;
|
|
84
|
+
}, { report }?: {
|
|
85
|
+
report?: Pick<Logger, 'error'>;
|
|
86
|
+
}): Promise<void>;
|
|
82
87
|
/** Atomically delete the stored token for `serverId`. No-op when absent. */
|
|
83
|
-
export declare function clearToken({ dataDir, serverId }: {
|
|
88
|
+
export declare function clearToken({ dataDir, serverId, clock, files }: {
|
|
84
89
|
dataDir: string;
|
|
85
90
|
serverId: string;
|
|
86
|
-
|
|
91
|
+
clock: Clock;
|
|
92
|
+
files: McpConfigFilesPort;
|
|
93
|
+
}, { report }?: {
|
|
94
|
+
report?: Pick<Logger, 'error'>;
|
|
95
|
+
}): Promise<void>;
|
|
87
96
|
/** Bulk read used by the spawn pipeline so we make one disk hit per spawn,
|
|
88
97
|
* not one per server. */
|
|
89
|
-
export declare function readAllTokens({ dataDir }: {
|
|
98
|
+
export declare function readAllTokens({ dataDir, clock, files }: {
|
|
90
99
|
dataDir: string;
|
|
91
|
-
|
|
100
|
+
clock: Clock;
|
|
101
|
+
files: McpConfigFilesPort;
|
|
102
|
+
}, { report }?: {
|
|
103
|
+
report?: Pick<Logger, 'error'>;
|
|
104
|
+
}): Promise<Record<string, StoredMcpToken>>;
|
|
92
105
|
/** True when the stored token is past its `expiresAt` (or within `skew`
|
|
93
106
|
* milliseconds of expiring). Returns false when no `expiresAt` is recorded
|
|
94
107
|
* — many providers issue non-expiring tokens. */
|
|
95
|
-
export declare function isTokenExpired({ token }: {
|
|
108
|
+
export declare function isTokenExpired({ token, clock }: {
|
|
96
109
|
token: StoredMcpToken;
|
|
97
|
-
|
|
98
|
-
|
|
110
|
+
clock: Clock;
|
|
111
|
+
}, { now, skew }?: {
|
|
99
112
|
now?: number;
|
|
100
113
|
skew?: number;
|
|
101
114
|
}): boolean;
|