@jini-ai/mcp 0.6.23 → 0.7.0

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 (51) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/agent-install/index.d.ts +1 -0
  3. package/dist/agent-install/index.js +1 -0
  4. package/dist/agent-install/install.d.ts +2 -1
  5. package/dist/agent-install/install.js +28 -6
  6. package/dist/agent-install/owned-json-install.d.ts +12 -0
  7. package/dist/agent-install/owned-json-install.js +48 -0
  8. package/dist/federation/adapter.http.d.ts +3 -6
  9. package/dist/federation/bootstrap.js +15 -2
  10. package/dist/federation/config.d.ts +3 -0
  11. package/dist/federation/frozen-grants.d.ts +11 -1
  12. package/dist/federation/frozen-grants.js +14 -0
  13. package/dist/federation/hosted/access.d.ts +92 -0
  14. package/dist/federation/hosted/access.js +116 -0
  15. package/dist/federation/hosted/auth.d.ts +69 -0
  16. package/dist/federation/hosted/auth.js +70 -0
  17. package/dist/federation/hosted/connection-gate.d.ts +83 -0
  18. package/dist/federation/hosted/connection-gate.js +107 -0
  19. package/dist/federation/hosted/index.d.ts +14 -0
  20. package/dist/federation/hosted/index.js +13 -0
  21. package/dist/federation/hosted/projections.d.ts +15 -0
  22. package/dist/federation/hosted/projections.js +15 -0
  23. package/dist/federation/hosted/revocation.d.ts +70 -0
  24. package/dist/federation/hosted/revocation.js +78 -0
  25. package/dist/federation/hosted/store-ports.d.ts +95 -0
  26. package/dist/federation/hosted/store-ports.js +2 -0
  27. package/dist/federation/hosted/store.d.ts +211 -0
  28. package/dist/federation/hosted/store.js +1441 -0
  29. package/dist/federation/hosted/store.memory.d.ts +41 -0
  30. package/dist/federation/hosted/store.memory.js +149 -0
  31. package/dist/federation/hosted/unconfigured-error.d.ts +7 -0
  32. package/dist/federation/hosted/unconfigured-error.js +10 -0
  33. package/dist/federation/hosted/validation-error.d.ts +8 -0
  34. package/dist/federation/hosted/validation-error.js +12 -0
  35. package/dist/federation/hosted/vault.d.ts +68 -0
  36. package/dist/federation/hosted/vault.js +106 -0
  37. package/dist/federation/hosted/vocabulary.d.ts +17 -0
  38. package/dist/federation/hosted/vocabulary.js +17 -0
  39. package/dist/federation/index.d.ts +1 -0
  40. package/dist/federation/index.js +1 -0
  41. package/dist/federation/ports.d.ts +4 -0
  42. package/dist/federation/registrations.js +1 -0
  43. package/dist/federation/stdio/default-connect.js +1 -1
  44. package/dist/index.d.ts +2 -2
  45. package/dist/index.js +2 -2
  46. package/dist/server/{http-tool-server.d.ts → http-tool-server.adapter.d.ts} +1 -1
  47. package/dist/server/{http-tool-server.js → http-tool-server.adapter.js} +1 -1
  48. package/dist/server/index.d.ts +1 -1
  49. package/dist/server/index.js +1 -1
  50. package/dist/server/tool-result-pages.d.ts +1 -1
  51. package/package.json +14 -8
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @file The hosted-MCP auth-mode readers. The store and its consumers import this shared leaf
3
+ * directly, preserving a single vocabulary owner without importing the sign-in or host tool layer.
4
+ *
5
+ * Parameters are declared STRUCTURALLY (the two fields each reader touches) rather than as
6
+ * `Pick<ExternalMcpServerRecord, ...>`: the record type lives in the store, which imports THIS file,
7
+ * so naming it here would close an import cycle. `ExternalMcpServerRecord` satisfies both shapes.
8
+ */
9
+ /**
10
+ * How a server's credentials are obtained — independent of `ExternalMcpTransport`.
11
+ *
12
+ * - `none` — no credentials at all. Common for local developer tooling.
13
+ * - `static_env` — the operator pasted a `KEY=VALUE` block. What this store has always done, and
14
+ * the default for every row that predates this field.
15
+ * - `oauth` — the host holds a token it obtained itself and must keep alive. See
16
+ * the separately wired sign-in service.
17
+ */
18
+ /** @agent-note Saved `authMode` literals; equals core `ExternalMcpAuthMode` both ways (pinned by test). */
19
+ export const EXTERNAL_MCP_AUTH_MODES = ["none", "static_env", "oauth"];
20
+ /**
21
+ * Reads a row's auth mode, defaulting a row written before the column existed.
22
+ *
23
+ * `static_env` is the correct default rather than `none`: every pre-existing row was written by a
24
+ * form whose only credential mechanism was the env block, and a row with an empty block behaves
25
+ * identically under either mode. Defaulting to `none` would silently relabel rows that DO carry a
26
+ * sealed block as credential-free.
27
+ *
28
+ * @complexity O(1).
29
+ */
30
+ /** @agent-note Pure, no I/O; the `static_env` default is the saved-format compatibility rule for rows older than the column. Hosts bind this exact function. */
31
+ export function resolveExternalMcpAuthMode(record) {
32
+ const mode = record.authMode;
33
+ return EXTERNAL_MCP_AUTH_MODES.includes(mode) ? mode : "static_env";
34
+ }
35
+ /**
36
+ * Whether a row holds a `static_env` access token — answered from plaintext columns, never by unsealing.
37
+ *
38
+ * Truthful because a `static_env` row's sealed OAuth blob only ever holds that token: leaving `oauth`
39
+ * clears the client secret and token set (`store.ts`'s `resolveSealedOAuthBlob`),
40
+ * and entering `oauth` never carries this token forward (`openExternalMcpOAuthPayload`'s callers
41
+ * rebuild the payload from `clientSecret`/`tokens` alone).
42
+ *
43
+ * @complexity O(1).
44
+ */
45
+ /** @agent-note Pure, plain-text columns only; never unseals. One of the six `hostedMcpProjections`. */
46
+ export function externalMcpRecordHasStaticAccessToken(record) {
47
+ return resolveExternalMcpAuthMode(record) === "static_env" && Boolean(record.sealedOAuth);
48
+ }
49
+ /**
50
+ * The runtime lifecycle of an OAuth-backed connection.
51
+ *
52
+ * `needs_reauth` is the state that earns its place here. It is deliberately NOT the boot-time "skip
53
+ * this row and report why" path {@link readEnabledExternalMcpConfigs} already uses for a sealed blob
54
+ * that will not decrypt: that is a STORAGE failure, nothing the operator types can fix it, and it is
55
+ * discovered while the daemon starts. `needs_reauth` is an expected RUNTIME lifecycle state — a
56
+ * token expired or was revoked while everything was working — it is exactly operator-actionable, and
57
+ * it must be visible in the admin tab rather than buried in a boot log nobody is reading at the time.
58
+ */
59
+ /** @agent-note Saved `oauthStatus` literals; equals core `ExternalMcpOAuthStatus` both ways. */
60
+ export const EXTERNAL_MCP_OAUTH_STATUSES = ["disconnected", "pending", "connected", "needs_reauth"];
61
+ /** A row's OAuth status, defaulting an absent or unrecognized value to `disconnected` — the safe
62
+ * direction, since it is the state in which no token is used and the operator is prompted. */
63
+ /** @agent-note Pure, no I/O; unknown defaults to `disconnected`. One of the six `hostedMcpProjections`. */
64
+ export function resolveExternalMcpOAuthStatus(record) {
65
+ const status = record.oauthStatus;
66
+ return status !== null && EXTERNAL_MCP_OAUTH_STATUSES.includes(status)
67
+ ? status
68
+ : "disconnected";
69
+ }
70
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1,83 @@
1
+ import type { UUID } from "@jini-ai/core/primitives";
2
+ import type { ExternalMcpRevocationReason, ExternalMcpServerRepoPort } from "@jini-ai/core/contracts/hosted-mcp";
3
+ import type { FederatedCallTarget, FederatedGateVerdict } from "../ports.js";
4
+ /** What {@link createHostedMcpConnectionGate} closes over — split out so
5
+ * {@link readConnectionRowOrRefuse} can share the exact same shape rather than restating it. */
6
+ export interface ExternalMcpConnectionGateDeps {
7
+ readonly workspaceId: UUID;
8
+ readonly repo: Pick<ExternalMcpServerRepoPort, "findByServerId">;
9
+ readonly isPluginEnabled: (pluginId: string) => Promise<boolean>;
10
+ readonly assertSharedAuthorized?: (input: {
11
+ serverId: string;
12
+ }) => Promise<boolean>;
13
+ }
14
+ /**
15
+ * @agent-note The gate's host inputs (EXTRACT-S5 H2b seam; the gate moves to `mcp/federation/hosted` in H3 and imports no
16
+ * integrations or OAuth module). The host fulfills them ONCE per gate. `repo` is the same repository instance the store and
17
+ * sign-in use; the gate makes one `findByServerId` per call and never unseals, opens a token or touches the network.
18
+ * `isPluginEnabled` is the host's activation owner: a throw DENIES. `assertSharedAuthorized` is the host's shared-owner
19
+ * check; `true` skips only the legacy re-authorization check. `reauthRequired` is the host's ONE canonical re-authorization
20
+ * factory, the same function its sign-in service throws through, so `instanceof`, `code` and `retryable` stay one identity.
21
+ * `revoked` builds the host's revocation error with its own messages and code. `recovery` returns model-facing recovery
22
+ * text naming the host's own tool ids. `logUnreadableRow` is operator-only diagnostics; it MUST NOT throw, and its detail never reaches model text.
23
+ */
24
+ export interface HostedMcpConnectionGatePorts extends ExternalMcpConnectionGateDeps {
25
+ readonly reauthRequired: (input: {
26
+ serverId: string;
27
+ label?: string | null;
28
+ }) => Error;
29
+ readonly revoked: (input: {
30
+ serverId: string;
31
+ label: string | null;
32
+ remoteName: string;
33
+ reason: ExternalMcpRevocationReason;
34
+ }) => Error;
35
+ readonly recovery: {
36
+ readonly accessHint: (input: {
37
+ pluginId: string;
38
+ serverId: string;
39
+ refusal: ExternalMcpRevocationReason;
40
+ }) => string;
41
+ readonly pluginOff: (input: {
42
+ pluginId: string;
43
+ }) => string;
44
+ };
45
+ readonly logUnreadableRow: (input: {
46
+ connectionId: string;
47
+ error: unknown;
48
+ }) => void;
49
+ }
50
+ /**
51
+ * Builds the liveness-AND-revocation gate the federation checks before every
52
+ * federated call.
53
+ *
54
+ * ## Why this reads the database on every call, and why that is the right cost
55
+ *
56
+ * The connection's row is the only thing both processes that might serve a call — the agent daemon
57
+ * and the admin web server, which hold separate database handles — can see, so an in-memory flag in
58
+ * either one would be invisible to the other. Answering "is this connection still usable" is one
59
+ * indexed primary-key read and, for the legacy reauth check below, no keyring round trip either.
60
+ *
61
+ * ## Two checks, in order, and why a PRESET short-circuits the first
62
+ *
63
+ * A preset connection (`origin.kind === "preset"`) has no row in this table at all — its
64
+ * `allowedToolNames`, its enabled state, everything about it, comes from
65
+ * the host's preset resolution, not from an operator-editable roster row.
66
+ * So {@link rosterRefusalFor} — `revocation.ts`'s per-call re-check against a roster
67
+ * row's CURRENT `enabled`/grant-lists/admission-revision — is skipped entirely for a preset; refusing
68
+ * it would take out a working server to guard a state it structurally cannot be in. A roster
69
+ * connection (`origin.kind === "roster"`, or a call built with no origin at all — the `unverifiable`
70
+ * bug-guard) gets the full re-check.
71
+ *
72
+ * The legacy OAuth `needs_reauth` check ({@link assertNotAwaitingReauth}) then runs regardless of
73
+ * origin, UNCHANGED from before this gate also did revocation — a preset can be OAuth-authenticated
74
+ * too, and this is the one state that always applied to both origins.
75
+ *
76
+ * @returns The gate. Never throws at construction.
77
+ * @complexity O(1) per call — one primary-key read, no unseal.
78
+ * @tradeoffs One read per federated tool call, rather than caching the status. A cache is what would
79
+ * reintroduce the cross-process invisibility this exists to close, and the read is far cheaper
80
+ * than the network round trip it guards.
81
+ */
82
+ export declare function createHostedMcpConnectionGate(deps: HostedMcpConnectionGatePorts): (connectionId: string, call: FederatedCallTarget) => Promise<void | FederatedGateVerdict>;
83
+ //# sourceMappingURL=connection-gate.d.ts.map
@@ -0,0 +1,107 @@
1
+ import { ToolInputError } from "@jini-ai/core";
2
+ import { rosterRefusalFor } from "./revocation.js";
3
+ import { resolveExternalMcpAuthMode, resolveExternalMcpOAuthStatus } from "./auth.js";
4
+ /**
5
+ * Builds the liveness-AND-revocation gate the federation checks before every
6
+ * federated call.
7
+ *
8
+ * ## Why this reads the database on every call, and why that is the right cost
9
+ *
10
+ * The connection's row is the only thing both processes that might serve a call — the agent daemon
11
+ * and the admin web server, which hold separate database handles — can see, so an in-memory flag in
12
+ * either one would be invisible to the other. Answering "is this connection still usable" is one
13
+ * indexed primary-key read and, for the legacy reauth check below, no keyring round trip either.
14
+ *
15
+ * ## Two checks, in order, and why a PRESET short-circuits the first
16
+ *
17
+ * A preset connection (`origin.kind === "preset"`) has no row in this table at all — its
18
+ * `allowedToolNames`, its enabled state, everything about it, comes from
19
+ * the host's preset resolution, not from an operator-editable roster row.
20
+ * So {@link rosterRefusalFor} — `revocation.ts`'s per-call re-check against a roster
21
+ * row's CURRENT `enabled`/grant-lists/admission-revision — is skipped entirely for a preset; refusing
22
+ * it would take out a working server to guard a state it structurally cannot be in. A roster
23
+ * connection (`origin.kind === "roster"`, or a call built with no origin at all — the `unverifiable`
24
+ * bug-guard) gets the full re-check.
25
+ *
26
+ * The legacy OAuth `needs_reauth` check ({@link assertNotAwaitingReauth}) then runs regardless of
27
+ * origin, UNCHANGED from before this gate also did revocation — a preset can be OAuth-authenticated
28
+ * too, and this is the one state that always applied to both origins.
29
+ *
30
+ * @returns The gate. Never throws at construction.
31
+ * @complexity O(1) per call — one primary-key read, no unseal.
32
+ * @tradeoffs One read per federated tool call, rather than caching the status. A cache is what would
33
+ * reintroduce the cross-process invisibility this exists to close, and the read is far cheaper
34
+ * than the network round trip it guards.
35
+ */
36
+ export function createHostedMcpConnectionGate(deps) {
37
+ return async (connectionId, call) => {
38
+ const record = await readConnectionRowOrRefuse(deps, connectionId);
39
+ await assertProvisioningPluginEnabled({ deps, record });
40
+ const isPreset = call.origin?.kind === "preset";
41
+ const refusal = isPreset ? null : rosterRefusalFor(record, call);
42
+ if (refusal !== null) {
43
+ offerPluginAccessCard({ deps, record, refusal });
44
+ throw deps.revoked({ serverId: connectionId, label: record?.label ?? null, remoteName: call.remoteName, reason: refusal });
45
+ }
46
+ const shared = await deps.assertSharedAuthorized?.({ serverId: connectionId });
47
+ if (!shared)
48
+ assertNotAwaitingReauth(deps, record, connectionId);
49
+ // A roster call just passed `rosterRefusalFor`'s current-row grant check; tell Jini so its
50
+ // admitted-grants snapshot does not refuse a grant added since boot. A preset vouches for nothing.
51
+ return isPreset ? undefined : "current-grants-checked";
52
+ };
53
+ }
54
+ /** Point an active plugin with missing source/tool/write grants back to its existing single card.
55
+ * @throws ToolInputError naming that review flow; no grant or configuration is changed here.
56
+ * @complexity O(1), no I/O.
57
+ */
58
+ function offerPluginAccessCard({ deps, record, refusal }, _options = {}) {
59
+ const pluginId = record?.provisionedByPluginId;
60
+ if (!pluginId || !['turned-off', 'tool-not-allowed', 'write-not-allowed'].includes(refusal))
61
+ return;
62
+ throw new ToolInputError({ message: deps.recovery.accessHint({ pluginId, serverId: record.serverId, refusal }) });
63
+ }
64
+ /** A surviving connection never overrides its provisioning plugin's OFF switch.
65
+ * @throws ToolInputError before any remote call when activation is off or cannot be verified.
66
+ * @complexity One activation-owner check for plugin rows; no extra row read.
67
+ */
68
+ async function assertProvisioningPluginEnabled({ deps, record }, _options = {}) {
69
+ const pluginId = record?.provisionedByPluginId;
70
+ if (!pluginId)
71
+ return;
72
+ let enabled = false;
73
+ try {
74
+ enabled = await deps.isPluginEnabled(pluginId);
75
+ }
76
+ catch { /* An unreadable activation must not authorize a remote call. */ }
77
+ if (!enabled)
78
+ throw new ToolInputError({ message: deps.recovery.pluginOff({ pluginId }) });
79
+ }
80
+ /** The gate's row read, guarded: a read that THROWS (a locked database, a corrupt row) must not leak
81
+ * its detail to the model — that detail can carry a file path or a driver's internal message — so it
82
+ * goes to the host's `logUnreadableRow` port for an operator to find, and the model gets only `unverifiable`'s generic
83
+ * text. Split out of {@link createHostedMcpConnectionGate} purely to keep that function's
84
+ * complexity under the shop ceiling.
85
+ * @complexity O(1). */
86
+ async function readConnectionRowOrRefuse(deps, connectionId) {
87
+ try {
88
+ return await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId: connectionId });
89
+ }
90
+ catch (error) {
91
+ deps.logUnreadableRow({ connectionId, error });
92
+ throw deps.revoked({ serverId: connectionId, label: null, remoteName: "", reason: "unverifiable" });
93
+ }
94
+ }
95
+ /** The gate's ORIGINAL body, byte-identical in behaviour: a missing row, or one not OAuth-authenticated,
96
+ * passes; `needs_reauth` throws the same terminal error it always has. Split out of
97
+ * {@link createHostedMcpConnectionGate} purely to keep that function's complexity under the shop
98
+ * ceiling.
99
+ * @complexity O(1). */
100
+ function assertNotAwaitingReauth(deps, record, connectionId) {
101
+ if (!record || resolveExternalMcpAuthMode(record) !== "oauth")
102
+ return;
103
+ if (resolveExternalMcpOAuthStatus(record) !== "needs_reauth")
104
+ return;
105
+ throw deps.reauthRequired({ serverId: connectionId, label: record.label });
106
+ }
107
+ //# sourceMappingURL=connection-gate.js.map
@@ -0,0 +1,14 @@
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
+ export * from "./vocabulary.js";
3
+ export * from "./auth.js";
4
+ export * from "./access.js";
5
+ export { ExternalMcpValidationError } from "./validation-error.js";
6
+ export { ExternalMcpSecretStoreUnconfiguredError } from "./unconfigured-error.js";
7
+ export { hostedMcpProjections } from "./projections.js";
8
+ export type * from "./store-ports.js";
9
+ export * from "./vault.js";
10
+ export * from "./store.js";
11
+ export { InMemoryExternalMcpServerRepo } from "./store.memory.js";
12
+ export * from "./revocation.js";
13
+ export * from "./connection-gate.js";
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,13 @@
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
+ export * from "./vocabulary.js";
3
+ export * from "./auth.js";
4
+ export * from "./access.js";
5
+ export { ExternalMcpValidationError } from "./validation-error.js";
6
+ export { ExternalMcpSecretStoreUnconfiguredError } from "./unconfigured-error.js";
7
+ export { hostedMcpProjections } from "./projections.js";
8
+ export * from "./vault.js";
9
+ export * from "./store.js";
10
+ export { InMemoryExternalMcpServerRepo } from "./store.memory.js";
11
+ export * from "./revocation.js";
12
+ export * from "./connection-gate.js";
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,15 @@
1
+ import { externalMcpAccessSnapshot, externalMcpAdmissionRevision, readExternalMcpToolGrants, validateExternalMcpToolNames } from "./access.js";
2
+ import { externalMcpRecordHasStaticAccessToken, resolveExternalMcpOAuthStatus } from "./auth.js";
3
+ /**
4
+ * The six pure row projections hosts hand to plugin and sign-in seams, as the original functions.
5
+ * @agent-note Function calls only: no I/O, cache or state. Members are the exact exported functions (same identity), so a host may bind this object or the functions directly. The host passes one object to every seam that needs projections.
6
+ */
7
+ export declare const hostedMcpProjections: {
8
+ readonly accessSnapshot: typeof externalMcpAccessSnapshot;
9
+ readonly admissionRevision: typeof externalMcpAdmissionRevision;
10
+ readonly readToolGrants: typeof readExternalMcpToolGrants;
11
+ readonly validateToolNames: typeof validateExternalMcpToolNames;
12
+ readonly oauthStatus: typeof resolveExternalMcpOAuthStatus;
13
+ readonly hasStaticAccessToken: typeof externalMcpRecordHasStaticAccessToken;
14
+ };
15
+ //# sourceMappingURL=projections.d.ts.map
@@ -0,0 +1,15 @@
1
+ import { externalMcpAccessSnapshot, externalMcpAdmissionRevision, readExternalMcpToolGrants, validateExternalMcpToolNames } from "./access.js";
2
+ import { externalMcpRecordHasStaticAccessToken, resolveExternalMcpOAuthStatus } from "./auth.js";
3
+ /**
4
+ * The six pure row projections hosts hand to plugin and sign-in seams, as the original functions.
5
+ * @agent-note Function calls only: no I/O, cache or state. Members are the exact exported functions (same identity), so a host may bind this object or the functions directly. The host passes one object to every seam that needs projections.
6
+ */
7
+ export const hostedMcpProjections = {
8
+ accessSnapshot: externalMcpAccessSnapshot,
9
+ admissionRevision: externalMcpAdmissionRevision,
10
+ readToolGrants: readExternalMcpToolGrants,
11
+ validateToolNames: validateExternalMcpToolNames,
12
+ oauthStatus: resolveExternalMcpOAuthStatus,
13
+ hasStaticAccessToken: externalMcpRecordHasStaticAccessToken,
14
+ };
15
+ //# sourceMappingURL=projections.js.map
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @file Per-call operator-revocation checks for an already-admitted federated tool — the roster half
3
+ * of the federation's `FederationDeps.assertConnectionUsable`, consumed by
4
+ * `createHostedMcpConnectionGate`.
5
+ *
6
+ * Why this exists at all: the federation's registry is append-only (see
7
+ * `registrations.ts`'s `FederationDeps.assertConnectionUsable` doc), so a connection deleted,
8
+ * disabled, narrowed, or edited after admission cannot be un-registered — its tools stay both
9
+ * listed and, absent this gate, callable. This file is what turns that stale admission into a
10
+ * refusal at the next call, by re-reading the connection's CURRENT row against what the tool was
11
+ * admitted under.
12
+ *
13
+ * Deliberately does not import the connection gate, which calls `rosterRefusalFor`, so the
14
+ * reverse import would be a cycle. Auth-mode/status readers come from `auth.ts` instead.
15
+ *
16
+ * `ExternalMcpConnectionRevokedError` extends `ToolInputError` rather than being reported through a
17
+ * `ToolPolicy` deny — the same D1 argument `registrations.ts`'s own gate doc and
18
+ * `federated-refusal-diagnosis.ts` both make: every consumer maps a policy `denied` to a fixed
19
+ * "denied by policy"-shaped string, which sends an operator who DOES have the permission looking in
20
+ * the wrong place. A handler-side `ToolInputError` reaches the model as `errorKind: 'validation'`
21
+ * with this file's own text instead.
22
+ */
23
+ import type { ExternalMcpRevocationReason } from "@jini-ai/core/contracts/hosted-mcp";
24
+ import { ToolInputError } from "@jini-ai/core";
25
+ import { type ExternalMcpServerRecord } from "@jini-ai/core/contracts/hosted-mcp";
26
+ import type { FederatedCallTarget } from "../ports.js";
27
+ /** What a revocation message may name: the connection, its operator label, the remote tool and why. */
28
+ /** @agent-note Built by the host's connection gate from the admitted call and the current row; `label` is operator-entered display text. */
29
+ export interface ExternalMcpRevocationMessageInput {
30
+ readonly serverId: string;
31
+ readonly label: string | null;
32
+ readonly remoteName: string;
33
+ readonly reason: ExternalMcpRevocationReason;
34
+ }
35
+ /** Model-facing text for each revocation reason, supplied by the host (its settings path and wording). */
36
+ /** @agent-note Host input: every reason must have a sentence; each must tell the model not to retry (except `unverifiable`) and must never carry a provider message, token or URL. */
37
+ export type ExternalMcpRevocationMessages = Readonly<Record<ExternalMcpRevocationReason, (input: ExternalMcpRevocationMessageInput) => string>>;
38
+ /**
39
+ * The terminal, non-retryable failure a federated tool returns once its connection has been revoked
40
+ * since admission — deleted, disabled, narrowed, edited, or OAuth-disconnected. Sibling of
41
+ * the host's canonical reauthorization error, with the same "always false, present
42
+ * as a field" `retryable` convention.
43
+ */
44
+ export declare class ExternalMcpConnectionRevokedError extends ToolInputError {
45
+ readonly code: string;
46
+ readonly retryable = false;
47
+ readonly serverId: string;
48
+ readonly reason: ExternalMcpRevocationReason;
49
+ /** @agent-note `messages` (model-facing text) and `code` (the host's stable error code) are bound once by the host; a host subclass keeps the old one-argument constructor. `code`, `name` and `retryable` are stable error identity. */
50
+ constructor({ code, ...input }: ExternalMcpRevocationMessageInput & {
51
+ messages: ExternalMcpRevocationMessages;
52
+ code: string;
53
+ });
54
+ }
55
+ /**
56
+ * Re-checks one already-admitted roster tool against its connection's CURRENT row — steps 3-8 of the
57
+ * design doc's D2. Pure: takes the row (already read by the caller) and the call's identity, and
58
+ * returns why it should now be refused, or `null` when it still clears every check.
59
+ *
60
+ * The caller (the hosted connection gate) invokes this ONLY for a non-preset origin — a preset
61
+ * has no row to compare against and gets only the legacy `needs_reauth` check. The `call.origin.kind
62
+ * === "preset"` branch below exists purely as a bug-guard for a roster-shaped call built outside
63
+ * `toResolvedFederatedConnections`, mirroring the `undefined` branch immediately before it: both fail
64
+ * closed to `unverifiable` rather than assume a shape this function was never handed at admission.
65
+ *
66
+ * @complexity O(1).
67
+ */
68
+ /** @agent-note Pure: the caller passes the row it already read (the store's repository, once per call) and the admitted call identity; no I/O and no state. */
69
+ export declare function rosterRefusalFor(record: ExternalMcpServerRecord | null, call: FederatedCallTarget): ExternalMcpRevocationReason | null;
70
+ //# sourceMappingURL=revocation.d.ts.map
@@ -0,0 +1,78 @@
1
+ import { ToolInputError } from "@jini-ai/core";
2
+ import { externalMcpAdmissionRevision, readExternalMcpToolGrants } from "./access.js";
3
+ import { resolveExternalMcpOAuthStatus } from "./auth.js";
4
+ import { resolveExternalMcpAuthMode } from "./auth.js";
5
+ import {} from "@jini-ai/core/contracts/hosted-mcp";
6
+ import { refusalForAdmittedToolUnderCurrentGrants } from "../trust.js";
7
+ /** @complexity O(1). */
8
+ function revocationMessage({ messages, ...input }) {
9
+ return messages[input.reason](input);
10
+ }
11
+ /**
12
+ * The terminal, non-retryable failure a federated tool returns once its connection has been revoked
13
+ * since admission — deleted, disabled, narrowed, edited, or OAuth-disconnected. Sibling of
14
+ * the host's canonical reauthorization error, with the same "always false, present
15
+ * as a field" `retryable` convention.
16
+ */
17
+ export class ExternalMcpConnectionRevokedError extends ToolInputError {
18
+ code;
19
+ retryable = false;
20
+ serverId;
21
+ reason;
22
+ /** @agent-note `messages` (model-facing text) and `code` (the host's stable error code) are bound once by the host; a host subclass keeps the old one-argument constructor. `code`, `name` and `retryable` are stable error identity. */
23
+ constructor({ code, ...input }) {
24
+ super({ message: revocationMessage(input) });
25
+ this.code = code;
26
+ this.name = "ExternalMcpConnectionRevokedError";
27
+ this.serverId = input.serverId;
28
+ this.reason = input.reason;
29
+ }
30
+ }
31
+ /** {@link rosterRefusalFor}'s OAuth check: `disconnected` refuses, `pending`/`connected`/`needs_reauth`
32
+ * do not — `needs_reauth` is the legacy check the gate still runs afterwards, unchanged, so it must
33
+ * not also be caught here. @complexity O(1). */
34
+ function isOAuthDisconnected(record) {
35
+ return resolveExternalMcpAuthMode(record) === "oauth" && resolveExternalMcpOAuthStatus(record) === "disconnected";
36
+ }
37
+ /** {@link rosterRefusalFor}'s grant check: reapplies R2 and "may write" to the connection's CURRENT
38
+ * allowlist and write list — narrowing only, never granting, exactly as {@link refusalForAdmittedToolUnderCurrentGrants}
39
+ * documents. Maps the one grant-refusal reason that means "a write tool without a write grant" onto
40
+ * the write-specific D3 message; every other reason (today, only `not-in-operator-allowlist`) maps
41
+ * to the generic one. @complexity O(a + w) in the two list lengths. */
42
+ function grantRefusalFor(record, call) {
43
+ const grants = readExternalMcpToolGrants(record);
44
+ const refusal = refusalForAdmittedToolUnderCurrentGrants({ tool: {
45
+ remoteName: call.remoteName, declaredAnnotations: call.declaredAnnotations, requiresWriteGrant: call.requiresWriteGrant,
46
+ }, grants });
47
+ if (refusal === null)
48
+ return null;
49
+ return refusal === "remote-declares-not-read-only" ? "write-not-allowed" : "tool-not-allowed";
50
+ }
51
+ /**
52
+ * Re-checks one already-admitted roster tool against its connection's CURRENT row — steps 3-8 of the
53
+ * design doc's D2. Pure: takes the row (already read by the caller) and the call's identity, and
54
+ * returns why it should now be refused, or `null` when it still clears every check.
55
+ *
56
+ * The caller (the hosted connection gate) invokes this ONLY for a non-preset origin — a preset
57
+ * has no row to compare against and gets only the legacy `needs_reauth` check. The `call.origin.kind
58
+ * === "preset"` branch below exists purely as a bug-guard for a roster-shaped call built outside
59
+ * `toResolvedFederatedConnections`, mirroring the `undefined` branch immediately before it: both fail
60
+ * closed to `unverifiable` rather than assume a shape this function was never handed at admission.
61
+ *
62
+ * @complexity O(1).
63
+ */
64
+ /** @agent-note Pure: the caller passes the row it already read (the store's repository, once per call) and the admitted call identity; no I/O and no state. */
65
+ export function rosterRefusalFor(record, call) {
66
+ if (call.origin === undefined || call.origin.kind === "preset")
67
+ return "unverifiable";
68
+ if (record === null)
69
+ return "removed";
70
+ if (externalMcpAdmissionRevision(record) !== call.origin.admissionRevision)
71
+ return "changed";
72
+ if (!record.enabled)
73
+ return "turned-off";
74
+ if (isOAuthDisconnected(record))
75
+ return "disconnected";
76
+ return grantRefusalFor(record, call);
77
+ }
78
+ //# sourceMappingURL=revocation.js.map
@@ -0,0 +1,95 @@
1
+ import type { KeyringPort, SecretSealerPort, VaultContext, VaultErrorCode, VaultIdentity, VaultKind, VaultMeta, VaultMetaParsers, VaultQuery, VaultRepoPort } from "@jini-ai/core/contracts/vault";
2
+ /** Display hint for a stored token: its length and, for tokens of 12+ characters, the last four. */
3
+ /** @agent-note Same shape as the platform credential hint; the host's `credential.hint` produces it from an unsealed value, server-side only. */
4
+ export type HostedMcpTokenHint = {
5
+ length: number;
6
+ last4: string | null;
7
+ };
8
+ /** The vault service operations the hosted store calls: one `put` when sealing, one `get` when opening. */
9
+ /** @agent-note Fulfilled by the host's vault service (usually `SecretsVaultService` from `@jini-ai/platform`) built by `vault.createService`. It must check `authorize` before any read or write, build AAD from the record context itself, and open with no legacy-AAD fallback. */
10
+ export interface HostedMcpVaultService {
11
+ put(input: VaultContext & {
12
+ id: string;
13
+ expectedRevision: number | null;
14
+ provider: string | null;
15
+ label: string;
16
+ meta: unknown;
17
+ payload: VaultMeta;
18
+ }): Promise<VaultIdentity>;
19
+ get(input: VaultIdentity): Promise<{
20
+ payload: VaultMeta | null;
21
+ } | null>;
22
+ }
23
+ /** Everything `vault.createService` receives; built fresh for each seal/open. */
24
+ /** @agent-note Pass every field through unchanged: `metaParsers` already carries the hosted metadata policy and `authorize` refuses any foreign workspace/owner/kind/principal by throwing. */
25
+ export interface HostedMcpVaultServiceDeps {
26
+ repo: VaultRepoPort;
27
+ sealer: SecretSealerPort;
28
+ keyring: KeyringPort;
29
+ metaParsers: VaultMetaParsers;
30
+ authorize: (input: {
31
+ action: "put" | "get" | "list" | "rotate" | "delete";
32
+ context: VaultContext | VaultIdentity | VaultQuery;
33
+ }) => Promise<void>;
34
+ now: () => string;
35
+ newId: () => string;
36
+ }
37
+ /** Host-bound vault ports for the envelope module and the in-memory repository. */
38
+ /** @agent-note The host binds these ONCE. `createMemoryRepo` returns a fresh, empty in-memory vault repository on every call (no shared Map); `createService` wraps the host's real vault service; `vaultErrors.create` must return the host's real vault error class instance (same `instanceof`/`code` the rest of the host checks); `metaParsers` builds the host's per-kind parsers around the supplied `validateMeta`, which must be consulted for both `mcp-env` and `mcp-auth`. Error codes are the saved vocabulary `conflict | context | invalid-meta | invalid-record`. */
39
+ export interface HostedMcpVaultPorts {
40
+ vault: {
41
+ createService(deps: HostedMcpVaultServiceDeps): HostedMcpVaultService;
42
+ createMemoryRepo(): VaultRepoPort;
43
+ };
44
+ vaultErrors: {
45
+ create({ code }: {
46
+ code: VaultErrorCode;
47
+ }, optionalArgs?: Record<string, never>): Error;
48
+ };
49
+ metaParsers(required: {
50
+ validateMeta: (input: {
51
+ kind: VaultKind;
52
+ meta: VaultMeta;
53
+ }) => VaultMeta;
54
+ }): VaultMetaParsers;
55
+ }
56
+ /** The error a credential rule throws: only a rule message and field, never the submitted value. */
57
+ /** @agent-note Fulfilled by the host's credential input error class; the store tests `instanceof` it and copies `message`/`field` into its own validation error. */
58
+ export type HostedMcpCredentialInputError = abstract new (...args: never[]) => Error & {
59
+ readonly field: string;
60
+ };
61
+ /** Host-bound ports the hosted store reads on top of the per-call `repo/sealer/keyring/clock`. */
62
+ /** @agent-note The host binds these ONCE (the same values for every call). `assertFreeField` throws `credential.InputError` when a plain field looks like a secret. `credential.normalize`/`assert` apply the host token policy and throw `credential.InputError`; `messages` supplies the five user-facing credential sentences; `limit` is the token length cap. `settingsLink` names where an operator fixes a connection and is interpolated verbatim into admission/model-facing failure reasons, so it must carry no secret. `reauthRequiredCode` is the stable `code` of the host OAuth resolver's reauthorization error; a resolver error carrying it is reported as "authorization expired" rather than as a token failure. */
63
+ export interface HostedMcpStorePorts extends HostedMcpVaultPorts {
64
+ assertFreeField(required: {
65
+ value: string;
66
+ field: string;
67
+ }): void;
68
+ credential: {
69
+ normalize(required: {
70
+ value: unknown;
71
+ field?: string;
72
+ hosted?: boolean;
73
+ }): string;
74
+ assert(required: {
75
+ value: unknown;
76
+ field?: string;
77
+ hosted?: boolean;
78
+ }): void;
79
+ hint(required: {
80
+ token: string;
81
+ }): HostedMcpTokenHint;
82
+ messages: {
83
+ readonly env: string;
84
+ readonly ascii: string;
85
+ readonly storage: string;
86
+ readonly blank: string;
87
+ readonly url: string;
88
+ };
89
+ limit: number;
90
+ InputError: HostedMcpCredentialInputError;
91
+ };
92
+ settingsLink: string;
93
+ reauthRequiredCode: string;
94
+ }
95
+ //# sourceMappingURL=store-ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=store-ports.js.map