@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.
Files changed (142) 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
@@ -1,5 +1,6 @@
1
+ import type { SealedSecret } from "@jini-ai/core/contracts/vault";
1
2
  import type { ISODateTime, UUID } from "@jini-ai/core/primitives";
2
- import type { ExternalMcpAccessUpdate, ExternalMcpServerRecord, ExternalMcpServerRepoPort } from "@jini-ai/core/contracts/hosted-mcp";
3
+ import type { ExternalMcpAccessUpdate, ExternalMcpOAuthRuntimePatch, ExternalMcpReplacedSecrets, ExternalMcpServerKey, ExternalMcpServerRecord, ExternalMcpServerRepoPort } from "@jini-ai/core/contracts/hosted-mcp";
3
4
  import type { HostedMcpVaultPorts } from "./store-ports.js";
4
5
  /** @agent-note A test/first-adapter repository. The host binds `vault.createMemoryRepo` (a fresh, empty host in-memory vault repo per call) and `vaultErrors` once; the store using this repository must import envelopes from the same `./vault.js` instance. Writes are serialized on one queue, so lease CAS and access CAS are indivisible per instance. */
5
6
  export declare class InMemoryExternalMcpServerRepo implements ExternalMcpServerRepoPort {
@@ -18,6 +19,30 @@ export declare class InMemoryExternalMcpServerRepo implements ExternalMcpServerR
18
19
  serverId: string;
19
20
  }): Promise<ExternalMcpServerRecord | null>;
20
21
  upsert(record: ExternalMcpServerRecord): Promise<void>;
22
+ /** Creates the row at version 1; `false` and nothing written when the key is taken.
23
+ * @complexity O(1) row lookup plus the bounded two-envelope commit. */
24
+ insert(required: {
25
+ readonly record: ExternalMcpServerRecord;
26
+ }): Promise<boolean>;
27
+ /** The edit write: the version AND both credential pointers are compared in the same queued step
28
+ * that writes, so nothing can land between the compare and the write.
29
+ * @complexity O(1) row lookup plus the bounded two-envelope commit. */
30
+ updateIfVersion(required: {
31
+ readonly record: ExternalMcpServerRecord;
32
+ readonly expectedVersion: number;
33
+ readonly replaces: ExternalMcpReplacedSecrets;
34
+ }): Promise<boolean>;
35
+ /** The runtime write: only the sealed-OAuth pointer and its status/expiry/lease columns change,
36
+ * and only while the stored credential is still the one the caller read. `version` is untouched.
37
+ * @complexity O(1) row lookup plus the bounded two-envelope commit. */
38
+ updateOAuthRuntime(required: {
39
+ readonly key: ExternalMcpServerKey;
40
+ readonly expectedSealedOAuth: SealedSecret | null;
41
+ readonly patch: ExternalMcpOAuthRuntimePatch;
42
+ }): Promise<boolean>;
43
+ private pointerId;
44
+ /** Writes `record` and its envelopes as one unit; runs inside the write queue. */
45
+ private commit;
21
46
  /** The existing write queue makes snapshot comparison and access replacement indivisible.
22
47
  * No vault operation runs, so concurrent OAuth refresh payloads remain exactly as stored.
23
48
  * @complexity O(a+w) bounded grant bytes, O(1) row lookup and replacement.
@@ -69,29 +69,78 @@ export class InMemoryExternalMcpServerRepo {
69
69
  return record ? this.hydrate({ record }) : null;
70
70
  }
71
71
  async upsert(record) {
72
- await this.write(async () => {
73
- const key = keyOf(record.workspaceId, record.serverId);
74
- const previous = this.rows.get(key);
75
- // Stage a fresh Jini memory repository: failures leave both payloads and the row untouched.
76
- // Only this server's two envelopes are copied, so a save is bounded independently of roster size.
77
- const repo = await this.stage({ previous });
78
- const ids = {
79
- "mcp-env": await persistExternalMcpVaultEnvelope({ repo, sealed: record.sealedEnv, identity: record, kind: "mcp-env", vaultErrors: this.ports.vaultErrors }),
80
- "mcp-auth": await persistExternalMcpVaultEnvelope({ repo, sealed: record.sealedOAuth, identity: record, kind: "mcp-auth", vaultErrors: this.ports.vaultErrors }),
81
- };
82
- for (const { kind, vault } of storedEnvelopes({ record: previous, vaultErrors: this.ports.vaultErrors })) {
83
- if (vault.id !== ids[kind])
84
- await deleteExternalMcpVaultEnvelope({ repo, workspaceId: record.workspaceId, id: vault.id });
85
- }
86
- // Publish both together only after all staged writes/deletes have succeeded.
87
- const saved = { ...record,
88
- sealedEnv: await envelopeAt({ repo, workspaceId: record.workspaceId, id: ids["mcp-env"] }),
89
- sealedOAuth: await envelopeAt({ repo, workspaceId: record.workspaceId, id: ids["mcp-auth"] }),
90
- };
91
- this.vaults.set(key, repo);
92
- this.rows.set(key, saved);
72
+ await this.write(() => this.commit({ record }));
73
+ }
74
+ /** Creates the row at version 1; `false` and nothing written when the key is taken.
75
+ * @complexity O(1) row lookup plus the bounded two-envelope commit. */
76
+ async insert(required) {
77
+ return this.write(async () => {
78
+ const { record } = required;
79
+ if (this.rows.has(keyOf(record.workspaceId, record.serverId)))
80
+ return false;
81
+ await this.commit({ record: { ...record, version: 1 } });
82
+ return true;
93
83
  });
94
84
  }
85
+ /** The edit write: the version AND both credential pointers are compared in the same queued step
86
+ * that writes, so nothing can land between the compare and the write.
87
+ * @complexity O(1) row lookup plus the bounded two-envelope commit. */
88
+ async updateIfVersion(required) {
89
+ return this.write(async () => {
90
+ const { record, expectedVersion, replaces } = required;
91
+ const current = this.rows.get(keyOf(record.workspaceId, record.serverId));
92
+ if (!current || current.version !== expectedVersion)
93
+ return false;
94
+ const sameEnv = this.pointerId({ sealed: replaces.sealedEnv, identity: current, kind: "mcp-env" }) === this.pointerId({ sealed: current.sealedEnv, identity: current, kind: "mcp-env" });
95
+ const sameAuth = this.pointerId({ sealed: replaces.sealedOAuth, identity: current, kind: "mcp-auth" }) === this.pointerId({ sealed: current.sealedOAuth, identity: current, kind: "mcp-auth" });
96
+ if (!sameEnv || !sameAuth)
97
+ return false;
98
+ await this.commit({ record: { ...record, version: expectedVersion + 1 } });
99
+ return true;
100
+ });
101
+ }
102
+ /** The runtime write: only the sealed-OAuth pointer and its status/expiry/lease columns change,
103
+ * and only while the stored credential is still the one the caller read. `version` is untouched.
104
+ * @complexity O(1) row lookup plus the bounded two-envelope commit. */
105
+ async updateOAuthRuntime(required) {
106
+ return this.write(async () => {
107
+ const { key, expectedSealedOAuth, patch } = required;
108
+ const current = this.rows.get(keyOf(key.workspaceId, key.serverId));
109
+ if (!current)
110
+ return false;
111
+ const expectedId = this.pointerId({ sealed: expectedSealedOAuth, identity: current, kind: "mcp-auth" });
112
+ if (expectedId !== this.pointerId({ sealed: current.sealedOAuth, identity: current, kind: "mcp-auth" }))
113
+ return false;
114
+ await this.commit({ record: { ...current, ...patch } });
115
+ return true;
116
+ });
117
+ }
118
+ pointerId({ sealed, identity, kind }) {
119
+ return sealed ? externalMcpVaultRecord({ sealed, identity, kind, vaultErrors: this.ports.vaultErrors }).id : null;
120
+ }
121
+ /** Writes `record` and its envelopes as one unit; runs inside the write queue. */
122
+ async commit({ record }) {
123
+ const key = keyOf(record.workspaceId, record.serverId);
124
+ const previous = this.rows.get(key);
125
+ // Stage a fresh Jini memory repository: failures leave both payloads and the row untouched.
126
+ // Only this server's two envelopes are copied, so a save is bounded independently of roster size.
127
+ const repo = await this.stage({ previous });
128
+ const ids = {
129
+ "mcp-env": await persistExternalMcpVaultEnvelope({ repo, sealed: record.sealedEnv, identity: record, kind: "mcp-env", vaultErrors: this.ports.vaultErrors }),
130
+ "mcp-auth": await persistExternalMcpVaultEnvelope({ repo, sealed: record.sealedOAuth, identity: record, kind: "mcp-auth", vaultErrors: this.ports.vaultErrors }),
131
+ };
132
+ for (const { kind, vault } of storedEnvelopes({ record: previous, vaultErrors: this.ports.vaultErrors })) {
133
+ if (vault.id !== ids[kind])
134
+ await deleteExternalMcpVaultEnvelope({ repo, workspaceId: record.workspaceId, id: vault.id });
135
+ }
136
+ // Publish both together only after all staged writes/deletes have succeeded.
137
+ const saved = { ...record,
138
+ sealedEnv: await envelopeAt({ repo, workspaceId: record.workspaceId, id: ids["mcp-env"] }),
139
+ sealedOAuth: await envelopeAt({ repo, workspaceId: record.workspaceId, id: ids["mcp-auth"] }),
140
+ };
141
+ this.vaults.set(key, repo);
142
+ this.rows.set(key, saved);
143
+ }
95
144
  /** The existing write queue makes snapshot comparison and access replacement indivisible.
96
145
  * No vault operation runs, so concurrent OAuth refresh payloads remain exactly as stored.
97
146
  * @complexity O(a+w) bounded grant bytes, O(1) row lookup and replacement.
@@ -103,7 +152,7 @@ export class InMemoryExternalMcpServerRepo {
103
152
  if (!row || !isDeepStrictEqual(externalMcpAccessSnapshot({ record: row }), input.expected))
104
153
  return false;
105
154
  this.rows.set(key, { ...row, ...input.access, writeGrantsUpdatedByPrincipalId: input.principalId,
106
- writeGrantsUpdatedAt: input.nowIso, updatedAt: input.nowIso });
155
+ writeGrantsUpdatedAt: input.nowIso, updatedAt: input.nowIso, version: row.version + 1 });
107
156
  return true;
108
157
  });
109
158
  }
@@ -0,0 +1,39 @@
1
+ import type { ExternalMcpServerKey, ExternalMcpServerRecord, ExternalMcpServerRepoPort, SaveExternalMcpServerInput } from "@jini-ai/core/contracts/hosted-mcp";
2
+ import type { HostedMcpStorePorts } from "./store-ports.js";
3
+ /**
4
+ * @file The write half of `saveExternalMcpServer` (lost-update design S1, rules M1/M4).
5
+ *
6
+ * A save used to upsert the whole row built from a read made earlier in the same request. It now
7
+ * creates with `insert` and edits with `updateIfVersion`: the compare is in the write, and the basis
8
+ * is the version the person loaded when they sent one (an old screen is refused) or else the version
9
+ * read in this request (which only closes the race between two server calls).
10
+ */
11
+ export type CredentialPorts = Pick<HostedMcpStorePorts, "assertFreeField" | "credential">;
12
+ export declare function assertExternalMcpPlainField(required: {
13
+ value: string;
14
+ field: string;
15
+ }, ports: CredentialPorts): void;
16
+ export declare function assertExternalMcpPlainInput({ input, ports }: {
17
+ input: SaveExternalMcpServerInput;
18
+ ports: CredentialPorts;
19
+ }, _options?: {}): void;
20
+ type SaveRepo = Pick<ExternalMcpServerRepoPort, "findByServerId" | "insert" | "updateIfVersion">;
21
+ /**
22
+ * Reads the stored row, builds the next one and writes it conditionally.
23
+ *
24
+ * @param required.expectedVersion - The version the person loaded; absent means "the version read here".
25
+ * @param required.build - Derives the row to write from the stored row (`null` for a create). It is
26
+ * re-run on a fresh read when the write missed only because a token refresh moved a credential.
27
+ * @returns the row as written, with its new version.
28
+ * @throws {RecordVersionConflictError} when the row changed (or was deleted, or created) after the
29
+ * basis, including a second miss after the one retry.
30
+ * @complexity O(1) writes; at most two reads and two builds.
31
+ */
32
+ export declare function commitExternalMcpSave({ repo, key, expectedVersion, build }: {
33
+ repo: SaveRepo;
34
+ key: ExternalMcpServerKey;
35
+ expectedVersion: number | undefined;
36
+ build: (existing: ExternalMcpServerRecord | null) => Promise<ExternalMcpServerRecord>;
37
+ }, _options?: {}): Promise<ExternalMcpServerRecord>;
38
+ export {};
39
+ //# sourceMappingURL=store.save.d.ts.map
@@ -0,0 +1,63 @@
1
+ import { RecordVersionConflictError } from "@jini-ai/core/optimistic-concurrency";
2
+ import { ExternalMcpValidationError } from "./validation-error.js";
3
+ export function assertExternalMcpPlainField(required, ports) {
4
+ try {
5
+ ports.assertFreeField(required);
6
+ }
7
+ catch (err) {
8
+ if (err instanceof ports.credential.InputError)
9
+ throw new ExternalMcpValidationError(err.message, err.field);
10
+ throw err;
11
+ }
12
+ }
13
+ export function assertExternalMcpPlainInput({ input, ports }, _options = {}) {
14
+ for (const field of ["serverId", "label", "command", "args", "url", "transport", "authMode", "accessTokenEnvName"]) {
15
+ assertExternalMcpPlainField({ value: input[field] ?? "", field }, ports);
16
+ }
17
+ for (const [field, value] of Object.entries(input.oauth ?? {})) {
18
+ if (field !== 'clientSecret' && typeof value === 'string')
19
+ assertExternalMcpPlainField({ value, field: `oauth.${field}` }, ports);
20
+ }
21
+ }
22
+ function conflict({ key, expectedVersion, currentVersion }) {
23
+ return new RecordVersionConflictError({ recordKind: "MCP server", recordId: key.serverId, expectedVersion, currentVersion });
24
+ }
25
+ /** Refuses the save when the row's current version is not the basis the person loaded (no basis: nothing to compare). */
26
+ function assertBasis({ key, expectedVersion, current }) {
27
+ if (expectedVersion === undefined)
28
+ return;
29
+ if ((current?.version ?? 0) !== expectedVersion)
30
+ throw conflict({ key, expectedVersion, currentVersion: current?.version ?? null });
31
+ }
32
+ /** Creates the row when there was none, else replaces it only if its version is still the one read. */
33
+ function writeNext({ repo, record, existing }) {
34
+ if (!existing)
35
+ return repo.insert({ record });
36
+ return repo.updateIfVersion({ record, expectedVersion: existing.version, replaces: { sealedEnv: existing.sealedEnv, sealedOAuth: existing.sealedOAuth } });
37
+ }
38
+ /**
39
+ * Reads the stored row, builds the next one and writes it conditionally.
40
+ *
41
+ * @param required.expectedVersion - The version the person loaded; absent means "the version read here".
42
+ * @param required.build - Derives the row to write from the stored row (`null` for a create). It is
43
+ * re-run on a fresh read when the write missed only because a token refresh moved a credential.
44
+ * @returns the row as written, with its new version.
45
+ * @throws {RecordVersionConflictError} when the row changed (or was deleted, or created) after the
46
+ * basis, including a second miss after the one retry.
47
+ * @complexity O(1) writes; at most two reads and two builds.
48
+ */
49
+ export async function commitExternalMcpSave({ repo, key, expectedVersion, build }, _options = {}) {
50
+ for (let attempt = 0; attempt < 2; attempt += 1) {
51
+ const existing = await repo.findByServerId(key);
52
+ assertBasis({ key, expectedVersion, current: existing });
53
+ const record = await build(existing);
54
+ if (await writeNext({ repo, record, existing }))
55
+ return { ...record, version: (existing?.version ?? 0) + 1 };
56
+ // A miss with the basis still current means a runtime write (a token refresh) or a concurrent
57
+ // internal write moved the row between the read and the write; read again and rebuild once.
58
+ assertBasis({ key, expectedVersion, current: await repo.findByServerId(key) });
59
+ }
60
+ const live = await repo.findByServerId(key);
61
+ throw conflict({ key, expectedVersion: expectedVersion ?? 0, currentVersion: live?.version ?? null });
62
+ }
63
+ //# sourceMappingURL=store.save.js.map
@@ -1,5 +1,6 @@
1
+ import type { ExternalMcpServerRecord, ExternalMcpStoreDeps, ExternalMcpSealedOAuthPayload, SealedExternalMcpOAuth } from "@jini-ai/core/contracts/hosted-mcp";
1
2
  import type { KeyringPort, SealedSecret, SecretSealerPort, VaultMeta, VaultRecord, VaultRepoPort } from "@jini-ai/core/contracts/vault";
2
- import type { HostedMcpVaultPorts } from "./store-ports.js";
3
+ import type { HostedMcpVaultPorts, HostedMcpStorePorts } from "./store-ports.js";
3
4
  /** Expected owner of an envelope: the workspace and the server row it belongs to. */
4
5
  /** @agent-note Supplied by the caller from the row being read or written, never inferred from an envelope. */
5
6
  export type Identity = {
@@ -65,4 +66,81 @@ export declare function deleteExternalMcpVaultEnvelope({ repo, workspaceId, id }
65
66
  workspaceId: string;
66
67
  id: string | null;
67
68
  }, _options?: {}): Promise<void>;
69
+ /** One stored row. `sealedEnv` is null when the server needs no credentials, which is normal. */
70
+ /** Compatibility DTO version for normalized vault envelopes; historical formats live in recovery. */
71
+ export declare const EXTERNAL_MCP_VAULT_VERSION = 1;
72
+ export type ExternalMcpIdentity = {
73
+ workspaceId: string;
74
+ serverId: string;
75
+ };
76
+ export type SealDeps = Pick<ExternalMcpStoreDeps, "sealer" | "keyring"> & HostedMcpStorePorts;
77
+ export type OpenDeps = {
78
+ sealer: Pick<SecretSealerPort, "open">;
79
+ } & HostedMcpStorePorts;
80
+ /** Opens `record`'s sealed env block, or returns `{}` when there is none to open. Split out of
81
+ * {@link resolveExternalMcpConfig} purely to keep that function's complexity under the shop
82
+ * ceiling — a decrypt failure is reported through the same ok/reason shape the caller already
83
+ * threads through, not thrown, since one unreadable server must not abort the whole read. */
84
+ export declare function openExternalMcpEnv(record: Pick<ExternalMcpServerRecord, "sealedEnv" | "workspaceId" | "serverId" | "aadVersion">, deps: OpenDeps): Promise<{
85
+ readonly ok: true;
86
+ readonly env: Record<string, string>;
87
+ } | {
88
+ readonly ok: false;
89
+ readonly reason: string;
90
+ }>;
91
+ /**
92
+ * What the OAuth sealed blob holds.
93
+ *
94
+ * ONE blob rather than a column per secret, for exactly the reason the env block is one blob: every
95
+ * read path wants the whole thing at once, and per-secret sealing would buy nothing and cost N
96
+ * keyring round trips. The consequence is a READ-MODIFY-WRITE rule that every writer must honour —
97
+ * unseal, change one member, reseal — because a writer that seals `{ tokens }` alone silently
98
+ * deletes the operator's client secret.
99
+ *
100
+ * Structurally compatible with the OAuth client's `OAuthTokenSet`, but declared here rather than
101
+ * imported: this is the STORED shape, and it must be able to stay still while the flow module's
102
+ * in-memory type moves.
103
+ */
104
+ /**
105
+ * Schema version of the *plaintext* inside the sealed OAuth blob.
106
+ *
107
+ * Distinct from `oauth_aad_version`, which versions how the blob is BOUND to its row and says
108
+ * nothing about what is inside it. Without this, a field could be added but never renamed, changed,
109
+ * or removed — there would be nothing to branch on at open time, and the only way out would be a
110
+ * migration over live credentials. Stamped at seal; a blob without it predates versioning and is
111
+ * upgraded on read.
112
+ */
113
+ export declare const EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION = 1;
114
+ /**
115
+ * The branching read for a sealed OAuth payload. A missing version is v0 (pre-versioning) and is
116
+ * upgraded in place; a newer version is refused rather than misread, because silently
117
+ * reinterpreting an unknown shape here means handing back a wrong or partial live credential.
118
+ *
119
+ * `schemaVersion` is stripped from the result: it is a wire concern, and a caller that saw it could
120
+ * persist it back into a payload it does not own.
121
+ *
122
+ * The vault's open already refuses a non-object payload, so `parsed` is always an object here.
123
+ *
124
+ * @throws When the payload was written by a newer build than this one understands.
125
+ * @complexity O(1).
126
+ */
127
+ export declare function hydrateExternalMcpOAuthPayload(parsed: Record<string, unknown>): ExternalMcpSealedOAuthPayload;
128
+ /**
129
+ * Opens a row's sealed OAuth blob.
130
+ *
131
+ * @returns `{}` when the row holds none, which is the normal state before a connection is authorized.
132
+ * @throws {ExternalMcpSecretStoreUnconfiguredError} When the blob exists but cannot be opened — a
133
+ * rotated site key or a corrupt row. Distinct from "no blob" on purpose: the caller must not treat a
134
+ * decryption failure as "not connected yet" and start a fresh authorization over a token that is
135
+ * still live at the provider.
136
+ * @complexity O(1) — one unseal.
137
+ */
138
+ /** @agent-note `deps` is the per-call sealer plus the host-bound ports; exactly one `sealer.open` per call. */
139
+ export declare function openExternalMcpOAuthPayload(deps: OpenDeps, record: Pick<ExternalMcpServerRecord, "sealedOAuth" | "workspaceId" | "serverId" | "oauthAadVersion">): Promise<ExternalMcpSealedOAuthPayload>;
140
+ /** @agent-note `deps` is the per-call sealer/keyring plus the host-bound ports; exactly one seal, the envelope is staged for the host repository's transaction. */
141
+ export declare function sealExternalMcpOAuthPayload({ deps, identity, payload }: {
142
+ deps: SealDeps;
143
+ identity: ExternalMcpIdentity;
144
+ payload: ExternalMcpSealedOAuthPayload;
145
+ }, _optional?: Record<string, never>): Promise<SealedExternalMcpOAuth>;
68
146
  //# sourceMappingURL=vault.d.ts.map
@@ -1,3 +1,4 @@
1
+ import { ExternalMcpSecretStoreUnconfiguredError } from "./unconfigured-error.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  const contextKey = Symbol("external-mcp-vault-context");
3
4
  const stagedKey = Symbol("external-mcp-staged");
@@ -103,4 +104,110 @@ export async function deleteExternalMcpVaultEnvelope({ repo, workspaceId, id },
103
104
  if (record)
104
105
  await repo.delete({ workspaceId, id, expectedRevision: record.revision });
105
106
  }
107
+ /** One stored row. `sealedEnv` is null when the server needs no credentials, which is normal. */
108
+ /** Compatibility DTO version for normalized vault envelopes; historical formats live in recovery. */
109
+ export const EXTERNAL_MCP_VAULT_VERSION = 1;
110
+ /** Opens `record`'s sealed env block, or returns `{}` when there is none to open. Split out of
111
+ * {@link resolveExternalMcpConfig} purely to keep that function's complexity under the shop
112
+ * ceiling — a decrypt failure is reported through the same ok/reason shape the caller already
113
+ * threads through, not thrown, since one unreadable server must not abort the whole read. */
114
+ export async function openExternalMcpEnv(record, deps) {
115
+ if (record.sealedEnv === null)
116
+ return { ok: true, env: {} };
117
+ try {
118
+ const env = await openExternalMcpVaultPayload({ sealer: deps.sealer, sealed: record.sealedEnv, identity: record, kind: "mcp-env", ports: deps });
119
+ return { ok: true, env };
120
+ }
121
+ catch {
122
+ // These reasons reach admissions and chat tools. Parser/sealer errors can contain secret plaintext.
123
+ return { ok: false, reason: `stored credentials could not be decrypted — check the site credential store and re-enter them in ${deps.settingsLink}` };
124
+ }
125
+ }
126
+ /**
127
+ * What the OAuth sealed blob holds.
128
+ *
129
+ * ONE blob rather than a column per secret, for exactly the reason the env block is one blob: every
130
+ * read path wants the whole thing at once, and per-secret sealing would buy nothing and cost N
131
+ * keyring round trips. The consequence is a READ-MODIFY-WRITE rule that every writer must honour —
132
+ * unseal, change one member, reseal — because a writer that seals `{ tokens }` alone silently
133
+ * deletes the operator's client secret.
134
+ *
135
+ * Structurally compatible with the OAuth client's `OAuthTokenSet`, but declared here rather than
136
+ * imported: this is the STORED shape, and it must be able to stay still while the flow module's
137
+ * in-memory type moves.
138
+ */
139
+ /**
140
+ * Schema version of the *plaintext* inside the sealed OAuth blob.
141
+ *
142
+ * Distinct from `oauth_aad_version`, which versions how the blob is BOUND to its row and says
143
+ * nothing about what is inside it. Without this, a field could be added but never renamed, changed,
144
+ * or removed — there would be nothing to branch on at open time, and the only way out would be a
145
+ * migration over live credentials. Stamped at seal; a blob without it predates versioning and is
146
+ * upgraded on read.
147
+ */
148
+ export const EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION = 1;
149
+ /**
150
+ * The branching read for a sealed OAuth payload. A missing version is v0 (pre-versioning) and is
151
+ * upgraded in place; a newer version is refused rather than misread, because silently
152
+ * reinterpreting an unknown shape here means handing back a wrong or partial live credential.
153
+ *
154
+ * `schemaVersion` is stripped from the result: it is a wire concern, and a caller that saw it could
155
+ * persist it back into a payload it does not own.
156
+ *
157
+ * The vault's open already refuses a non-object payload, so `parsed` is always an object here.
158
+ *
159
+ * @throws When the payload was written by a newer build than this one understands.
160
+ * @complexity O(1).
161
+ */
162
+ export function hydrateExternalMcpOAuthPayload(parsed) {
163
+ const { schemaVersion, ...rest } = parsed;
164
+ const stored = typeof schemaVersion === "number" ? schemaVersion : 0;
165
+ if (stored > EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION) {
166
+ throw new Error(`external MCP OAuth payload was written at schema version ${stored}, newer than this build understands (${EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION}) — upgrade rather than risk misreading a live credential`);
167
+ }
168
+ // v0 -> v1 added only the discriminator, so the upgrade is a stamp; a later version adds its own
169
+ // branch here rather than a backfill over live credentials.
170
+ return rest;
171
+ }
172
+ /**
173
+ * Opens a row's sealed OAuth blob.
174
+ *
175
+ * @returns `{}` when the row holds none, which is the normal state before a connection is authorized.
176
+ * @throws {ExternalMcpSecretStoreUnconfiguredError} When the blob exists but cannot be opened — a
177
+ * rotated site key or a corrupt row. Distinct from "no blob" on purpose: the caller must not treat a
178
+ * decryption failure as "not connected yet" and start a fresh authorization over a token that is
179
+ * still live at the provider.
180
+ * @complexity O(1) — one unseal.
181
+ */
182
+ /** @agent-note `deps` is the per-call sealer plus the host-bound ports; exactly one `sealer.open` per call. */
183
+ export async function openExternalMcpOAuthPayload(deps, record) {
184
+ if (record.sealedOAuth === null)
185
+ return {};
186
+ let parsed;
187
+ try {
188
+ parsed = await openExternalMcpVaultPayload({ sealer: deps.sealer, sealed: record.sealedOAuth, identity: record, kind: "mcp-auth", ports: deps });
189
+ }
190
+ catch {
191
+ throw new ExternalMcpSecretStoreUnconfiguredError("Stored OAuth credentials could not be decrypted.");
192
+ }
193
+ // Deliberately OUTSIDE the catch above: a version mismatch is not a decryption failure, and must
194
+ // not be swallowed by a caller that treats that error as "not connected yet".
195
+ return hydrateExternalMcpOAuthPayload(parsed);
196
+ }
197
+ /** @agent-note `deps` is the per-call sealer/keyring plus the host-bound ports; exactly one seal, the envelope is staged for the host repository's transaction. */
198
+ export async function sealExternalMcpOAuthPayload({ deps, identity, payload }, _optional = {}) {
199
+ const hasSecret = (payload.clientSecret !== undefined && payload.clientSecret !== "") || payload.tokens !== undefined || Boolean(payload.staticAccessToken);
200
+ if (!hasSecret)
201
+ return { sealedOAuth: null, oauthAadVersion: EXTERNAL_MCP_VAULT_VERSION };
202
+ try {
203
+ const sealedOAuth = await sealExternalMcpVaultPayload({ deps, identity, kind: "mcp-auth",
204
+ // The discriminator remains authenticated inside the payload, never plain metadata.
205
+ payload: JSON.parse(JSON.stringify({ ...payload, schemaVersion: EXTERNAL_MCP_OAUTH_PAYLOAD_VERSION })),
206
+ });
207
+ return { sealedOAuth, oauthAadVersion: EXTERNAL_MCP_VAULT_VERSION };
208
+ }
209
+ catch {
210
+ throw new ExternalMcpSecretStoreUnconfiguredError(deps.credential.messages.storage);
211
+ }
212
+ }
106
213
  //# sourceMappingURL=vault.js.map
@@ -1,6 +1,6 @@
1
1
  /** @agent-note Node entry: values for hosted MCP connections. Types come from `@jini-ai/core/contracts/hosted-mcp`; the host wires these values into its store, plugin and sign-in seams. No other Jini package is imported. */
2
2
  /**
3
- * Both transports are federated. `stdio` is served by `../adapter.stdio.ts` (a local
3
+ * Both transports are federated. `stdio` is served by `packages/mcp/src/federation/stdio/adapter.stdio.ts` (a local
4
4
  * child process); `streamable_http` by `../adapter.http.ts` (a hosted endpoint, with a
5
5
  * bearer header when the row is OAuth- or access-token-authenticated — see `resolveHttpTarget`).
6
6
  * {@link readEnabledExternalMcpConfigs} resolves a hosted row to a `streamable_http` target,
@@ -1,6 +1,6 @@
1
1
  /** @agent-note Node entry: values for hosted MCP connections. Types come from `@jini-ai/core/contracts/hosted-mcp`; the host wires these values into its store, plugin and sign-in seams. No other Jini package is imported. */
2
2
  /**
3
- * Both transports are federated. `stdio` is served by `../adapter.stdio.ts` (a local
3
+ * Both transports are federated. `stdio` is served by `packages/mcp/src/federation/stdio/adapter.stdio.ts` (a local
4
4
  * child process); `streamable_http` by `../adapter.http.ts` (a hosted endpoint, with a
5
5
  * bearer header when the row is OAuth- or access-token-authenticated — see `resolveHttpTarget`).
6
6
  * {@link readEnabledExternalMcpConfigs} resolves a hosted row to a `streamable_http` target,
@@ -8,6 +8,7 @@ export * from "./refusal-notice.js";
8
8
  export * from "./registrations.js";
9
9
  export * from "./bootstrap.js";
10
10
  export * from "./reload.js";
11
+ export * from "./admissions.js";
11
12
  export * from "./tool-approvals.js";
12
13
  export * from "./approvals/index.js";
13
14
  export * from "./messages.js";
@@ -8,6 +8,7 @@ export * from "./refusal-notice.js";
8
8
  export * from "./registrations.js";
9
9
  export * from "./bootstrap.js";
10
10
  export * from "./reload.js";
11
+ export * from "./admissions.js";
11
12
  export * from "./tool-approvals.js";
12
13
  export * from "./approvals/index.js";
13
14
  export * from "./messages.js";
@@ -56,7 +56,7 @@ export declare class McpProtocolError extends Error {
56
56
  * not this). Kept as a distinguishable
57
57
  * subtype, rather than a generic `McpProtocolError` a caller would have to pattern-match on message
58
58
  * text, so a layer that DOES know what "authorization" means for one connection (an OAuth-backed
59
- * row, at `assistant/external-mcp-oauth.ts`) can react to it — without this module, which is
59
+ * row, at a host module) can react to it — without this module, which is
60
60
  * transport-independent protocol plumbing, knowing anything about OAuth.
61
61
  */
62
62
  export declare class McpAuthFailedError extends McpProtocolError {
@@ -41,7 +41,7 @@ export class McpProtocolError extends Error {
41
41
  * not this). Kept as a distinguishable
42
42
  * subtype, rather than a generic `McpProtocolError` a caller would have to pattern-match on message
43
43
  * text, so a layer that DOES know what "authorization" means for one connection (an OAuth-backed
44
- * row, at `assistant/external-mcp-oauth.ts`) can react to it — without this module, which is
44
+ * row, at a host module) can react to it — without this module, which is
45
45
  * transport-independent protocol plumbing, knowing anything about OAuth.
46
46
  */
47
47
  export class McpAuthFailedError extends McpProtocolError {
@@ -205,7 +205,7 @@ export interface McpStdioLaunchSpec {
205
205
  *
206
206
  * Deliberately a plain header bag rather than a token field: this layer should not know that OAuth
207
207
  * exists. It is handed headers and sends them. Which credential produced them, whether it can be
208
- * refreshed, and what to do when it expires are all `assistant/external-mcp-oauth.ts`'s questions,
208
+ * refreshed, and what to do when it expires are all a host module's questions,
209
209
  * decided before a launch spec is ever built.
210
210
  */
211
211
  export interface McpHttpLaunchSpec {
@@ -277,7 +277,7 @@ export interface FederatedCallConfirmationRequest {
277
277
  /**
278
278
  * The hints recorded when the tool was admitted, and where its connection came from — the tool
279
279
  * identity a remembered approval ("Allow for this chat", "Always allow") is pinned to
280
- * (`assistant/external-mcp-tool-approvals.ts`), so a changed server, name or hints asks again.
280
+ * (`packages/mcp/src/federation/tool-approvals.ts`), so a changed server, name or hints asks again.
281
281
  */
282
282
  readonly declaredAnnotations: RemoteToolDescriptor["annotations"] | undefined;
283
283
  readonly origin: FederatedConnectionOrigin | undefined;
@@ -102,7 +102,7 @@ export declare function safeRemoteName({ remoteName, messages }: {
102
102
  * Host wording names the concrete remediation; the reducer must not assume a UI or labels.
103
103
  *
104
104
  * The routine default-deny explanation is included for attempts — see R-B. Needed here
105
- * because ATTEMPT-TIME reporting (`../federated-refusal-diagnosis.ts`) is not enumeration: R-B's
105
+ * because ATTEMPT-TIME reporting (`packages/daemon/src/tool-recovery/federated-refusal.ts`) is not enumeration: R-B's
106
106
  * "not news" argument only holds for a boot-time list the model reads whether it asked or not. A
107
107
  * model that has actually NAMED this exact tool id in a call has, by doing so, already decided it
108
108
  * wants it — telling it why that specific call failed is never the spam R-B guards against.
@@ -28,7 +28,7 @@ export function safeRemoteName({ remoteName, messages }) {
28
28
  * Host wording names the concrete remediation; the reducer must not assume a UI or labels.
29
29
  *
30
30
  * The routine default-deny explanation is included for attempts — see R-B. Needed here
31
- * because ATTEMPT-TIME reporting (`../federated-refusal-diagnosis.ts`) is not enumeration: R-B's
31
+ * because ATTEMPT-TIME reporting (`packages/daemon/src/tool-recovery/federated-refusal.ts`) is not enumeration: R-B's
32
32
  * "not news" argument only holds for a boot-time list the model reads whether it asked or not. A
33
33
  * model that has actually NAMED this exact tool id in a call has, by doing so, already decided it
34
34
  * wants it — telling it why that specific call failed is never the spam R-B guards against.
@@ -22,7 +22,7 @@ import { admitRemoteTools, type AdmittedFederatedTool, type FederatedCallConfirm
22
22
  * see cannot be called. Convergence there is mechanical, and everything that makes the tiers
23
23
  * distinct — namespacing, the operator allowlist, the one-way hint rule, the untrusted-data
24
24
  * envelope, the coarse `admin.integrations.manage` gate — is applied on this side of it, before
25
- * anything is handed over. The audit trail stays separable for free: `tool-executor-audit.ts` wraps
25
+ * anything is handed over. The audit trail stays separable for free: `packages/daemon/src/core/tool-audit.ts` wraps
26
26
  * the executor, so federated attempts are recorded like any other, distinguishable by their
27
27
  * `mcp__` id prefix.
28
28
  *
@@ -79,9 +79,9 @@ export interface FederationDeps {
79
79
  * disabled, narrowed (allowlist or write list), or otherwise changed since admission has no way to
80
80
  * be un-registered (see this doc's own paragraph above), so every one of those must be caught here
81
81
  * instead, on every call, by re-reading the connection's current row.
82
- * `assistant/external-mcp-oauth.ts`'s `createExternalMcpConnectionGate` is the composition root
82
+ * a host module's `createExternalMcpConnectionGate` is the composition root
83
83
  * that does both jobs — the original liveness check plus this revocation re-check
84
- * (`assistant/external-mcp-revocation.ts`'s `rosterRefusalFor`) — and it is NOT a `ToolPolicy` deny:
84
+ * (a host module's `rosterRefusalFor`) — and it is NOT a `ToolPolicy` deny:
85
85
  * see that gate's own doc for why a handler-side refusal, not a policy one, is what lets the model
86
86
  * see WHY rather than a fixed "denied by policy" string.
87
87
  *
@@ -91,9 +91,9 @@ export interface FederationDeps {
91
91
  * @returns `"current-grants-checked"` only when it checked this call against the roster row's current
92
92
  * allowlist and write list; anything else keeps the admitted-grants check ({@link FederatedGateVerdict}).
93
93
  * @throws Whatever the composition root's terminal error is — for OAuth connections,
94
- * `assistant/external-mcp-oauth.ts`'s `ExternalMcpReauthRequiredError`, whose message tells the
94
+ * a host module's `ExternalMcpReauthRequiredError`, whose message tells the
95
95
  * model in words not to retry. For a revoked roster connection,
96
- * `assistant/external-mcp-revocation.ts`'s `ExternalMcpConnectionRevokedError`.
96
+ * a host module's `ExternalMcpConnectionRevokedError`.
97
97
  */
98
98
  readonly assertConnectionUsable?: ((required: {
99
99
  connectionId: string;
@@ -108,7 +108,7 @@ export interface FederationDeps {
108
108
  * shape invites a retry loop).
109
109
  *
110
110
  * A composition root that KNOWS what "authorization" means for this connection (an OAuth-backed
111
- * row, today — `assistant/external-mcp-oauth.ts`) wires this to record the durable state — so
111
+ * row, today — a host module) wires this to record the durable state — so
112
112
  * `assertConnectionUsable`'s cheap row read catches the NEXT call instead of this module reaching
113
113
  * the network again — and to throw the same terminal, non-retryable error that path already uses.
114
114
  * Always throws; this module does not decide what replaces the original error.
@@ -149,7 +149,7 @@ function gateCheckedCurrentGrants({ verdict, config }) {
149
149
  */
150
150
  function assertAdmittedGrants({ deps, config, call }) {
151
151
  const refusal = refusalForAdmittedToolUnderCurrentGrants({ tool: call, grants: config });
152
- const reason = revocationReasonForToolRefusal(refusal);
152
+ const reason = revocationReasonForToolRefusal({ refusal });
153
153
  if (refusal === null || reason === null)
154
154
  return;
155
155
  throw new ToolInputError({ message: `${deps.errorCode}_${reason.toUpperCase().replace(/-/g, "_")}: ` +