@myrialabs/clopen 0.4.37 → 0.4.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/backend/auth/permissions.ts +14 -0
- package/backend/bootstrap.ts +16 -0
- package/backend/database/crypto/envelope.test.ts +93 -0
- package/backend/database/crypto/envelope.ts +127 -0
- package/backend/database/crypto/index.ts +22 -0
- package/backend/database/crypto/master-key.ts +129 -0
- package/backend/database/crypto/secret-columns.ts +147 -0
- package/backend/database/migrations/071_create_notes_tables.ts +90 -0
- package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
- package/backend/database/migrations/073_create_integration_tables.ts +119 -0
- package/backend/database/migrations/074_create_work_tables.ts +94 -0
- package/backend/database/migrations/index.ts +28 -0
- package/backend/database/queries/db-client-connection-queries.ts +23 -12
- package/backend/database/queries/engine-queries.ts +23 -10
- package/backend/database/queries/index.ts +6 -1
- package/backend/database/queries/integration-queries.ts +297 -0
- package/backend/database/queries/mcp-server-queries.ts +38 -11
- package/backend/database/queries/note-queries.test.ts +190 -0
- package/backend/database/queries/note-queries.ts +269 -0
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/ssh-connection-queries.ts +19 -8
- package/backend/database/queries/work-queries.ts +210 -0
- package/backend/engine/docs/artifacts.md +22 -9
- package/backend/files/os-clipboard.test.ts +209 -0
- package/backend/files/os-clipboard.ts +567 -0
- package/backend/http/integration-hooks.ts +42 -0
- package/backend/http/notes-images.test.ts +228 -0
- package/backend/http/notes-images.ts +196 -0
- package/backend/index.ts +9 -0
- package/backend/integrations/accounts.ts +229 -0
- package/backend/integrations/health.ts +146 -0
- package/backend/integrations/index.ts +36 -0
- package/backend/integrations/projections/index.ts +120 -0
- package/backend/integrations/projections/mcp-projector.test.ts +204 -0
- package/backend/integrations/projections/mcp-projector.ts +159 -0
- package/backend/integrations/projections/types.ts +51 -0
- package/backend/integrations/registry/define.ts +38 -0
- package/backend/integrations/registry/index.ts +56 -0
- package/backend/integrations/registry/providers/context7.ts +44 -0
- package/backend/integrations/registry/providers/firecrawl.ts +41 -0
- package/backend/integrations/registry/providers/github.ts +78 -0
- package/backend/integrations/registry/types.ts +96 -0
- package/backend/integrations/webhooks/gateway.ts +160 -0
- package/backend/integrations/webhooks/verify.ts +65 -0
- package/backend/mcp/README.md +25 -3
- package/backend/mcp/external/config.ts +35 -1
- package/backend/mcp/index.ts +1 -1
- package/backend/mcp/internal/config.ts +1 -1
- package/backend/notes/access.test.ts +82 -0
- package/backend/notes/access.ts +27 -0
- package/backend/notes/storage.test.ts +77 -0
- package/backend/notes/storage.ts +114 -0
- package/backend/permissions/service.ts +2 -2
- package/backend/profiles/service.ts +1 -1
- package/backend/projects/project-cleanup.ts +6 -0
- package/backend/work/bindings.ts +124 -0
- package/backend/work/index.ts +42 -0
- package/backend/work/prompts.ts +150 -0
- package/backend/work/providers/github/actions-logs.ts +180 -0
- package/backend/work/providers/github/adapter.test.ts +88 -0
- package/backend/work/providers/github/adapter.ts +1255 -0
- package/backend/work/providers/github/client.ts +280 -0
- package/backend/work/providers/github/list-range.test.ts +158 -0
- package/backend/work/providers/github/token-kind.test.ts +42 -0
- package/backend/work/pull-requests.ts +242 -0
- package/backend/work/registry.ts +27 -0
- package/backend/work/service.ts +436 -0
- package/backend/work/start-work.test.ts +71 -0
- package/backend/work/start-work.ts +232 -0
- package/backend/work/types.ts +180 -0
- package/backend/ws/files/clipboard.ts +78 -0
- package/backend/ws/files/index.ts +5 -0
- package/backend/ws/git/diff-budget.ts +70 -11
- package/backend/ws/index.ts +11 -1
- package/backend/ws/integrations/crud.ts +219 -0
- package/backend/ws/integrations/index.ts +22 -0
- package/backend/ws/mcp/crud.ts +25 -1
- package/backend/ws/notes/index.ts +278 -0
- package/backend/ws/profiles/crud.ts +1 -1
- package/backend/ws/work/actions.ts +206 -0
- package/backend/ws/work/context.ts +51 -0
- package/backend/ws/work/crud.ts +347 -0
- package/backend/ws/work/index.ts +17 -0
- package/backend/ws/work/pull-requests.ts +177 -0
- package/backend/ws/work/schemas.ts +226 -0
- package/dist/assets/{index-sJmS_CCm.js → index-CyH7fSbR.js} +1 -1
- package/dist/assets/{index-Bik9TCBi.js → index-DSHIANSy.js} +1 -1
- package/dist/assets/main-D2IOjftb.css +1 -0
- package/dist/assets/main-DM-tHKbW.js +1152 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/tool-icons.ts +33 -0
- package/shared/types/database/schema.ts +41 -0
- package/shared/types/integrations.ts +140 -0
- package/shared/types/stores/settings.ts +8 -0
- package/shared/types/work.ts +426 -0
- package/shared/utils/logger.ts +3 -0
- package/dist/assets/main-DLqolBI2.css +0 -1
- package/dist/assets/main-Df1I3hnw.js +0 -1096
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Account health, and the health of the secrets layer itself.
|
|
3
|
+
*
|
|
4
|
+
* Account health reuses the MCP probe rather than inventing a second notion of
|
|
5
|
+
* "is this connector working" — for an account whose only capability is agent
|
|
6
|
+
* tools, the probe against its projected row IS the answer.
|
|
7
|
+
*
|
|
8
|
+
* That answer runs out the moment a capability projects no MCP row. A GitHub
|
|
9
|
+
* account offering `work` has a credential that can be verified precisely —
|
|
10
|
+
* by calling the API it was issued for — but nothing for `probeServer()` to
|
|
11
|
+
* reach. So a surface may register its own probe for its providers, and the
|
|
12
|
+
* hub's status strip keeps meaning something for every account rather than
|
|
13
|
+
* reading "Nothing to probe yet" forever.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { probeServer, resolveServerRow } from '$backend/mcp';
|
|
17
|
+
import {
|
|
18
|
+
integrationAccountQueries,
|
|
19
|
+
integrationProjectionQueries,
|
|
20
|
+
mcpServerQueries
|
|
21
|
+
} from '$backend/database/queries';
|
|
22
|
+
import { getDatabase } from '$backend/database';
|
|
23
|
+
import { auditSecretColumns, getDecryptFailures, getMasterKey } from '$backend/database/crypto';
|
|
24
|
+
import type { IntegrationStatus, SecretsHealth } from '$shared/types/integrations';
|
|
25
|
+
import { integrationAccounts } from './accounts';
|
|
26
|
+
import { debug } from '$shared/utils/logger';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A probe contributed by a surface, keyed by provider id.
|
|
30
|
+
*
|
|
31
|
+
* Returning null means "this probe has nothing to say about this account" — for
|
|
32
|
+
* instance a GitHub account with `work` switched off — and the MCP path is
|
|
33
|
+
* used instead. That is what lets one account carry both kinds of capability
|
|
34
|
+
* without the two probes fighting over which one reports.
|
|
35
|
+
*/
|
|
36
|
+
export type AccountProbe = (
|
|
37
|
+
accountId: string,
|
|
38
|
+
projectId: string | null
|
|
39
|
+
) => Promise<{ status: IntegrationStatus; detail: string | null } | null>;
|
|
40
|
+
|
|
41
|
+
const providerProbes = new Map<string, AccountProbe>();
|
|
42
|
+
|
|
43
|
+
/** Register a provider-specific probe. Called at module load by the surface. */
|
|
44
|
+
export function registerAccountProbe(provider: string, probe: AccountProbe): void {
|
|
45
|
+
providerProbes.set(provider, probe);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Probe one account.
|
|
50
|
+
*
|
|
51
|
+
* An account with no projected MCP row has nothing probeable yet — its
|
|
52
|
+
* capabilities belong to surfaces that do not exist. That is reported as
|
|
53
|
+
* `unknown` rather than `ok`, because claiming health we never measured is the
|
|
54
|
+
* one answer worse than "not checked".
|
|
55
|
+
*/
|
|
56
|
+
export async function checkAccountHealth(accountId: string): Promise<{ status: IntegrationStatus; detail: string | null }> {
|
|
57
|
+
const account = integrationAccountQueries.getById(accountId);
|
|
58
|
+
if (!account) throw new Error('Integration account not found');
|
|
59
|
+
|
|
60
|
+
if (account.is_enabled !== 1) {
|
|
61
|
+
const result = { status: 'unknown' as const, detail: 'Disabled' };
|
|
62
|
+
integrationAccounts.setStatus(accountId, result.status, result.detail);
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// A surface probe is the more specific answer when there is one: it talks to
|
|
67
|
+
// the API the credential was issued for, rather than to an MCP server that
|
|
68
|
+
// happens to accept the same token.
|
|
69
|
+
const providerProbe = providerProbes.get(account.provider);
|
|
70
|
+
if (providerProbe) {
|
|
71
|
+
try {
|
|
72
|
+
const result = await providerProbe(accountId, account.project_id);
|
|
73
|
+
if (result) {
|
|
74
|
+
integrationAccounts.setStatus(accountId, result.status, result.detail);
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
} catch (error) {
|
|
78
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
79
|
+
debug.error('integrations', `Provider probe failed for account ${accountId}:`, error);
|
|
80
|
+
integrationAccounts.setStatus(accountId, 'error', detail);
|
|
81
|
+
return { status: 'error', detail };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const projection = integrationProjectionQueries
|
|
86
|
+
.getForAccount(accountId)
|
|
87
|
+
.find((row) => row.target_kind === 'mcp_server');
|
|
88
|
+
|
|
89
|
+
if (!projection) {
|
|
90
|
+
const result = { status: 'unknown' as const, detail: 'Nothing to probe yet' };
|
|
91
|
+
integrationAccounts.setStatus(accountId, result.status, result.detail);
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const row = mcpServerQueries.getById(Number(projection.target_id));
|
|
96
|
+
if (!row) {
|
|
97
|
+
const result = { status: 'error' as const, detail: 'Projected connector is missing' };
|
|
98
|
+
integrationAccounts.setStatus(accountId, result.status, result.detail);
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const health = await probeServer(resolveServerRow(row));
|
|
104
|
+
// The probe's `unreachable` and `local` states have no account-level
|
|
105
|
+
// meaning: one is an error and the other means "nothing to reach".
|
|
106
|
+
const status: IntegrationStatus =
|
|
107
|
+
health.state === 'ok' ? 'ok'
|
|
108
|
+
: health.state === 'needs_auth' ? 'needs_auth'
|
|
109
|
+
: health.state === 'needs_config' ? 'needs_config'
|
|
110
|
+
: health.state === 'local' ? 'unknown'
|
|
111
|
+
: 'error';
|
|
112
|
+
|
|
113
|
+
integrationAccounts.setStatus(accountId, status, health.message ?? null);
|
|
114
|
+
return { status, detail: health.message ?? null };
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
117
|
+
debug.error('integrations', `Health check failed for account ${accountId}:`, error);
|
|
118
|
+
integrationAccounts.setStatus(accountId, 'error', detail);
|
|
119
|
+
return { status: 'error', detail };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* State of secrets at rest, rendered by the hub as a banner.
|
|
125
|
+
*
|
|
126
|
+
* A non-zero failure count is almost always a database restored next to a
|
|
127
|
+
* freshly generated key. Surfacing the fingerprints is what turns that from
|
|
128
|
+
* "some credentials stopped working" into "you are missing key 3f9a1c22".
|
|
129
|
+
*/
|
|
130
|
+
export function getSecretsHealth(): SecretsHealth {
|
|
131
|
+
const { fingerprint, source } = getMasterKey();
|
|
132
|
+
const failures = getDecryptFailures();
|
|
133
|
+
|
|
134
|
+
const unsealedColumns = auditSecretColumns(getDatabase())
|
|
135
|
+
.filter((entry) => entry.unsealed > 0)
|
|
136
|
+
.map((entry) => ({ table: entry.table, column: entry.column, count: entry.unsealed }));
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
keySource: source,
|
|
140
|
+
keyFingerprint: fingerprint,
|
|
141
|
+
failureCount: failures.count,
|
|
142
|
+
lastFailureAt: failures.lastAt,
|
|
143
|
+
unknownKeyFingerprints: failures.fingerprints,
|
|
144
|
+
unsealedColumns
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Third-party integrations.
|
|
3
|
+
*
|
|
4
|
+
* A connected account is a CREDENTIAL WITH CAPABILITIES, stored once in
|
|
5
|
+
* `integration_accounts`. Rows on other surfaces are projections derived from
|
|
6
|
+
* it, and nothing downstream of a projection needs to know accounts exist.
|
|
7
|
+
*
|
|
8
|
+
* registry/ what Clopen can connect to, declared in code
|
|
9
|
+
* accounts.ts connect / reconfigure / disconnect
|
|
10
|
+
* projections/ the derived rows, and the adopt-and-release rules
|
|
11
|
+
* webhooks/ the signed inbound endpoint
|
|
12
|
+
* health.ts account health, and the health of secrets at rest
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export {
|
|
16
|
+
PROVIDERS,
|
|
17
|
+
getProvider,
|
|
18
|
+
listProviderInfo,
|
|
19
|
+
toProviderInfo,
|
|
20
|
+
defaultCapabilitiesOf,
|
|
21
|
+
defineProvider
|
|
22
|
+
} from './registry';
|
|
23
|
+
export type { IntegrationProvider, McpPreset, WebhookSpec } from './registry';
|
|
24
|
+
|
|
25
|
+
export { integrationAccounts, toAccountInfo } from './accounts';
|
|
26
|
+
export type { ConnectInput } from './accounts';
|
|
27
|
+
|
|
28
|
+
export { reproject, releaseAll, registerProjector, projectableCapabilities } from './projections';
|
|
29
|
+
export type { Projector, ProjectionContext, ProjectionResult } from './projections';
|
|
30
|
+
|
|
31
|
+
export { handleInboundDelivery, onWebhook, MAX_BODY_BYTES } from './webhooks/gateway';
|
|
32
|
+
export type { WebhookEvent, WebhookSubscriber } from './webhooks/gateway';
|
|
33
|
+
export { verifySignature } from './webhooks/verify';
|
|
34
|
+
|
|
35
|
+
export { checkAccountHealth, getSecretsHealth, registerAccountProbe } from './health';
|
|
36
|
+
export type { AccountProbe } from './health';
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Projector registry and the re-projection pass.
|
|
3
|
+
*
|
|
4
|
+
* `reproject()` is the single entry point every mutation goes through —
|
|
5
|
+
* connect, credential change, capability toggle, enable/disable, disconnect.
|
|
6
|
+
* Having one pass rather than four call sites is what keeps "projections are
|
|
7
|
+
* derived" true: there is no path that changes an account without the surfaces
|
|
8
|
+
* being recomputed from it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { integrationAccountQueries, integrationProjectionQueries } from '$backend/database/queries';
|
|
12
|
+
import type { IntegrationAccountRow } from '$backend/database/queries';
|
|
13
|
+
import type { IntegrationCapability } from '$shared/types/integrations';
|
|
14
|
+
import { getProvider } from '../registry';
|
|
15
|
+
import { mcpProjector } from './mcp-projector';
|
|
16
|
+
import type { Projector, ProjectionContext } from './types';
|
|
17
|
+
import { debug } from '$shared/utils/logger';
|
|
18
|
+
|
|
19
|
+
export type { Projector, ProjectionContext, ProjectionResult } from './types';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One projector per capability that has a surface to project onto.
|
|
23
|
+
*
|
|
24
|
+
* A capability a provider declares but that has no projector here simply does
|
|
25
|
+
* not project — the account still records it, so the surface that lands later
|
|
26
|
+
* finds its accounts already connected.
|
|
27
|
+
*/
|
|
28
|
+
const PROJECTORS: Projector[] = [mcpProjector];
|
|
29
|
+
|
|
30
|
+
const byCapability = new Map(PROJECTORS.map((projector) => [projector.capability, projector]));
|
|
31
|
+
|
|
32
|
+
/** Register a projector from the surface that owns it. Called at module load. */
|
|
33
|
+
export function registerProjector(projector: Projector): void {
|
|
34
|
+
if (byCapability.has(projector.capability)) {
|
|
35
|
+
throw new Error(`A projector for "${projector.capability}" is already registered`);
|
|
36
|
+
}
|
|
37
|
+
byCapability.set(projector.capability, projector);
|
|
38
|
+
PROJECTORS.push(projector);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function contextFor(account: IntegrationAccountRow): ProjectionContext | null {
|
|
42
|
+
const provider = getProvider(account.provider);
|
|
43
|
+
if (!provider) {
|
|
44
|
+
debug.warn('integrations', `Account ${account.id} references unknown provider "${account.provider}"`);
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
account,
|
|
49
|
+
provider,
|
|
50
|
+
credentials: integrationAccountQueries.credentialsOf(account)
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Recompute every surface row this account owns.
|
|
56
|
+
*
|
|
57
|
+
* `wanted` is the set of capabilities that should be projected right now: the
|
|
58
|
+
* account's enabled capabilities, or nothing at all when the account is
|
|
59
|
+
* disabled. Anything projected that is not wanted gets released, which is how a
|
|
60
|
+
* capability toggle and a disconnect end up being the same operation.
|
|
61
|
+
*/
|
|
62
|
+
export function reproject(accountId: string, options: { releaseAll?: boolean } = {}): void {
|
|
63
|
+
const account = integrationAccountQueries.getById(accountId);
|
|
64
|
+
if (!account) return;
|
|
65
|
+
|
|
66
|
+
const context = contextFor(account);
|
|
67
|
+
if (!context) return;
|
|
68
|
+
|
|
69
|
+
const wanted: Set<IntegrationCapability> = options.releaseAll || account.is_enabled !== 1
|
|
70
|
+
? new Set()
|
|
71
|
+
: new Set(integrationAccountQueries.capabilitiesOf(account));
|
|
72
|
+
|
|
73
|
+
const current = integrationProjectionQueries.getForAccount(accountId);
|
|
74
|
+
|
|
75
|
+
// Release first. A capability turned off and a slug moved to another
|
|
76
|
+
// provider both look like "this projection is no longer wanted", and doing
|
|
77
|
+
// the releases before the projections keeps a slug from colliding with its
|
|
78
|
+
// own stale row.
|
|
79
|
+
for (const row of current) {
|
|
80
|
+
if (wanted.has(row.capability)) continue;
|
|
81
|
+
const projector = byCapability.get(row.capability);
|
|
82
|
+
if (projector) {
|
|
83
|
+
try {
|
|
84
|
+
projector.release(context, row.target_id, row.adopted === 1, integrationProjectionQueries.restoreOf(row));
|
|
85
|
+
} catch (error) {
|
|
86
|
+
debug.error('integrations', `Failed to release ${row.capability} for account ${accountId}:`, error);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
integrationProjectionQueries.remove(accountId, row.capability, row.target_kind);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
for (const capability of wanted) {
|
|
93
|
+
const projector = byCapability.get(capability);
|
|
94
|
+
if (!projector) continue;
|
|
95
|
+
try {
|
|
96
|
+
const result = projector.project(context);
|
|
97
|
+
integrationProjectionQueries.upsert({
|
|
98
|
+
accountId,
|
|
99
|
+
capability,
|
|
100
|
+
targetKind: result.targetKind,
|
|
101
|
+
targetId: result.targetId,
|
|
102
|
+
adopted: result.adopted,
|
|
103
|
+
restore: result.restore
|
|
104
|
+
});
|
|
105
|
+
} catch (error) {
|
|
106
|
+
debug.error('integrations', `Failed to project ${capability} for account ${accountId}:`, error);
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Release everything this account owns. Called immediately before deleting it. */
|
|
113
|
+
export function releaseAll(accountId: string): void {
|
|
114
|
+
reproject(accountId, { releaseAll: true });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Capabilities that currently have a surface to project onto. */
|
|
118
|
+
export function projectableCapabilities(): IntegrationCapability[] {
|
|
119
|
+
return [...byCapability.keys()];
|
|
120
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the agent-tools projection.
|
|
3
|
+
*
|
|
4
|
+
* The cases that matter are the ownership ones, because they are the ones that
|
|
5
|
+
* destroy something when they are wrong: adopting a hand-installed server must
|
|
6
|
+
* produce ONE entry rather than a sibling, and disconnecting must hand that
|
|
7
|
+
* server back with the credential the user had on it — not with ours, and not
|
|
8
|
+
* with an empty one.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'bun:test';
|
|
12
|
+
|
|
13
|
+
import { initializeDatabase, closeDatabase } from '$backend/database';
|
|
14
|
+
import { mcpServerQueries, integrationAccountQueries, integrationProjectionQueries } from '$backend/database/queries';
|
|
15
|
+
import { integrationAccounts } from '../accounts';
|
|
16
|
+
|
|
17
|
+
const FIRECRAWL_SLUG = 'firecrawl';
|
|
18
|
+
|
|
19
|
+
function parseEnv(slug: string): Record<string, string> {
|
|
20
|
+
const row = mcpServerQueries.getBySlug(slug);
|
|
21
|
+
if (!row) return {};
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(row.env) as Record<string, string>;
|
|
24
|
+
} catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function clearFixtures(): void {
|
|
30
|
+
for (const account of integrationAccountQueries.getAll()) {
|
|
31
|
+
integrationAccountQueries.remove(account.id);
|
|
32
|
+
}
|
|
33
|
+
const row = mcpServerQueries.getBySlug(FIRECRAWL_SLUG);
|
|
34
|
+
if (row) mcpServerQueries.remove(row.id);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
beforeAll(async () => {
|
|
38
|
+
await initializeDatabase();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
beforeEach(() => {
|
|
42
|
+
clearFixtures();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
afterAll(() => {
|
|
46
|
+
clearFixtures();
|
|
47
|
+
closeDatabase();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe('agent-tools projection', () => {
|
|
51
|
+
it('creates a connector row and removes it on disconnect', () => {
|
|
52
|
+
const account = integrationAccounts.connect({
|
|
53
|
+
provider: 'firecrawl',
|
|
54
|
+
credentials: { apiKey: 'fc-first' }
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const row = mcpServerQueries.getBySlug(FIRECRAWL_SLUG);
|
|
58
|
+
expect(row).not.toBe(null);
|
|
59
|
+
expect(parseEnv(FIRECRAWL_SLUG).FIRECRAWL_API_KEY).toBe('fc-first');
|
|
60
|
+
expect(account.projections[0]?.adopted).toBe(false);
|
|
61
|
+
|
|
62
|
+
integrationAccounts.disconnect(account.id);
|
|
63
|
+
expect(mcpServerQueries.getBySlug(FIRECRAWL_SLUG)).toBe(null);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('adopts a hand-installed server instead of creating a sibling', () => {
|
|
67
|
+
mcpServerQueries.insert({
|
|
68
|
+
slug: FIRECRAWL_SLUG,
|
|
69
|
+
name: 'My Firecrawl',
|
|
70
|
+
transport: 'stdio',
|
|
71
|
+
command: 'npx',
|
|
72
|
+
args: ['-y', 'firecrawl-mcp'],
|
|
73
|
+
env: { FIRECRAWL_API_KEY: 'fc-mine', EXTRA: 'keep-me' },
|
|
74
|
+
source: 'custom'
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const account = integrationAccounts.connect({
|
|
78
|
+
provider: 'firecrawl',
|
|
79
|
+
credentials: { apiKey: 'fc-account' }
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
expect(mcpServerQueries.getBySource('custom').filter((row) => row.slug === FIRECRAWL_SLUG).length).toBe(1);
|
|
83
|
+
expect(account.projections[0]?.adopted).toBe(true);
|
|
84
|
+
|
|
85
|
+
const env = parseEnv(FIRECRAWL_SLUG);
|
|
86
|
+
expect(env.FIRECRAWL_API_KEY).toBe('fc-account');
|
|
87
|
+
// An env var the preset says nothing about is the user's, and adopting
|
|
88
|
+
// must not quietly drop it.
|
|
89
|
+
expect(env.EXTRA).toBe('keep-me');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('hands an adopted server back with the user credential on disconnect', () => {
|
|
93
|
+
mcpServerQueries.insert({
|
|
94
|
+
slug: FIRECRAWL_SLUG,
|
|
95
|
+
name: 'My Firecrawl',
|
|
96
|
+
transport: 'stdio',
|
|
97
|
+
command: 'npx',
|
|
98
|
+
args: ['-y', 'firecrawl-mcp'],
|
|
99
|
+
env: { FIRECRAWL_API_KEY: 'fc-mine' },
|
|
100
|
+
source: 'custom'
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const account = integrationAccounts.connect({
|
|
104
|
+
provider: 'firecrawl',
|
|
105
|
+
credentials: { apiKey: 'fc-account' }
|
|
106
|
+
});
|
|
107
|
+
integrationAccounts.disconnect(account.id);
|
|
108
|
+
|
|
109
|
+
const row = mcpServerQueries.getBySlug(FIRECRAWL_SLUG);
|
|
110
|
+
expect(row).not.toBe(null);
|
|
111
|
+
expect(parseEnv(FIRECRAWL_SLUG).FIRECRAWL_API_KEY).toBe('fc-mine');
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('does not re-snapshot on re-projection, so release still restores the original', () => {
|
|
115
|
+
mcpServerQueries.insert({
|
|
116
|
+
slug: FIRECRAWL_SLUG,
|
|
117
|
+
name: 'My Firecrawl',
|
|
118
|
+
transport: 'stdio',
|
|
119
|
+
command: 'npx',
|
|
120
|
+
env: { FIRECRAWL_API_KEY: 'fc-mine' },
|
|
121
|
+
source: 'custom'
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const account = integrationAccounts.connect({
|
|
125
|
+
provider: 'firecrawl',
|
|
126
|
+
credentials: { apiKey: 'fc-account' }
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// A credential rotation re-projects. If that took a fresh snapshot it
|
|
130
|
+
// would capture OUR key, and release would "restore" a token we are about
|
|
131
|
+
// to delete.
|
|
132
|
+
integrationAccounts.updateCredentials(account.id, { apiKey: 'fc-rotated' });
|
|
133
|
+
expect(parseEnv(FIRECRAWL_SLUG).FIRECRAWL_API_KEY).toBe('fc-rotated');
|
|
134
|
+
|
|
135
|
+
integrationAccounts.disconnect(account.id);
|
|
136
|
+
expect(parseEnv(FIRECRAWL_SLUG).FIRECRAWL_API_KEY).toBe('fc-mine');
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('releases the connector when the capability is turned off, and projects again when back on', () => {
|
|
140
|
+
const account = integrationAccounts.connect({
|
|
141
|
+
provider: 'firecrawl',
|
|
142
|
+
credentials: { apiKey: 'fc-toggle' }
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
integrationAccounts.setCapabilities(account.id, []);
|
|
146
|
+
expect(mcpServerQueries.getBySlug(FIRECRAWL_SLUG)).toBe(null);
|
|
147
|
+
expect(integrationProjectionQueries.getForAccount(account.id).length).toBe(0);
|
|
148
|
+
|
|
149
|
+
integrationAccounts.setCapabilities(account.id, ['agent-tools']);
|
|
150
|
+
expect(parseEnv(FIRECRAWL_SLUG).FIRECRAWL_API_KEY).toBe('fc-toggle');
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('releases the connector while the account is disabled', () => {
|
|
154
|
+
const account = integrationAccounts.connect({
|
|
155
|
+
provider: 'firecrawl',
|
|
156
|
+
credentials: { apiKey: 'fc-disable' }
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
integrationAccounts.setEnabled(account.id, false);
|
|
160
|
+
expect(mcpServerQueries.getBySlug(FIRECRAWL_SLUG)).toBe(null);
|
|
161
|
+
|
|
162
|
+
integrationAccounts.setEnabled(account.id, true);
|
|
163
|
+
expect(mcpServerQueries.getBySlug(FIRECRAWL_SLUG)).not.toBe(null);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('refuses a second account that would fight over the same connector', () => {
|
|
167
|
+
integrationAccounts.connect({ provider: 'firecrawl', credentials: { apiKey: 'fc-one' } });
|
|
168
|
+
|
|
169
|
+
expect(() => integrationAccounts.connect({
|
|
170
|
+
provider: 'firecrawl',
|
|
171
|
+
label: 'Firecrawl (second org)',
|
|
172
|
+
credentials: { apiKey: 'fc-two' }
|
|
173
|
+
})).toThrow();
|
|
174
|
+
|
|
175
|
+
// The rejected account must not be left behind half-connected.
|
|
176
|
+
expect(integrationAccountQueries.getByProvider('firecrawl').length).toBe(1);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it('rejects a connect that is missing a required credential', () => {
|
|
180
|
+
expect(() => integrationAccounts.connect({
|
|
181
|
+
provider: 'firecrawl',
|
|
182
|
+
credentials: {}
|
|
183
|
+
})).toThrow();
|
|
184
|
+
expect(mcpServerQueries.getBySlug(FIRECRAWL_SLUG)).toBe(null);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it('stores the credential sealed and never returns it to the caller', () => {
|
|
188
|
+
const account = integrationAccounts.connect({
|
|
189
|
+
provider: 'context7',
|
|
190
|
+
credentials: { apiKey: 'ctx7sk-secret' }
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// The account DTO reports which fields are set, not what they are set to.
|
|
194
|
+
expect(account.configuredFields).toEqual(['apiKey']);
|
|
195
|
+
expect(JSON.stringify(account)).not.toContain('ctx7sk-secret');
|
|
196
|
+
|
|
197
|
+
const row = mcpServerQueries.getBySlug('context7');
|
|
198
|
+
expect(row).not.toBe(null);
|
|
199
|
+
expect(JSON.parse(row!.headers).CONTEXT7_API_KEY).toBe('ctx7sk-secret');
|
|
200
|
+
|
|
201
|
+
integrationAccounts.disconnect(account.id);
|
|
202
|
+
mcpServerQueries.getBySlug('context7') && mcpServerQueries.remove(mcpServerQueries.getBySlug('context7')!.id);
|
|
203
|
+
});
|
|
204
|
+
});
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `agent-tools` projector: an account with agent tools owns one
|
|
3
|
+
* `mcp_servers` row.
|
|
4
|
+
*
|
|
5
|
+
* Nothing downstream of this row knows accounts exist. `resolveServerRow()`,
|
|
6
|
+
* every per-engine config builder and the `/mcp/ext/<slug>` proxy read the row
|
|
7
|
+
* exactly as they read a hand-installed one — which is the whole point of
|
|
8
|
+
* keeping this layer off the path MCP config already flows through.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { mcpServerQueries, integrationProjectionQueries } from '$backend/database/queries';
|
|
12
|
+
import type { McpServerRow } from '$backend/database/queries';
|
|
13
|
+
import type { McpPreset } from '../registry';
|
|
14
|
+
import type { Projector, ProjectionContext, ProjectionResult } from './types';
|
|
15
|
+
import { debug } from '$shared/utils/logger';
|
|
16
|
+
|
|
17
|
+
/** Snapshot of the credential-bearing fields, taken before an adopted row is written. */
|
|
18
|
+
interface McpRestoreSnapshot {
|
|
19
|
+
env: Record<string, string>;
|
|
20
|
+
headers: Record<string, string>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function parseMap(raw: string | null): Record<string, string> {
|
|
24
|
+
if (!raw) return {};
|
|
25
|
+
try {
|
|
26
|
+
const parsed = JSON.parse(raw);
|
|
27
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
28
|
+
? (parsed as Record<string, string>)
|
|
29
|
+
: {};
|
|
30
|
+
} catch {
|
|
31
|
+
return {};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Map the stored credential onto the env vars the upstream server expects,
|
|
37
|
+
* keeping any keys already on the row.
|
|
38
|
+
*
|
|
39
|
+
* Merging rather than replacing matters for adoption: a user who installed this
|
|
40
|
+
* server by hand may have set env vars the preset says nothing about, and
|
|
41
|
+
* connecting an account must not silently drop them.
|
|
42
|
+
*/
|
|
43
|
+
function buildEnv(preset: McpPreset, credentials: Record<string, string>, existing: Record<string, string>): Record<string, string> {
|
|
44
|
+
const env = { ...existing, ...(preset.staticEnv ?? {}) };
|
|
45
|
+
for (const [field, variable] of Object.entries(preset.env ?? {})) {
|
|
46
|
+
const value = credentials[field];
|
|
47
|
+
if (value) env[variable] = value;
|
|
48
|
+
}
|
|
49
|
+
return env;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Same, for the remote path. `format` wraps the value, `Bearer {value}` being the usual case. */
|
|
53
|
+
function buildHeaders(preset: McpPreset, credentials: Record<string, string>, existing: Record<string, string>): Record<string, string> {
|
|
54
|
+
const headers = { ...existing, ...(preset.staticHeaders ?? {}) };
|
|
55
|
+
for (const [field, spec] of Object.entries(preset.headers ?? {})) {
|
|
56
|
+
const value = credentials[field];
|
|
57
|
+
if (!value) continue;
|
|
58
|
+
headers[spec.name] = spec.format ? spec.format.replace('{value}', value) : value;
|
|
59
|
+
}
|
|
60
|
+
return headers;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function presetOf(context: ProjectionContext): McpPreset {
|
|
64
|
+
const preset = context.provider.mcp;
|
|
65
|
+
if (!preset) {
|
|
66
|
+
throw new Error(`Provider "${context.provider.id}" offers agent tools but declares no MCP preset`);
|
|
67
|
+
}
|
|
68
|
+
return preset;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const mcpProjector: Projector = {
|
|
72
|
+
capability: 'agent-tools',
|
|
73
|
+
targetKind: 'mcp_server',
|
|
74
|
+
|
|
75
|
+
project(context: ProjectionContext): ProjectionResult {
|
|
76
|
+
const preset = presetOf(context);
|
|
77
|
+
const existing: McpServerRow | null = mcpServerQueries.getBySlug(preset.slug);
|
|
78
|
+
|
|
79
|
+
if (!existing) {
|
|
80
|
+
const row = mcpServerQueries.insert({
|
|
81
|
+
slug: preset.slug,
|
|
82
|
+
name: preset.name,
|
|
83
|
+
description: preset.description,
|
|
84
|
+
transport: preset.transport,
|
|
85
|
+
command: preset.command ?? null,
|
|
86
|
+
args: preset.args ?? [],
|
|
87
|
+
url: preset.url ?? null,
|
|
88
|
+
env: buildEnv(preset, context.credentials, {}),
|
|
89
|
+
headers: buildHeaders(preset, context.credentials, {}),
|
|
90
|
+
// Registry-installed vs hand-written is a provenance question about
|
|
91
|
+
// the CONFIG. Ownership by an account is a different question, and
|
|
92
|
+
// `integration_projections` is where it is answered — so this stays
|
|
93
|
+
// an ordinary custom row rather than needing a fourth source value.
|
|
94
|
+
source: 'custom'
|
|
95
|
+
});
|
|
96
|
+
return { targetKind: 'mcp_server', targetId: String(row.id), adopted: false, restore: null };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ADOPT rather than create a sibling. A user who installed this server by
|
|
100
|
+
// hand before the provider existed must end up with ONE entry.
|
|
101
|
+
const targetId = String(existing.id);
|
|
102
|
+
const prior = integrationProjectionQueries.getByTarget('mcp_server', targetId);
|
|
103
|
+
|
|
104
|
+
if (prior && prior.account_id !== context.account.id) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
`The "${preset.slug}" connector is already managed by another connected account. ` +
|
|
107
|
+
`Disconnect that one first.`
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Re-projecting a row we already own must not re-snapshot it — the second
|
|
112
|
+
// snapshot would capture OUR credential, and release would then "restore"
|
|
113
|
+
// the user's row to the token we are about to delete.
|
|
114
|
+
const adopted = prior ? prior.adopted === 1 : true;
|
|
115
|
+
const restore = prior
|
|
116
|
+
? integrationProjectionQueries.restoreOf<McpRestoreSnapshot>(prior)
|
|
117
|
+
: ({ env: parseMap(existing.env), headers: parseMap(existing.headers) } satisfies McpRestoreSnapshot);
|
|
118
|
+
|
|
119
|
+
if (!prior) {
|
|
120
|
+
debug.log('integrations', `Adopting existing MCP server "${preset.slug}" for ${context.provider.id}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
mcpServerQueries.updateConfig(
|
|
124
|
+
existing.id,
|
|
125
|
+
buildEnv(preset, context.credentials, parseMap(existing.env)),
|
|
126
|
+
buildHeaders(preset, context.credentials, parseMap(existing.headers))
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
// Only a row we created gets its transport-level config rewritten. On an
|
|
130
|
+
// adopted row the user's command, args and URL are theirs, and a preset
|
|
131
|
+
// that thinks it knows better would break a working server.
|
|
132
|
+
if (!adopted) {
|
|
133
|
+
if (preset.transport === 'stdio' && preset.command) {
|
|
134
|
+
mcpServerQueries.updateCommand(existing.id, preset.command, preset.args ?? []);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return { targetKind: 'mcp_server', targetId, adopted, restore };
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
release(context: ProjectionContext, targetId: string, adopted: boolean, restore: unknown | null): void {
|
|
142
|
+
const id = Number(targetId);
|
|
143
|
+
if (!Number.isFinite(id)) return;
|
|
144
|
+
|
|
145
|
+
if (!adopted) {
|
|
146
|
+
mcpServerQueries.remove(id);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// The row was the user's before it was ours. Put back exactly what we
|
|
151
|
+
// found, so what is left behind is their server, not a husk pointing at a
|
|
152
|
+
// credential that no longer exists.
|
|
153
|
+
const snapshot = (restore ?? { env: {}, headers: {} }) as McpRestoreSnapshot;
|
|
154
|
+
if (mcpServerQueries.getById(id)) {
|
|
155
|
+
mcpServerQueries.updateConfig(id, snapshot.env ?? {}, snapshot.headers ?? {});
|
|
156
|
+
debug.log('integrations', `Released adopted MCP server ${id} back to the user (${context.provider.id})`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
};
|