@jini-ai/mcp 0.7.2 → 0.7.3-next.2

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.
Files changed (146) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/dist/agent-install/antigravity/install.d.ts +15 -0
  3. package/dist/agent-install/antigravity/install.js +15 -0
  4. package/dist/agent-install/claude/install.d.ts +4 -0
  5. package/dist/agent-install/claude/install.js +11 -0
  6. package/dist/agent-install/cline/install.d.ts +4 -0
  7. package/dist/agent-install/cline/install.js +7 -0
  8. package/dist/agent-install/codex/install.d.ts +4 -0
  9. package/dist/agent-install/codex/install.js +10 -0
  10. package/dist/agent-install/cursor/install.d.ts +4 -0
  11. package/dist/agent-install/cursor/install.js +4 -0
  12. package/dist/agent-install/hermes/install.d.ts +4 -0
  13. package/dist/agent-install/hermes/install.js +26 -0
  14. package/dist/agent-install/index.d.ts +1 -1
  15. package/dist/agent-install/install.d.ts +1 -11
  16. package/dist/agent-install/install.js +29 -167
  17. package/dist/agent-install/kimi/install.d.ts +4 -0
  18. package/dist/agent-install/kimi/install.js +10 -0
  19. package/dist/agent-install/openclaw/install.d.ts +4 -0
  20. package/dist/agent-install/openclaw/install.js +4 -0
  21. package/dist/agent-install/opencode/install.d.ts +4 -0
  22. package/dist/agent-install/opencode/install.js +7 -0
  23. package/dist/agent-install/owned-json-install.d.ts +7 -0
  24. package/dist/agent-install/owned-json-install.js +4 -4
  25. package/dist/agent-install/pi/install.d.ts +4 -0
  26. package/dist/agent-install/pi/install.js +13 -0
  27. package/dist/agent-install/planner-shared.d.ts +40 -0
  28. package/dist/agent-install/planner-shared.js +52 -0
  29. package/dist/agent-install/trae/install.d.ts +4 -0
  30. package/dist/agent-install/trae/install.js +7 -0
  31. package/dist/agent-install/vibe/install.d.ts +4 -0
  32. package/dist/agent-install/vibe/install.js +30 -0
  33. package/dist/bin/serve.js +5 -3
  34. package/dist/client/client.js +11 -7
  35. package/dist/core/claude/config.d.ts +21 -0
  36. package/dist/core/claude/config.js +29 -0
  37. package/dist/core/config-shared.d.ts +27 -0
  38. package/dist/core/config-shared.js +64 -0
  39. package/dist/core/config.d.ts +60 -81
  40. package/dist/core/config.js +33 -192
  41. package/dist/core/opencode/config.d.ts +39 -0
  42. package/dist/core/opencode/config.js +74 -0
  43. package/dist/core/tokens.d.ts +38 -25
  44. package/dist/core/tokens.js +23 -54
  45. package/dist/federation/adapter.http.d.ts +8 -5
  46. package/dist/federation/adapter.http.js +12 -8
  47. package/dist/federation/admissions.d.ts +36 -0
  48. package/dist/federation/admissions.js +34 -0
  49. package/dist/federation/approvals/call-confirmation.js +2 -2
  50. package/dist/federation/approvals/remembered-approval.d.ts +11 -2
  51. package/dist/federation/approvals/remembered-approval.js +11 -8
  52. package/dist/federation/approvals/revocation-reason.d.ts +3 -1
  53. package/dist/federation/approvals/revocation-reason.js +1 -1
  54. package/dist/federation/approvals/revocation.js +3 -3
  55. package/dist/federation/approvals/scope-option.d.ts +3 -1
  56. package/dist/federation/approvals/scope-option.js +1 -1
  57. package/dist/federation/bootstrap.d.ts +1 -1
  58. package/dist/federation/bootstrap.js +4 -5
  59. package/dist/federation/config.d.ts +1 -1
  60. package/dist/federation/hosted/access.d.ts +53 -1
  61. package/dist/federation/hosted/access.js +94 -0
  62. package/dist/federation/hosted/connection-gate.js +1 -1
  63. package/dist/federation/hosted/index.d.ts +11 -3
  64. package/dist/federation/hosted/index.js +9 -3
  65. package/dist/federation/hosted/pinned-capability.d.ts +91 -0
  66. package/dist/federation/hosted/pinned-capability.js +73 -0
  67. package/dist/federation/hosted/probe.d.ts +67 -0
  68. package/dist/federation/hosted/probe.js +99 -0
  69. package/dist/federation/hosted/revocation.d.ts +5 -2
  70. package/dist/federation/hosted/revocation.js +1 -1
  71. package/dist/federation/hosted/store-config.d.ts +43 -0
  72. package/dist/federation/hosted/store-config.js +209 -0
  73. package/dist/federation/hosted/store-credentials.d.ts +74 -0
  74. package/dist/federation/hosted/store-credentials.js +228 -0
  75. package/dist/federation/hosted/store-input.d.ts +55 -0
  76. package/dist/federation/hosted/store-input.js +232 -0
  77. package/dist/federation/hosted/store-oauth-fields.d.ts +26 -0
  78. package/dist/federation/hosted/store-oauth-fields.js +246 -0
  79. package/dist/federation/hosted/store-view.d.ts +49 -0
  80. package/dist/federation/hosted/store-view.js +112 -0
  81. package/dist/federation/hosted/store.d.ts +13 -180
  82. package/dist/federation/hosted/store.js +33 -1252
  83. package/dist/federation/hosted/store.memory.d.ts +26 -1
  84. package/dist/federation/hosted/store.memory.js +71 -22
  85. package/dist/federation/hosted/store.save.d.ts +39 -0
  86. package/dist/federation/hosted/store.save.js +63 -0
  87. package/dist/federation/hosted/vault.d.ts +79 -1
  88. package/dist/federation/hosted/vault.js +107 -0
  89. package/dist/federation/hosted/vocabulary.d.ts +1 -1
  90. package/dist/federation/hosted/vocabulary.js +1 -1
  91. package/dist/federation/index.d.ts +1 -0
  92. package/dist/federation/index.js +1 -0
  93. package/dist/federation/mcp-protocol.d.ts +1 -1
  94. package/dist/federation/mcp-protocol.js +1 -1
  95. package/dist/federation/ports.d.ts +2 -2
  96. package/dist/federation/refusal-notice.d.ts +1 -1
  97. package/dist/federation/refusal-notice.js +1 -1
  98. package/dist/federation/registrations.d.ts +6 -6
  99. package/dist/federation/registrations.js +1 -1
  100. package/dist/federation/reload.js +37 -36
  101. package/dist/federation/stdio/adapter.stdio.js +27 -20
  102. package/dist/federation/stdio/default-connect.d.ts +2 -5
  103. package/dist/federation/stdio/default-connect.js +2 -1
  104. package/dist/federation/stdio/index.d.ts +1 -0
  105. package/dist/federation/stdio/index.js +1 -0
  106. package/dist/federation/stdio/smoke.d.ts +62 -0
  107. package/dist/federation/stdio/smoke.js +156 -0
  108. package/dist/federation/trust.d.ts +2 -2
  109. package/dist/federation/trust.js +4 -4
  110. package/dist/index.d.ts +3 -4
  111. package/dist/index.js +1 -1
  112. package/dist/server/adapters/sdk-server.d.ts +88 -0
  113. package/dist/server/adapters/sdk-server.js +27 -0
  114. package/dist/server/{sdk-transport.d.ts → adapters/sdk-transport.d.ts} +3 -3
  115. package/dist/server/{sdk-transport.js → adapters/sdk-transport.js} +2 -2
  116. package/dist/server/adapters/sdk-wire.d.ts +16 -0
  117. package/dist/server/adapters/sdk-wire.js +16 -0
  118. package/dist/server/call-progress.d.ts +48 -0
  119. package/dist/server/call-progress.js +60 -0
  120. package/dist/server/http-tool-server.adapter.js +209 -196
  121. package/dist/server/index.d.ts +1 -0
  122. package/dist/server/loopback-fetch.d.ts +5 -0
  123. package/dist/server/loopback-fetch.js +48 -0
  124. package/dist/server/resource-protocol.d.ts +1 -1
  125. package/dist/server/run-tool-host.js +3 -1
  126. package/dist/server/stdio-hosting.d.ts +8 -12
  127. package/dist/server/stdio-hosting.js +135 -126
  128. package/dist/server/tool-arguments.d.ts +9 -1
  129. package/dist/server/tool-arguments.js +18 -4
  130. package/dist/server/tool-protocol.d.ts +15 -3
  131. package/dist/server/tool-protocol.js +18 -21
  132. package/dist/server/tool-result-pages.js +37 -28
  133. package/dist/server/tool-server.d.ts +8 -46
  134. package/dist/server/tool-server.js +138 -128
  135. package/dist/server/tools/component-catalog-tools.d.ts +2 -2
  136. package/dist/server/tools/component-catalog-tools.js +2 -2
  137. package/dist/server/tools/delegated-tool.js +74 -57
  138. package/dist/server/tools/run-tools.d.ts +5 -5
  139. package/dist/server/tools/run-tools.js +5 -5
  140. package/dist/server/tools/tool-catalog-tools.d.ts +2 -2
  141. package/dist/server/tools/tool-catalog-tools.js +35 -12
  142. package/package.json +8 -9
  143. package/dist/core/oauth.d.ts +0 -274
  144. package/dist/core/oauth.js +0 -667
  145. package/dist/core/secure-write.d.ts +0 -17
  146. package/dist/core/secure-write.js +0 -72
@@ -0,0 +1,30 @@
1
+ import path from 'node:path';
2
+ export const planVibeInstall = ({ spec, ctx: { home, serverName } }) => ({
3
+ kind: 'manual',
4
+ slug: 'vibe',
5
+ format: 'toml',
6
+ configPath: path.join(home, '.vibe', 'config.toml'),
7
+ snippet: vibeTomlSnippet({ spec, name: serverName }),
8
+ reason: 'Vibe uses a TOML array-of-tables ([[mcp_servers]]); ' +
9
+ 'its exact schema is unverified, so append this block by hand ' +
10
+ 'to avoid corrupting an existing config.',
11
+ });
12
+ /** Render the launch command and environment as a Vibe TOML snippet without I/O.
13
+ * @complexity O(n) time and space in the serialized launch spec length.
14
+ */
15
+ function vibeTomlSnippet({ spec, name }, _options = {}) {
16
+ const argsToml = `[${spec.args.map((a) => JSON.stringify(a)).join(', ')}]`;
17
+ const lines = [
18
+ '[[mcp_servers]]',
19
+ `name = ${JSON.stringify(name)}`,
20
+ 'transport = "stdio"',
21
+ `command = ${JSON.stringify(spec.command)}`,
22
+ `args = ${argsToml}`,
23
+ ];
24
+ if (Object.keys(spec.env).length > 0) {
25
+ const envToml = Object.entries(spec.env).map(([key, value]) => `${JSON.stringify(key)} = ${JSON.stringify(value)}`).join(', ');
26
+ lines.push(`env = { ${envToml} }`);
27
+ }
28
+ return lines.join('\n');
29
+ }
30
+ //# sourceMappingURL=install.js.map
package/dist/bin/serve.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * The bootable `jini-mcp` binary (`package.json`'s `"bin": { "jini-mcp": "./dist/bin/serve.js" }`)
6
6
  * — the real executable entry point gap 3's MCP-callback continuation-transport spike needed and
7
- * did not have (see `packages/daemon/archived provenance ledger`'s "run/chat orchestration gap 3, part 1"
7
+ * did not have (see `070311a07^:packages/daemon/source-map.md`'s "run/chat orchestration gap 3, part 1"
8
8
  * addition, and this package's own dated section in `archived provenance ledger`). `../server/tool-server.js`'s
9
9
  * `createMcpToolServer` was always designed to run as *this process's own* stdio — meant to be a
10
10
  * script a client (Claude Code) spawns as its own child subprocess and talks to over that child's
@@ -38,9 +38,10 @@
38
38
  */
39
39
  import { existsSync, realpathSync } from 'node:fs';
40
40
  import { fileURLToPath } from 'node:url';
41
- import { isLoopbackHostname } from '@jini-ai/platform/net';
41
+ import { isLoopbackHostname } from '@jini-ai/core/net';
42
42
  import { createMcpToolServer as createMcpToolServerDefault } from '../server/tool-server.js';
43
43
  import { assembleRunToolHost } from '../server/run-tool-host.js';
44
+ import { createLoopbackFetch } from '../server/loopback-fetch.js';
44
45
  /** The one run this process is scoped to for its entire lifetime. Set by the spawning daemon, never by the MCP client. */
45
46
  export const RUN_ID_ENV_VAR = 'JINI_RUN_ID';
46
47
  /** Checked (only) when resolving the daemon HTTP base URL — see `resolveDaemonUrl`'s own docs; matches the CLI entry point's identically-named constant. */
@@ -132,11 +133,12 @@ export async function serve(_requiredArgs, deps = {}) {
132
133
  const messageRelay = resolveMessageRelay({ env, runId, writeErr, exit });
133
134
  try {
134
135
  const diagnosticToolIds = parseLaunchToolIds({ env, key: 'JINI_DIAGNOSTIC_TOOL_IDS' });
136
+ // The daemon call has no header wait of its own (global fetch gives up after 300 s); the caller's signal and each route's deadline still end it.
135
137
  // Absent credential => no `authHeaders` at all => byte-identical request headers to before this
136
138
  // env var existed. See DAEMON_TOKEN_ENV_VAR's doc for why an unset value is not a startup failure.
137
139
  const assembled = await assembleRunToolHost({ runId, resolveBaseUrl }, {
138
140
  ...delegatedGatewayOptions,
139
- ...definedOnly({ credential: env[DAEMON_TOKEN_ENV_VAR], fetchImpl: deps.fetchImpl,
141
+ ...definedOnly({ credential: env[DAEMON_TOKEN_ENV_VAR], fetchImpl: deps.fetchImpl ?? createLoopbackFetch(),
140
142
  messageRelayNonce: messageRelay?.nonce }),
141
143
  startupToolIds: parseLaunchToolIds({ env, key: STARTUP_TOOL_IDS_ENV_VAR }),
142
144
  ...(diagnosticToolIds.length ? { diagnosticToolIds } : {}),
@@ -55,15 +55,19 @@ export function createMcpIdleExitController({ idleMs, onIdle, }, { timers = defa
55
55
  }, delayMs: effectiveIdleMs });
56
56
  };
57
57
  schedule();
58
+ return idleControllerOperations({ schedule, clear, isDisposed: () => disposed,
59
+ dispose: () => { disposed = true; }, changeInFlight: delta => (inFlight += delta) });
60
+ }
61
+ function idleControllerOperations(state) {
58
62
  return {
59
63
  noteActivity(_required) {
60
- schedule();
64
+ state.schedule();
61
65
  },
62
66
  async trackRequest({ fn }) {
63
- if (disposed) {
67
+ if (state.isDisposed()) {
64
68
  return fn({});
65
69
  }
66
- inFlight += 1;
70
+ state.changeInFlight(1);
67
71
  // Deliberately does NOT call `schedule()` here (SEC-RB-011): a request
68
72
  // starting while the timer is already running doesn't need to reset
69
73
  // the deadline — the timer, if it fires mid-flight, already re-checks
@@ -75,15 +79,15 @@ export function createMcpIdleExitController({ idleMs, onIdle, }, { timers = defa
75
79
  return await fn({});
76
80
  }
77
81
  finally {
78
- inFlight -= 1;
82
+ const inFlight = state.changeInFlight(-1);
79
83
  if (inFlight === 0) {
80
- schedule();
84
+ state.schedule();
81
85
  }
82
86
  }
83
87
  },
84
88
  dispose(_required) {
85
- disposed = true;
86
- clear();
89
+ state.dispose();
90
+ state.clear();
87
91
  },
88
92
  };
89
93
  }
@@ -0,0 +1,21 @@
1
+ import type { McpServerConfig } from '../config.js';
2
+ /**
3
+ * Project-cwd `.mcp.json` shape that Claude Code auto-loads on spawn (the
4
+ * same format Claude Desktop and Cursor use). Returns null when the user
5
+ * has no enabled servers — in that case the caller should NOT write the
6
+ * file (and should clean up any stale one).
7
+ *
8
+ * `tokens` is an optional map of `serverId -> bearer access token`, used
9
+ * for HTTP/SSE servers that completed the daemon's web OAuth flow. When a
10
+ * token is present we inject `Authorization: Bearer <token>` into the
11
+ * server's headers — this is what bypasses the per-spawn `mcp-remote`
12
+ * dance and lets Claude Code talk directly to the upstream MCP using
13
+ * pre-authenticated credentials. User-supplied headers always win on
14
+ * conflict so they can pin a specific token if they really want to.
15
+ */
16
+ export declare function buildClaudeMcpJson({ servers }: {
17
+ servers: McpServerConfig[];
18
+ }, { tokens }?: {
19
+ tokens?: Record<string, string>;
20
+ }): unknown | null;
21
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,29 @@
1
+ import { nonEmptyField, remoteHeadersField } from '../config-shared.js';
2
+ /**
3
+ * Project-cwd `.mcp.json` shape that Claude Code auto-loads on spawn (the
4
+ * same format Claude Desktop and Cursor use). Returns null when the user
5
+ * has no enabled servers — in that case the caller should NOT write the
6
+ * file (and should clean up any stale one).
7
+ *
8
+ * `tokens` is an optional map of `serverId -> bearer access token`, used
9
+ * for HTTP/SSE servers that completed the daemon's web OAuth flow. When a
10
+ * token is present we inject `Authorization: Bearer <token>` into the
11
+ * server's headers — this is what bypasses the per-spawn `mcp-remote`
12
+ * dance and lets Claude Code talk directly to the upstream MCP using
13
+ * pre-authenticated credentials. User-supplied headers always win on
14
+ * conflict so they can pin a specific token if they really want to.
15
+ */
16
+ export function buildClaudeMcpJson({ servers }, { tokens = {} } = {}) {
17
+ const enabled = servers.filter((s) => s.enabled);
18
+ if (enabled.length === 0)
19
+ return null;
20
+ const out = {};
21
+ for (const s of enabled) {
22
+ out[s.id] = s.transport === 'stdio'
23
+ ? { command: s.command, ...nonEmptyField({ key: 'args', value: s.args }), ...nonEmptyField({ key: 'env', value: s.env }) }
24
+ // type: 'sse' | 'http'
25
+ : { type: s.transport, url: s.url, ...remoteHeadersField({ server: s, tokens }) };
26
+ }
27
+ return { mcpServers: out };
28
+ }
29
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,27 @@
1
+ import type { McpAuthMode, McpServerConfig } from './config.js';
2
+ export declare function isPlainObject(required: {
3
+ v: unknown;
4
+ }, _optional?: Record<string, never>): required is {
5
+ v: Record<string, unknown>;
6
+ };
7
+ /**
8
+ * Infer the appropriate `McpAuthMode` for a given server URL.
9
+ * Returns `'none'` for loopback targets (localhost, 127.x.x.x, ::1)
10
+ * and `'oauth'` for everything else, including when `rawUrl` is absent or unparseable.
11
+ * @param rawUrl The server URL string to inspect, if any.
12
+ * @returns The inferred `McpAuthMode`.
13
+ */
14
+ export declare function inferMcpAuthModeForUrl({ rawUrl }: {
15
+ rawUrl: string | undefined;
16
+ }): McpAuthMode;
17
+ /** `{ [key]: value }` when `value` has at least one element/key, else `{}` — for spreading optional fields. */
18
+ export declare function nonEmptyField({ key, value }: {
19
+ key: string;
20
+ value: object | undefined;
21
+ }): Record<string, unknown>;
22
+ /** `{ headers }` for a remote server (user headers + its own stored OAuth bearer), or `{}` when empty. */
23
+ export declare function remoteHeadersField({ server, tokens }: {
24
+ server: McpServerConfig;
25
+ tokens: Record<string, string>;
26
+ }, _options?: {}): Record<string, unknown>;
27
+ //# sourceMappingURL=config-shared.d.ts.map
@@ -0,0 +1,64 @@
1
+ import { isLoopbackHostname } from '@jini-ai/core/net';
2
+ export function isPlainObject(required, _optional = {}) {
3
+ const { v } = required;
4
+ return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
5
+ }
6
+ // The shared classifier receives the URL parser's canonical hostname; IPv4-mapped
7
+ // IPv6 is deliberately not a loopback exception for default authentication.
8
+ /**
9
+ * Infer the appropriate `McpAuthMode` for a given server URL.
10
+ * Returns `'none'` for loopback targets (localhost, 127.x.x.x, ::1)
11
+ * and `'oauth'` for everything else, including when `rawUrl` is absent or unparseable.
12
+ * @param rawUrl The server URL string to inspect, if any.
13
+ * @returns The inferred `McpAuthMode`.
14
+ */
15
+ export function inferMcpAuthModeForUrl({ rawUrl }) {
16
+ if (!rawUrl)
17
+ return 'oauth';
18
+ try {
19
+ return isLoopbackHostname({ hostname: new URL(rawUrl).hostname }) ? 'none' : 'oauth';
20
+ }
21
+ catch {
22
+ return 'oauth';
23
+ }
24
+ }
25
+ // Only ever invoked for http/sse servers (the callers gate on transport), so
26
+ // there is no stdio short-circuit here — the token merge just needs the
27
+ // effective auth mode for a remote server.
28
+ function effectiveMcpAuthMode(server) {
29
+ return server.authMode ?? inferMcpAuthModeForUrl({ rawUrl: server.url });
30
+ }
31
+ /** `{ [key]: value }` when `value` has at least one element/key, else `{}` — for spreading optional fields. */
32
+ export function nonEmptyField({ key, value }) {
33
+ return value && Object.keys(value).length > 0 ? { [key]: value } : {};
34
+ }
35
+ /** `{ headers }` for a remote server (user headers + its own stored OAuth bearer), or `{}` when empty. */
36
+ export function remoteHeadersField({ server, tokens }, _options = {}) {
37
+ const bearer = effectiveMcpAuthMode(server) === 'oauth' && Object.hasOwn(tokens, server.id) ? tokens[server.id] : undefined;
38
+ return nonEmptyField({ key: 'headers', value: mergeAuthHeader(server.headers, bearer) });
39
+ }
40
+ /** Build a headers object that includes the daemon-issued bearer token when
41
+ * the user hasn't already supplied a NON-EMPTY Authorization header. A
42
+ * blank Authorization (empty string / whitespace only) is treated as
43
+ * "not pinned" — historically the template UI persisted empty values from
44
+ * unfilled fields, and we never want a blank Authorization to suppress a
45
+ * valid OAuth Bearer (the upstream MCP would refuse the connection and
46
+ * fall back to its in-tool re-auth dance). Real user-pinned values still
47
+ * win so manually-set PATs aren't silently overwritten. */
48
+ function mergeAuthHeader(existing, bearer) {
49
+ const merged = {};
50
+ let userAuth = false;
51
+ for (const [k, v] of Object.entries(existing ?? {})) {
52
+ const isAuth = k.toLowerCase() === 'authorization';
53
+ // empty / whitespace authorization is ignored, NOT carried through
54
+ if (isAuth && (typeof v !== 'string' || v.trim() === ''))
55
+ continue;
56
+ userAuth ||= isAuth;
57
+ merged[k] = v;
58
+ }
59
+ if (bearer && !userAuth) {
60
+ merged['Authorization'] = `Bearer ${bearer}`;
61
+ }
62
+ return merged;
63
+ }
64
+ //# sourceMappingURL=config-shared.js.map
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @module @jini-ai/mcp/core/config
3
+ * Config schema + on-disk store for the external MCP servers the daemon connects
4
+ * to as a client, plus the per-agent config builders (Claude `.mcp.json`, ACP
5
+ * `mcpServers`, OpenCode) that hand those servers to a launching agent. Part of
6
+ * the MCP `core` kernel; depends on no sibling subdirectory.
7
+ */
8
+ import { type Logger } from '@jini-ai/core/primitives';
9
+ import type { AtomicFileWriterPort } from '@jini-ai/core/contracts/runtime';
10
+ export { inferMcpAuthModeForUrl } from './config-shared.js';
11
+ export { buildClaudeMcpJson } from './claude/config.js';
12
+ export { buildOpenCodeMcpConfigContent, type OpenCodeConfigBuildOptions } from './opencode/config.js';
1
13
  /** Wire-level transport discriminator for how the daemon connects to an external MCP server. */
2
14
  export type McpTransport = 'stdio' | 'sse' | 'http';
3
15
  /** Authentication mode for remote MCP servers: `'none'` for local/loopback targets, `'oauth'` for remote ones. */
@@ -22,32 +34,55 @@ export interface McpServerConfig {
22
34
  export interface McpConfig {
23
35
  servers: McpServerConfig[];
24
36
  }
25
- /** Text I/O boundary; secret writes must be atomic and owner-only from creation. */
26
- export interface McpConfigFilesystemPort {
37
+ export interface McpConfigFilesPort {
27
38
  readText(args: {
28
39
  filePath: string;
29
40
  }): Promise<string>;
30
- writeSecretText(args: {
31
- filePath: string;
32
- contents: string;
33
- }): Promise<void>;
41
+ readonly writer: Pick<AtomicFileWriterPort, 'writeText'>;
34
42
  }
35
- /**
36
- * Infer the appropriate `McpAuthMode` for a given server URL.
37
- * Returns `'none'` for loopback targets (localhost, 127.x.x.x, ::1)
38
- * and `'oauth'` for everything else, including when `rawUrl` is absent or unparseable.
39
- * @param rawUrl The server URL string to inspect, if any.
40
- * @returns The inferred `McpAuthMode`.
43
+ /** Text I/O boundary; secret writes must be atomic and owner-only from creation. */
44
+ /** Shared atomic secret persistence (CR-006 / SEC-RB-002).
45
+ * The previous pattern in each of those stores wrote the temp file with
46
+ * default permissions and either never restricted it (config, OAuth client
47
+ * cache) or `chmod(0600)`'d it *after* the atomic rename and silently
48
+ * continued when the chmod failed (tokens) — both leave a window where the
49
+ * file exists world/group-readable, and the latter makes the "protection"
50
+ * advisory rather than enforced. The platform writer instead:
51
+ *
52
+ * 1. Creates the temp file *exclusively* (`wx`) with mode 0600 supplied to
53
+ * the same `open()`/`writeFile()` call that creates it — POSIX applies
54
+ * the requested mode atomically at creation time, so there is no
55
+ * window where the file exists with a broader mode. Creation-mode enforcement
56
+ * follows the existing prompt-file precedent; the shared writer also reapplies
57
+ * 0600 before checking the mode and flushing the file, never after rename.
58
+ * 2. On POSIX platforms, verifies the on-disk mode actually landed as
59
+ * owner-only before renaming into place, and fails closed — removing
60
+ * the temp file and throwing — if it did not (e.g. an unusual umask or
61
+ * a filesystem that doesn't honor `mode`).
62
+ * 3. Skips that verification on `win32`: Windows has no POSIX permission-
63
+ * bit model (`mode` there only toggles the read-only attribute), so
64
+ * there is nothing meaningful to enforce or fail closed on.
65
+ * 4. Flushes file content before rename and the parent directory after it. A directory
66
+ * flush can fail after replacement; it is reported rather than silently ignored.
67
+ *
41
68
  */
42
- export declare function inferMcpAuthModeForUrl({ rawUrl }: {
43
- rawUrl: string | undefined;
44
- }): McpAuthMode;
69
+ export declare const MCP_SECRET_WRITE_OPTIONS: {
70
+ readonly mode: 384;
71
+ readonly verifyOwnerOnly: true;
72
+ readonly createParent: true;
73
+ };
74
+ /** Adapt secret text to the atomic writer with MCP's owner-only policy; writer errors propagate. */
75
+ export declare function writeSecretText({ files, filePath, contents }: {
76
+ files: McpConfigFilesPort;
77
+ filePath: string;
78
+ contents: string;
79
+ }, _optional?: Record<string, never>): Promise<void>;
45
80
  /**
46
81
  * Validate a single user-supplied entry. Drops invalid fields so a typo in
47
82
  * one server doesn't tank the whole config. Returns null when the entry is
48
83
  * unsalvageable (no id, or no transport-required fields).
49
84
  */
50
- export declare function sanitizeMcpServer({ raw }: {
85
+ export declare function sanitizeMcpServer({ raw: value }: {
51
86
  raw: unknown;
52
87
  }): McpServerConfig | null;
53
88
  /**
@@ -57,7 +92,7 @@ export declare function sanitizeMcpServer({ raw }: {
57
92
  * @param raw The raw parsed JSON to sanitize.
58
93
  * @returns A clean `McpConfig` guaranteed to have only valid, unique server entries.
59
94
  */
60
- export declare function sanitizeMcpConfig({ raw }: {
95
+ export declare function sanitizeMcpConfig({ raw: value }: {
61
96
  raw: unknown;
62
97
  }): McpConfig;
63
98
  /**
@@ -66,10 +101,11 @@ export declare function sanitizeMcpConfig({ raw }: {
66
101
  * @param dataDir The resolved runtime data directory.
67
102
  * @returns The sanitized `McpConfig`, never rejects on missing-file or corrupt-JSON.
68
103
  */
69
- export declare function readMcpConfig({ dataDir }: {
104
+ export declare function readMcpConfig({ dataDir, files }: {
70
105
  dataDir: string;
71
- }, { filesystem }?: {
72
- filesystem?: McpConfigFilesystemPort;
106
+ files: McpConfigFilesPort;
107
+ }, { report }?: {
108
+ report?: Pick<Logger, 'error'>;
73
109
  }): Promise<McpConfig>;
74
110
  /**
75
111
  * Sanitize and atomically write the MCP config to `<dataDir>/mcp-config.json`.
@@ -78,18 +114,17 @@ export declare function readMcpConfig({ dataDir }: {
78
114
  * being written. This file may carry environment variables and
79
115
  * `Authorization` header values (API keys, bearer tokens — see
80
116
  * `McpServerConfig.env`/`.headers`), so it is written with owner-only
81
- * (0600) permissions from the very first byte via `writeFileAtomicAsync`
117
+ * (0600) permissions from the very first byte via the injected atomic writer
82
118
  * rather than a post-rename chmod (CR-006 / SEC-RB-002).
83
119
  * @param dataDir The resolved runtime data directory.
84
120
  * @param body The raw config body to sanitize and persist.
85
121
  * @returns The sanitized `McpConfig` that was written to disk.
86
122
  */
87
- export declare function writeMcpConfig({ dataDir, body }: {
123
+ export declare function writeMcpConfig({ dataDir, body, files }: {
88
124
  dataDir: string;
89
125
  body: unknown;
90
- }, { filesystem }?: {
91
- filesystem?: McpConfigFilesystemPort;
92
- }): Promise<McpConfig>;
126
+ files: McpConfigFilesPort;
127
+ }, _optional?: Record<string, never>): Promise<McpConfig>;
93
128
  /**
94
129
  * True when `cwd` is a daemon-managed project directory under `projectsDir`
95
130
  * (= safe to write `.mcp.json` into without risk of clobbering a user-owned
@@ -112,25 +147,6 @@ export declare function isManagedProjectCwd({ cwd, projectsDir }: {
112
147
  filePath: string;
113
148
  }) => string;
114
149
  }): boolean;
115
- /**
116
- * Project-cwd `.mcp.json` shape that Claude Code auto-loads on spawn (the
117
- * same format Claude Desktop and Cursor use). Returns null when the user
118
- * has no enabled servers — in that case the caller should NOT write the
119
- * file (and should clean up any stale one).
120
- *
121
- * `tokens` is an optional map of `serverId -> bearer access token`, used
122
- * for HTTP/SSE servers that completed the daemon's web OAuth flow. When a
123
- * token is present we inject `Authorization: Bearer <token>` into the
124
- * server's headers — this is what bypasses the per-spawn `mcp-remote`
125
- * dance and lets Claude Code talk directly to the upstream MCP using
126
- * pre-authenticated credentials. User-supplied headers always win on
127
- * conflict so they can pin a specific token if they really want to.
128
- */
129
- export declare function buildClaudeMcpJson({ servers }: {
130
- servers: McpServerConfig[];
131
- }, { tokens }?: {
132
- tokens?: Record<string, string>;
133
- }): unknown | null;
134
150
  /**
135
151
  * Convert user-configured external MCP servers into the ACP `mcpServers`
136
152
  * shape that stdio-capable ACP agents accept.
@@ -156,41 +172,4 @@ export interface AcpMcpServer {
156
172
  export declare function buildAcpMcpServers({ servers }: {
157
173
  servers: McpServerConfig[];
158
174
  }): AcpMcpServer[];
159
- /**
160
- * OpenCode merges its config from multiple sources at boot — global
161
- * `~/.config/opencode/opencode.json`, the `OPENCODE_CONFIG` file path, the
162
- * project `opencode.json`, and the `OPENCODE_CONFIG_CONTENT` env var (an
163
- * inline JSON string). The env-var path is what lets a launcher hand servers
164
- * to a single `opencode run` invocation without writing into the user's
165
- * global config or leaving a temp file around on crash. We also use the same
166
- * payload to grant `external_directory` access to launcher-selected absolute
167
- * paths (project cwd, staged skill dirs, etc.) so headless OpenCode runs do
168
- * not auto-reject them.
169
- *
170
- * Returns `null` when nothing would be emitted — the caller must NOT set
171
- * `OPENCODE_CONFIG_CONTENT` to `null`/empty in that case, because doing so
172
- * would override the user's saved global config with an empty object. A
173
- * null return means "leave the env untouched and let OpenCode read the
174
- * user's home-dir config as-is."
175
- *
176
- * The OAuth Bearer merge mirrors `buildClaudeMcpJson` so a remote MCP
177
- * server the daemon already authenticated against works the same way for
178
- * OpenCode users without forcing them to re-authenticate inside OpenCode.
179
- */
180
- /** Options for `buildOpenCodeMcpConfigContent`. */
181
- export interface OpenCodeConfigBuildOptions {
182
- /** Access tokens keyed by server id. */
183
- tokens?: Record<string, string>;
184
- /** Resolves symlinks for permission allowlists. */
185
- resolvePath?: (args: {
186
- filePath: string;
187
- }) => string;
188
- /** Absolute filesystem paths OpenCode's `external_directory` permission should allow. */
189
- allowedDirectories?: string[];
190
- /** Additional top-level keys merged into the emitted config object (e.g. `provider`). */
191
- extraConfig?: Record<string, unknown>;
192
- }
193
- export declare function buildOpenCodeMcpConfigContent({ servers }: {
194
- servers: McpServerConfig[];
195
- }, options?: OpenCodeConfigBuildOptions): string | null;
196
175
  //# sourceMappingURL=config.d.ts.map