create-nextblock 0.14.5 → 0.14.6
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/package.json +1 -1
- package/templates/nextblock-template/AGENTS.md +9 -0
- package/templates/nextblock-template/CLAUDE.md +1 -0
- package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +96 -1
- package/templates/nextblock-template/app/api/mcp/route.ts +346 -0
- package/templates/nextblock-template/app/cms/settings/cortex-ai/McpServerSettingsCard.tsx +584 -0
- package/templates/nextblock-template/app/cms/settings/cortex-ai/StoredCortexAiSettingsClient.tsx +6 -0
- package/templates/nextblock-template/app/cms/settings/cortex-ai/actions.ts +4 -20
- package/templates/nextblock-template/app/cms/settings/cortex-ai/mcp-actions.ts +205 -0
- package/templates/nextblock-template/app/cms/settings/cortex-ai/page.tsx +64 -1
- package/templates/nextblock-template/app/cms/settings/cortex-ai/require-admin.ts +34 -0
- package/templates/nextblock-template/docs/04-DATABASE-AND-AUTH.md +31 -1
- package/templates/nextblock-template/docs/08-NEXTBLOCK-CORTEX-AI-ARCHITECTURE.md +151 -0
- package/templates/nextblock-template/lib/setup/migrations-bundle.ts +5 -0
- package/templates/nextblock-template/next-env.d.ts +2 -2
- package/templates/nextblock-template/package.json +1 -1
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
'use server';
|
|
2
|
+
|
|
3
|
+
import { revalidatePath } from 'next/cache';
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
CORTEX_AI_MCP_SETTINGS_KEY,
|
|
7
|
+
CORTEX_AI_MCP_TOKENS_TABLE,
|
|
8
|
+
mintCortexAiMcpToken,
|
|
9
|
+
normalizeCortexAiMcpSettings,
|
|
10
|
+
type CortexAiMcpScope,
|
|
11
|
+
type CortexAiMcpSettings,
|
|
12
|
+
} from '@nextblock-cms/cortex';
|
|
13
|
+
|
|
14
|
+
import { requireAdminSupabaseClient } from './require-admin';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Server actions for the "MCP server access" card.
|
|
18
|
+
*
|
|
19
|
+
* Unlike the rest of `actions.ts`, these return values instead of redirecting with a
|
|
20
|
+
* `?success=` message. A minted token is displayed exactly once and must never travel
|
|
21
|
+
* in a URL — it would land in browser history, the referrer header, and the server
|
|
22
|
+
* access log. Returning it to a client component that renders it in-place and forgets
|
|
23
|
+
* it keeps the secret out of every one of those.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const CORTEX_AI_SETTINGS_PATH = '/cms/settings/cortex-ai';
|
|
27
|
+
|
|
28
|
+
const MAX_TOKEN_NAME_LENGTH = 80;
|
|
29
|
+
const MAX_TOKENS = 20;
|
|
30
|
+
|
|
31
|
+
export type McpAccessTokenSummary = {
|
|
32
|
+
createdAt: string;
|
|
33
|
+
expiresAt: string | null;
|
|
34
|
+
id: string;
|
|
35
|
+
lastUsedAt: string | null;
|
|
36
|
+
name: string;
|
|
37
|
+
scopes: CortexAiMcpScope[];
|
|
38
|
+
tokenPrefix: string;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export type McpSettingsStatus = {
|
|
42
|
+
settings: CortexAiMcpSettings;
|
|
43
|
+
tokens: McpAccessTokenSummary[];
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
function toScopeList(raw: unknown): CortexAiMcpScope[] {
|
|
47
|
+
const list = Array.isArray(raw) ? raw : [];
|
|
48
|
+
const scopes = list.filter(
|
|
49
|
+
(entry): entry is CortexAiMcpScope => entry === 'read' || entry === 'write'
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
return scopes.length > 0 ? Array.from(new Set(scopes)) : ['read'];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Load MCP settings and the non-secret token list.
|
|
57
|
+
*
|
|
58
|
+
* Revoked tokens are filtered out rather than deleted at revoke time so the row keeps
|
|
59
|
+
* acting as a tombstone: the hash stays in the unique index, which makes an
|
|
60
|
+
* accidental re-mint of the same value impossible.
|
|
61
|
+
*/
|
|
62
|
+
export async function getMcpSettingsStatus(): Promise<McpSettingsStatus> {
|
|
63
|
+
const { supabase } = await requireAdminSupabaseClient();
|
|
64
|
+
|
|
65
|
+
const [{ data: settingsRow }, { data: tokenRows }] = await Promise.all([
|
|
66
|
+
supabase.from('site_settings').select('value').eq('key', CORTEX_AI_MCP_SETTINGS_KEY).maybeSingle(),
|
|
67
|
+
supabase
|
|
68
|
+
.from(CORTEX_AI_MCP_TOKENS_TABLE)
|
|
69
|
+
.select('id, name, scopes, token_prefix, created_at, expires_at, last_used_at, revoked_at')
|
|
70
|
+
.is('revoked_at', null)
|
|
71
|
+
.order('created_at', { ascending: false })
|
|
72
|
+
.limit(MAX_TOKENS),
|
|
73
|
+
]);
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
settings: normalizeCortexAiMcpSettings(settingsRow?.value),
|
|
77
|
+
tokens: (tokenRows ?? []).map((row: Record<string, any>) => ({
|
|
78
|
+
createdAt: row.created_at,
|
|
79
|
+
expiresAt: row.expires_at,
|
|
80
|
+
id: row.id,
|
|
81
|
+
lastUsedAt: row.last_used_at,
|
|
82
|
+
name: row.name,
|
|
83
|
+
scopes: toScopeList(row.scopes),
|
|
84
|
+
tokenPrefix: row.token_prefix,
|
|
85
|
+
})),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function saveMcpSettingsAction(input: {
|
|
90
|
+
allowLocalhostWithoutToken: boolean;
|
|
91
|
+
enabled: boolean;
|
|
92
|
+
}): Promise<{ error?: string; success: boolean }> {
|
|
93
|
+
try {
|
|
94
|
+
const { supabase } = await requireAdminSupabaseClient();
|
|
95
|
+
const value = normalizeCortexAiMcpSettings(input);
|
|
96
|
+
|
|
97
|
+
const { error } = await supabase
|
|
98
|
+
.from('site_settings')
|
|
99
|
+
.upsert({ key: CORTEX_AI_MCP_SETTINGS_KEY, value });
|
|
100
|
+
|
|
101
|
+
if (error) {
|
|
102
|
+
throw new Error(error.message);
|
|
103
|
+
}
|
|
104
|
+
} catch (error) {
|
|
105
|
+
return {
|
|
106
|
+
error: error instanceof Error ? error.message : 'Failed to save MCP server settings.',
|
|
107
|
+
success: false,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
revalidatePath(CORTEX_AI_SETTINGS_PATH);
|
|
112
|
+
return { success: true };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function createMcpAccessTokenAction(input: {
|
|
116
|
+
expiresInDays?: number | null;
|
|
117
|
+
name: string;
|
|
118
|
+
scopes: CortexAiMcpScope[];
|
|
119
|
+
}): Promise<{ error?: string; success: boolean; token?: string; tokenPrefix?: string }> {
|
|
120
|
+
try {
|
|
121
|
+
const { supabase, userId } = await requireAdminSupabaseClient();
|
|
122
|
+
|
|
123
|
+
const name = String(input.name || '').trim().slice(0, MAX_TOKEN_NAME_LENGTH);
|
|
124
|
+
|
|
125
|
+
if (!name) {
|
|
126
|
+
throw new Error('Give the token a name so you can tell your clients apart later.');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const scopes = toScopeList(input.scopes);
|
|
130
|
+
|
|
131
|
+
const { count } = await supabase
|
|
132
|
+
.from(CORTEX_AI_MCP_TOKENS_TABLE)
|
|
133
|
+
.select('id', { count: 'exact', head: true })
|
|
134
|
+
.is('revoked_at', null);
|
|
135
|
+
|
|
136
|
+
if ((count ?? 0) >= MAX_TOKENS) {
|
|
137
|
+
throw new Error(
|
|
138
|
+
`You already have ${MAX_TOKENS} active MCP tokens. Revoke one before creating another.`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const expiresInDays =
|
|
143
|
+
typeof input.expiresInDays === 'number' && Number.isFinite(input.expiresInDays)
|
|
144
|
+
? Math.min(3650, Math.max(1, Math.round(input.expiresInDays)))
|
|
145
|
+
: null;
|
|
146
|
+
|
|
147
|
+
const expiresAt = expiresInDays
|
|
148
|
+
? new Date(Date.now() + expiresInDays * 24 * 60 * 60 * 1000).toISOString()
|
|
149
|
+
: null;
|
|
150
|
+
|
|
151
|
+
const minted = mintCortexAiMcpToken();
|
|
152
|
+
|
|
153
|
+
const { error } = await supabase.from(CORTEX_AI_MCP_TOKENS_TABLE).insert({
|
|
154
|
+
created_by: userId,
|
|
155
|
+
expires_at: expiresAt,
|
|
156
|
+
name,
|
|
157
|
+
scopes,
|
|
158
|
+
token_hash: minted.tokenHash,
|
|
159
|
+
token_prefix: minted.tokenPrefix,
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
if (error) {
|
|
163
|
+
throw new Error(error.message);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
revalidatePath(CORTEX_AI_SETTINGS_PATH);
|
|
167
|
+
|
|
168
|
+
return { success: true, token: minted.token, tokenPrefix: minted.tokenPrefix };
|
|
169
|
+
} catch (error) {
|
|
170
|
+
return {
|
|
171
|
+
error: error instanceof Error ? error.message : 'Failed to create the MCP access token.',
|
|
172
|
+
success: false,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function revokeMcpAccessTokenAction(input: {
|
|
178
|
+
id: string;
|
|
179
|
+
}): Promise<{ error?: string; success: boolean }> {
|
|
180
|
+
try {
|
|
181
|
+
const { supabase } = await requireAdminSupabaseClient();
|
|
182
|
+
const id = String(input.id || '').trim();
|
|
183
|
+
|
|
184
|
+
if (!id) {
|
|
185
|
+
throw new Error('Missing token id.');
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const { error } = await supabase
|
|
189
|
+
.from(CORTEX_AI_MCP_TOKENS_TABLE)
|
|
190
|
+
.update({ revoked_at: new Date().toISOString() })
|
|
191
|
+
.eq('id', id);
|
|
192
|
+
|
|
193
|
+
if (error) {
|
|
194
|
+
throw new Error(error.message);
|
|
195
|
+
}
|
|
196
|
+
} catch (error) {
|
|
197
|
+
return {
|
|
198
|
+
error: error instanceof Error ? error.message : 'Failed to revoke the MCP access token.',
|
|
199
|
+
success: false,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
revalidatePath(CORTEX_AI_SETTINGS_PATH);
|
|
204
|
+
return { success: true };
|
|
205
|
+
}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import { headers } from 'next/headers';
|
|
2
|
+
|
|
1
3
|
import { listCortexAiCompatibleOpenRouterModels } from '@nextblock-cms/cortex';
|
|
2
4
|
import { getCortexAiSettingsStatus } from './actions';
|
|
5
|
+
import { getMcpSettingsStatus } from './mcp-actions';
|
|
6
|
+
import { McpServerSettingsCard } from './McpServerSettingsCard';
|
|
3
7
|
import { SandboxCortexAiSettingsClient } from './SandboxCortexAiSettingsClient';
|
|
4
8
|
import { StoredCortexAiSettingsClient } from './StoredCortexAiSettingsClient';
|
|
5
9
|
import { redirect } from 'next/navigation';
|
|
@@ -22,6 +26,51 @@ function formatDate(value: string | null) {
|
|
|
22
26
|
}).format(new Date(value));
|
|
23
27
|
}
|
|
24
28
|
|
|
29
|
+
/**
|
|
30
|
+
* The origin an external MCP client should dial.
|
|
31
|
+
*
|
|
32
|
+
* Prefers NEXT_PUBLIC_URL (the deployed canonical origin) and falls back to the
|
|
33
|
+
* request's own host, so the snippet is correct on a preview deployment or a custom
|
|
34
|
+
* domain that was never written into the env.
|
|
35
|
+
*/
|
|
36
|
+
async function resolveSiteOrigin(): Promise<string> {
|
|
37
|
+
const configured = process.env.NEXT_PUBLIC_URL?.trim();
|
|
38
|
+
|
|
39
|
+
if (configured) {
|
|
40
|
+
return configured.replace(/\/+$/, '');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const headerList = await headers();
|
|
44
|
+
const host = headerList.get('host');
|
|
45
|
+
|
|
46
|
+
if (!host) {
|
|
47
|
+
return 'https://your-site.com';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const protocol = headerList.get('x-forwarded-proto') || (host.startsWith('localhost') ? 'http' : 'https');
|
|
51
|
+
|
|
52
|
+
return `${protocol}://${host}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The loopback origin to show in the "Localhost" client snippets.
|
|
57
|
+
*
|
|
58
|
+
* Ports differ per setup — `nx serve nextblock` uses Nx's default 4200, not Next's
|
|
59
|
+
* plain 3000 — and a snippet pointing at the wrong port fails with a bare connection
|
|
60
|
+
* error that gives the reader nothing to go on. When this page is itself being viewed
|
|
61
|
+
* over loopback, that request's own host is the authoritative answer.
|
|
62
|
+
*/
|
|
63
|
+
async function resolveLocalOrigin(): Promise<string> {
|
|
64
|
+
const headerList = await headers();
|
|
65
|
+
const host = headerList.get('host')?.trim();
|
|
66
|
+
|
|
67
|
+
if (host && /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(host)) {
|
|
68
|
+
return `http://${host}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return 'http://localhost:4200';
|
|
72
|
+
}
|
|
73
|
+
|
|
25
74
|
export default async function CortexAiSettingsPage({
|
|
26
75
|
searchParams,
|
|
27
76
|
}: CortexAiSettingsPageProps) {
|
|
@@ -70,6 +119,12 @@ export default async function CortexAiSettingsPage({
|
|
|
70
119
|
);
|
|
71
120
|
}
|
|
72
121
|
|
|
122
|
+
const [mcpStatus, siteOrigin, localOrigin] = await Promise.all([
|
|
123
|
+
getMcpSettingsStatus(),
|
|
124
|
+
resolveSiteOrigin(),
|
|
125
|
+
resolveLocalOrigin(),
|
|
126
|
+
]);
|
|
127
|
+
|
|
73
128
|
return (
|
|
74
129
|
<StoredCortexAiSettingsClient
|
|
75
130
|
compatibleModels={compatibleModels as any}
|
|
@@ -95,6 +150,14 @@ export default async function CortexAiSettingsPage({
|
|
|
95
150
|
agentSettings={status.agentSettings}
|
|
96
151
|
successMessage={params.success}
|
|
97
152
|
errorMessage={params.error}
|
|
98
|
-
|
|
153
|
+
>
|
|
154
|
+
<McpServerSettingsCard
|
|
155
|
+
allowLocalhostWithoutToken={mcpStatus.settings.allowLocalhostWithoutToken}
|
|
156
|
+
enabled={mcpStatus.settings.enabled}
|
|
157
|
+
localMcpUrl={`${localOrigin}/api/mcp`}
|
|
158
|
+
mcpUrl={`${siteOrigin}/api/mcp`}
|
|
159
|
+
tokens={mcpStatus.tokens}
|
|
160
|
+
/>
|
|
161
|
+
</StoredCortexAiSettingsClient>
|
|
99
162
|
);
|
|
100
163
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { createClient } from '@nextblock-cms/db/server';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Admin gate shared by the Cortex AI settings server actions.
|
|
5
|
+
*
|
|
6
|
+
* Lives outside `actions.ts` because that file is `'use server'`, where every export
|
|
7
|
+
* must itself be a valid server action — a helper returning a Supabase client cannot
|
|
8
|
+
* be exported from there. Keeping one copy matters more than the file count: this is
|
|
9
|
+
* the check standing between a WRITER and the OpenRouter key, the stock-photo keys,
|
|
10
|
+
* and the MCP access tokens.
|
|
11
|
+
*/
|
|
12
|
+
export async function requireAdminSupabaseClient() {
|
|
13
|
+
const supabase = createClient();
|
|
14
|
+
const {
|
|
15
|
+
data: { user },
|
|
16
|
+
error: userError,
|
|
17
|
+
} = await supabase.auth.getUser();
|
|
18
|
+
|
|
19
|
+
if (userError || !user) {
|
|
20
|
+
throw new Error('You must be logged in to manage Cortex AI settings.');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const { data: profile, error: profileError } = await supabase
|
|
24
|
+
.from('profiles')
|
|
25
|
+
.select('role')
|
|
26
|
+
.eq('id', user.id)
|
|
27
|
+
.single();
|
|
28
|
+
|
|
29
|
+
if (profileError || !profile || profile.role !== 'ADMIN') {
|
|
30
|
+
throw new Error('You do not have permission to manage Cortex AI settings.');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return { supabase, userId: user.id };
|
|
34
|
+
}
|
|
@@ -198,7 +198,13 @@ production or shared database change.
|
|
|
198
198
|
`libs/db/src/supabase/migrations` for each new schema/data change.
|
|
199
199
|
- Keep migrations non-destructive by default. Avoid dropping or rewriting data
|
|
200
200
|
that may include orders, users, payments, or customer records.
|
|
201
|
-
- Run `npm run db:migrate:check` before `npm run db:migrate`.
|
|
201
|
+
- Run `npm run db:migrate:check` before `npm run db:migrate`. **Read its pending
|
|
202
|
+
list** — do not just look for a success line. If you added a migration and the
|
|
203
|
+
check reports `Pending: 0`, that file will never run (see below).
|
|
204
|
+
- **Supabase matches migration history by version only, never by content.** A file
|
|
205
|
+
whose 14-digit version is already recorded remotely is skipped in silence — no
|
|
206
|
+
error, no output. That is why the check prints the pending list and warns when a
|
|
207
|
+
version is recorded remotely with no local file behind it.
|
|
202
208
|
- If an existing database lists old baseline files such as
|
|
203
209
|
`00000000000000_baseline_schema.sql` as pending, do not replay them. Use
|
|
204
210
|
`npm run db:migrate:repair-history:check`, then
|
|
@@ -207,6 +213,30 @@ production or shared database change.
|
|
|
207
213
|
rerun `npm run db:migrate:check`.
|
|
208
214
|
- Use `npm run db:migrate:fresh` only for a brand-new empty database.
|
|
209
215
|
|
|
216
|
+
#### Why `db:migrate:check` is read-only by construction
|
|
217
|
+
|
|
218
|
+
On 2026-08-10 the check applied migration `00000000000017` to the production
|
|
219
|
+
project while printing `DRY RUN: migrations will *not* be pushed` and `Dry run
|
|
220
|
+
complete. No database changes were applied.` The `--check` path then ran
|
|
221
|
+
`supabase link --yes` followed by `supabase db push --dry-run` (Supabase CLI
|
|
222
|
+
v2.107); which of the two executed the SQL was never established, and the decisive
|
|
223
|
+
probe would have written a row to the production migration history.
|
|
224
|
+
|
|
225
|
+
`tools/scripts/push-db-migrations.js` no longer runs either on the check path. It
|
|
226
|
+
now runs only `supabase migration list` — a pure read — and derives the pending set
|
|
227
|
+
by diffing local files against remote history. Consequences worth keeping:
|
|
228
|
+
|
|
229
|
+
- The check links nothing. An unlinked repo is told to run `supabase link` itself
|
|
230
|
+
rather than having project state written underneath a command called "check".
|
|
231
|
+
- The check needs no `SUPABASE_ACCESS_TOKEN`, because only linking did.
|
|
232
|
+
- The apply path derives its baseline-replay guard from the same read instead of
|
|
233
|
+
regex-scraping `db push --dry-run` output, and returns early when nothing is
|
|
234
|
+
pending, so `db push` is never invoked without work to do.
|
|
235
|
+
- `parseMigrationList` is unit-tested in `tools/scripts/push-db-migrations.test.ts`.
|
|
236
|
+
|
|
237
|
+
If a future CLI upgrade tempts you back toward `db push --dry-run` for previewing:
|
|
238
|
+
don't. A command named `check` must not be able to write.
|
|
239
|
+
|
|
210
240
|
### Category map
|
|
211
241
|
|
|
212
242
|
| Migration file | Domain | What it covers |
|
|
@@ -1060,6 +1060,157 @@ Unsplash has strict usage rules; Pexels' license is permissive (attribution opti
|
|
|
1060
1060
|
- `importExternalImageToMedia` (`apps/nextblock/app/cms/media/import-external-image.ts`, ADMIN/WRITER) downloads an external image (SSRF-guarded, 15MB/15s caps), measures it with `sharp`, generates a blur placeholder, uploads to R2/Supabase Storage via the shared storage provider, and records it with `recordMediaUpload`. Returns `{ media_id, object_key, width, height, url, blur_data_url }`.
|
|
1061
1061
|
- Editor UX: `ImageBlockEditor` and `BackgroundSelector` accept a pasted image URL and show a **Save to media library** action that swaps the external URL for a permanent optimized media reference (or the author can replace it with their own uploaded asset).
|
|
1062
1062
|
|
|
1063
|
+
## MCP Server (external client access)
|
|
1064
|
+
|
|
1065
|
+
Cortex AI is dual-access. Alongside the in-app BYOK path (dashboard chat + inline
|
|
1066
|
+
editor), the same tool registry is exposed over the **Model Context Protocol** at
|
|
1067
|
+
`/api/mcp`, so Claude Code, Claude Desktop, Cursor, and VS Code can operate the CMS
|
|
1068
|
+
from inside the editor.
|
|
1069
|
+
|
|
1070
|
+
### Files
|
|
1071
|
+
|
|
1072
|
+
| File | Purpose |
|
|
1073
|
+
| --- | --- |
|
|
1074
|
+
| `libs/cortex/src/lib/mcp-server.ts` | Transport-agnostic JSON-RPC 2.0 engine. No `next` imports, so it is unit-testable. |
|
|
1075
|
+
| `libs/cortex/src/lib/mcp-tool-registry.ts` | Zod→JSON Schema conversion, read/write scope table, MCP-contract aliases, tool dispatch, resources, prompts. |
|
|
1076
|
+
| `libs/cortex/src/lib/mcp-tokens.ts` | Token mint/hash/verify, MCP settings resolver, localhost-trust rules. |
|
|
1077
|
+
| `libs/cortex/src/lib/mcp-server.test.ts` | 33 tests across tokens, registry, and protocol. |
|
|
1078
|
+
| `apps/nextblock/app/api/mcp/route.ts` | Streamable HTTP shim + hybrid auth + tool-context construction. |
|
|
1079
|
+
| `apps/nextblock/app/cms/settings/cortex-ai/mcp-actions.ts` | Admin server actions: settings, mint, revoke. |
|
|
1080
|
+
| `apps/nextblock/app/cms/settings/cortex-ai/McpServerSettingsCard.tsx` | Settings UI + copy-paste client config. |
|
|
1081
|
+
| `apps/nextblock/app/cms/settings/cortex-ai/require-admin.ts` | Shared admin gate (also used by `actions.ts`). |
|
|
1082
|
+
| `libs/db/src/supabase/migrations/00000000000017_cortex_ai_mcp_server.sql` | `mcp_access_tokens` table + `cortex_ai_mcp_settings` RLS. |
|
|
1083
|
+
|
|
1084
|
+
### Protocol decisions
|
|
1085
|
+
|
|
1086
|
+
**Hand-rolled, not `@modelcontextprotocol/sdk`.** The needed surface (initialize,
|
|
1087
|
+
tools/list, tools/call, resources/*, prompts/*, ping) is small and declarative. The v1
|
|
1088
|
+
SDK pulls in `express`, `cors`, `hono`, and `@hono/node-server` — heavy transitive
|
|
1089
|
+
weight for a publishable lib whose only peer dependency is `next` — and its default
|
|
1090
|
+
`StreamableHTTPServerTransport` is built on Node `IncomingMessage`/`ServerResponse`
|
|
1091
|
+
rather than the Web `Request`/`Response` an App Router handler receives.
|
|
1092
|
+
|
|
1093
|
+
**Dual-era.** The spec forked: `2026-07-28` is stateless (no `initialize`, no session
|
|
1094
|
+
id, protocol metadata in a per-request `_meta` envelope), while everything through
|
|
1095
|
+
`2025-11-25` is handshake-based. As of 2026-08 every shipping client is legacy-era, so
|
|
1096
|
+
that path must work; the modern path is detected and served too. Because the server is
|
|
1097
|
+
stateless either way, supporting both costs nothing.
|
|
1098
|
+
|
|
1099
|
+
Deliberate behaviours, each of which breaks a real client if changed:
|
|
1100
|
+
|
|
1101
|
+
- **Notifications get `202 Accepted` with an empty body.** Returning a JSON-RPC
|
|
1102
|
+
envelope for a message with no `id` desyncs strict clients.
|
|
1103
|
+
- **GET returns `405`.** The server never initiates requests or pushes unsolicited
|
|
1104
|
+
notifications, so there is no stream to open. The spec explicitly allows 405 here.
|
|
1105
|
+
- **401 carries a bare `WWW-Authenticate: Bearer`.** Adding a `resource_metadata`
|
|
1106
|
+
parameter (or serving `/.well-known/oauth-protected-resource`) advertises RFC 9728
|
|
1107
|
+
OAuth discovery, and Claude Code responds by starting an OAuth flow that dead-ends
|
|
1108
|
+
against a static-token server.
|
|
1109
|
+
- **Tool failures are `isError: true` on a *successful* result**, not JSON-RPC errors.
|
|
1110
|
+
Only unknown-tool and scope denial use the error channel, because those are the
|
|
1111
|
+
faults a model cannot fix by retrying with different arguments.
|
|
1112
|
+
- **`inputSchema` is always a JSON Schema object** with `$schema` stripped (MCP defines
|
|
1113
|
+
the dialect; some clients reject the extra key). Converted with `io: 'input'` so
|
|
1114
|
+
`.default()` fields stay optional.
|
|
1115
|
+
- **Array bodies are rejected.** JSON-RPC batching was removed in `2025-06-18`.
|
|
1116
|
+
- **`Origin` is validated when present** (DNS-rebinding defence, a spec MUST) and
|
|
1117
|
+
answered with 403. Native clients send no Origin, so absence is allowed.
|
|
1118
|
+
|
|
1119
|
+
### Authentication
|
|
1120
|
+
|
|
1121
|
+
Three accepted paths, in priority order, all gated behind
|
|
1122
|
+
`verifyPackageOnline('cortex-ai')` and the `enabled` setting:
|
|
1123
|
+
|
|
1124
|
+
1. **Bearer token** from `public.mcp_access_tokens` — what every external client uses.
|
|
1125
|
+
2. **Authenticated ADMIN cookie session** — lets the dashboard reach the endpoint
|
|
1126
|
+
without minting a token.
|
|
1127
|
+
3. **Loopback in development** — only when `allowLocalhostWithoutToken` is on *and*
|
|
1128
|
+
`NODE_ENV !== 'production'`. Behind a proxy the `Host` header is attacker-
|
|
1129
|
+
controllable, so localhost trust is a development affordance only.
|
|
1130
|
+
|
|
1131
|
+
Tokens are stored as **SHA-256 hashes**; the plaintext (`nbmcp_` + 256 bits base64url)
|
|
1132
|
+
is shown once at mint time and is unrecoverable. This differs from the OpenRouter BYOK
|
|
1133
|
+
key on purpose: that key must be handed back to OpenRouter, so it needs a reversible
|
|
1134
|
+
envelope, whereas an MCP token only ever needs to be *compared*. `token_prefix` is a
|
|
1135
|
+
non-secret display fragment. Revocation is a tombstone (`revoked_at`), which keeps the
|
|
1136
|
+
hash in the unique index so the same value can never be re-minted.
|
|
1137
|
+
|
|
1138
|
+
The minted token is returned through a **server action return value**, never a redirect
|
|
1139
|
+
query string — a `?success=<token>` would land in browser history, the referrer header,
|
|
1140
|
+
and the server access log.
|
|
1141
|
+
|
|
1142
|
+
### Scopes
|
|
1143
|
+
|
|
1144
|
+
`CORTEX_MCP_TOOL_KINDS` classifies all 29 registry tools as `read` or `write`. A
|
|
1145
|
+
read-only token does not merely get refused on a write — the mutating tools are absent
|
|
1146
|
+
from its `tools/list` entirely, aliases included.
|
|
1147
|
+
|
|
1148
|
+
The table is **exhaustive by construction**: `assertCortexMcpToolCoverage` compares its
|
|
1149
|
+
keys against the live factory output, and a unit test fails if they diverge. An
|
|
1150
|
+
unclassified tool is *withheld*, never defaulted to `read`, so adding a tool to the
|
|
1151
|
+
agent without classifying it is a loud failure rather than a silent hole.
|
|
1152
|
+
|
|
1153
|
+
### Confirmation is skipped over MCP
|
|
1154
|
+
|
|
1155
|
+
The in-app two-phase confirm matches a phrase in the user's *next chat message*, which
|
|
1156
|
+
has no analogue in MCP — there is no channel to carry a human phrase back between a
|
|
1157
|
+
tool call and its result. Every MCP host already gates tool calls behind its own
|
|
1158
|
+
approval UI, so leaving it on would just make every mutating tool return a preview
|
|
1159
|
+
forever. The real control is the token scope. `ToolExecutionContext.skipConfirmation`
|
|
1160
|
+
is therefore `true` for all MCP calls.
|
|
1161
|
+
|
|
1162
|
+
### MCP-contract tool names
|
|
1163
|
+
|
|
1164
|
+
Five names are exposed as aliases forwarding to existing executors, so external clients
|
|
1165
|
+
get the documented contract without forking tested code. The canonical names remain
|
|
1166
|
+
listed too, and each alias description begins with "Alias of `<canonical>`" so a model
|
|
1167
|
+
does not call both.
|
|
1168
|
+
|
|
1169
|
+
| MCP name | Forwards to |
|
|
1170
|
+
| --- | --- |
|
|
1171
|
+
| `get_database_schema` | `describe_database_schema` |
|
|
1172
|
+
| `generate_jsonb_layout` | `rewrite_page_draft` (stages a Live Draft; nothing goes live unpublished) |
|
|
1173
|
+
| `query_site_analytics` | `fetch_ecommerce_stats` |
|
|
1174
|
+
| `update_site_navigation` | `update_navigation_bar` |
|
|
1175
|
+
| `search_stock_media` | `search_stock_photos` |
|
|
1176
|
+
|
|
1177
|
+
### Resources and prompts
|
|
1178
|
+
|
|
1179
|
+
Resources: `cortex://schema/database`, `cortex://schema/blocks`,
|
|
1180
|
+
`cortex://schema/custom-blocks`. Prompts: `build-page`, `clone-from-url`,
|
|
1181
|
+
`translate-content`.
|
|
1182
|
+
|
|
1183
|
+
### Settings and client configuration
|
|
1184
|
+
|
|
1185
|
+
`/cms/settings/cortex-ai` gains an "MCP server access" card: enable/disable, localhost
|
|
1186
|
+
trust, token mint/revoke, and copy-paste config for all four clients. **The server is
|
|
1187
|
+
disabled by default** — it is a remote write surface onto live content, so it must be
|
|
1188
|
+
an explicit opt-in.
|
|
1189
|
+
|
|
1190
|
+
Client config differs in ways that silently no-op if copied wrong, which is why the UI
|
|
1191
|
+
generates each one rather than documenting a single snippet:
|
|
1192
|
+
|
|
1193
|
+
- **Claude Code** — `mcpServers`, and `"type": "http"` is *required* (a `url` with no
|
|
1194
|
+
`type` is a hard error that skips the server).
|
|
1195
|
+
- **Cursor** — `mcpServers`, infers transport from `url`, no `type` needed.
|
|
1196
|
+
- **VS Code** — top-level `servers`, **not** `mcpServers`, and prompts for the token
|
|
1197
|
+
via `inputs` rather than storing it.
|
|
1198
|
+
- **Claude Desktop** — `claude_desktop_config.json` is stdio-only, so a remote server
|
|
1199
|
+
needs either the Connectors UI (which dials out from Anthropic's cloud, so localhost
|
|
1200
|
+
and firewalled sites will not connect) or the `mcp-remote` stdio bridge.
|
|
1201
|
+
|
|
1202
|
+
### Related hardening
|
|
1203
|
+
|
|
1204
|
+
`read_database_records` previously filtered only `cortex_ai_openrouter_api_key` from
|
|
1205
|
+
`site_settings`. The `isSensitiveKey` heuristic inspects *column names*, and a
|
|
1206
|
+
site_settings row is `{ key, value }` — neither name trips it, so the stock-photo and
|
|
1207
|
+
payment/email secret rows passed through. That was low-risk while the tool was
|
|
1208
|
+
dashboard-only; exposing it to remote MCP clients widened it. `ai-global-agent-db-tools.ts`
|
|
1209
|
+
now carries `PROTECTED_SITE_SETTING_KEYS`, redacted on read and refused on write.
|
|
1210
|
+
|
|
1211
|
+
`mcp_access_tokens` is deliberately **absent** from `tableConfigs`, so the generic DB
|
|
1212
|
+
tools cannot read token hashes or insert rows.
|
|
1213
|
+
|
|
1063
1214
|
## Advanced Agent Settings
|
|
1064
1215
|
|
|
1065
1216
|
The global agent's model limits are admin-tunable from `/cms/settings/cortex-ai` (collapsible "Advanced settings"), stored as a non-secret JSON `site_settings` row `cortex_ai_agent_settings` and read by the route via `resolveCortexAiAgentSettings(supabase)` (defaults + clamping in `normalizeCortexAiAgentSettings`, `libs/cortex/src/lib/ai-config.ts`):
|
|
@@ -98,5 +98,10 @@ export const MIGRATIONS_BUNDLE: BundledMigration[] = [
|
|
|
98
98
|
"version": "00000000000016",
|
|
99
99
|
"name": "00000000000016_product_revisions_and_revision_baseline.sql",
|
|
100
100
|
"sql": "-- 00000000000016_product_revisions_and_revision_baseline.sql\n--\n-- Revision History, part 1 of 2 (schema). The application-side rewrite lives in\n-- apps/nextblock/app/cms/revisions/**.\n--\n-- Three things happen here:\n--\n-- 1. products.version — the monotonic counter the hybrid revision engine drives,\n-- mirroring pages.version / posts.version.\n--\n-- 2. product_revisions — a structural mirror of page_revisions / post_revisions.\n-- product_id is uuid (products.id is uuid, not bigint), and\n-- writes are gated on is_admin() to match products_*_policy\n-- rather than the ADMIN|WRITER pattern the page/post revision\n-- tables use. A WRITER who could insert a revision but not\n-- apply a restore would get a silent no-op restore, because\n-- PostgREST returns no error for an UPDATE matching zero rows.\n--\n-- 3. Revision baseline — every page, post and product gets a real `snapshot` row to\n-- restore to. Until now the CMS synthesised a fake \"Initial\n-- Version\" entry in the UI whose Restore button resolved to\n-- \"current metadata + zero blocks\" and wiped the content.\n-- There is now an actual stored baseline instead.\n--\n-- Case A (version = 1, no revisions at all): the live row IS\n-- version 1. This covers seeded content — 00000000000003\n-- inserts every page and post at version 1 and writes no\n-- revision rows — and everything authored since the CMS save\n-- path stopped recording revisions. Snapshotting it at\n-- version 1 is what makes \"restore the original seeded page\"\n-- real for the first time.\n--\n-- Case B (version > 1 but no snapshot at or below it): the\n-- true v1 is unrecoverable and is NOT fabricated. A snapshot\n-- of the current state is stored at the current version so the\n-- diff chain has a valid base and future restores resolve.\n--\n-- Forward-only, idempotent, and it modifies no existing row: every backfill is an\n-- INSERT ... WHERE NOT EXISTS ... ON CONFLICT DO NOTHING.\n\n-- ---------------------------------------------------------------------------\n-- 1. products.version\n-- ---------------------------------------------------------------------------\n\nALTER TABLE public.products\n ADD COLUMN IF NOT EXISTS version integer DEFAULT 1 NOT NULL;\n\nCOMMENT ON COLUMN public.products.version IS 'Monotonic version number for hybrid revisions.';\n\n-- ---------------------------------------------------------------------------\n-- 2. product_revisions\n-- ---------------------------------------------------------------------------\n\nCREATE TABLE IF NOT EXISTS public.product_revisions (\n id bigint NOT NULL,\n product_id uuid NOT NULL,\n author_id uuid,\n version integer NOT NULL,\n revision_type public.revision_type NOT NULL,\n content jsonb NOT NULL,\n created_at timestamp with time zone DEFAULT now() NOT NULL\n);\n\nCOMMENT ON TABLE public.product_revisions IS 'Hybrid (snapshot/diff) revisions for products.';\nCOMMENT ON COLUMN public.product_revisions.content IS 'If snapshot: full content; if diff: JSON Patch array.';\n\nDO $rb$\nBEGIN\n IF NOT EXISTS (\n SELECT 1 FROM pg_attribute\n WHERE attrelid = 'public.product_revisions'::regclass\n AND attname = 'id'\n AND attidentity <> ''\n ) THEN\n ALTER TABLE public.product_revisions\n ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (\n SEQUENCE NAME public.product_revisions_id_seq\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1\n );\n END IF;\nEND $rb$;\n\nDO $rb$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint\n WHERE conname = 'product_revisions_pkey'\n AND conrelid = 'public.product_revisions'::regclass) THEN\n ALTER TABLE ONLY public.product_revisions\n ADD CONSTRAINT product_revisions_pkey PRIMARY KEY (id);\n END IF;\nEND $rb$;\n\nDO $rb$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint\n WHERE conname = 'product_revisions_product_version_key'\n AND conrelid = 'public.product_revisions'::regclass) THEN\n ALTER TABLE ONLY public.product_revisions\n ADD CONSTRAINT product_revisions_product_version_key UNIQUE (product_id, version);\n END IF;\nEND $rb$;\n\nDO $rb$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint\n WHERE conname = 'product_revisions_author_id_fkey'\n AND conrelid = 'public.product_revisions'::regclass) THEN\n ALTER TABLE ONLY public.product_revisions\n ADD CONSTRAINT product_revisions_author_id_fkey\n FOREIGN KEY (author_id) REFERENCES public.profiles(id) ON DELETE SET NULL;\n END IF;\nEND $rb$;\n\nDO $rb$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint\n WHERE conname = 'product_revisions_product_id_fkey'\n AND conrelid = 'public.product_revisions'::regclass) THEN\n ALTER TABLE ONLY public.product_revisions\n ADD CONSTRAINT product_revisions_product_id_fkey\n FOREIGN KEY (product_id) REFERENCES public.products(id) ON DELETE CASCADE;\n END IF;\nEND $rb$;\n\nCREATE INDEX IF NOT EXISTS idx_product_revisions_author_id\n ON public.product_revisions USING btree (author_id);\n\nCREATE INDEX IF NOT EXISTS idx_product_revisions_product_id_version\n ON public.product_revisions USING btree (product_id, version);\n\nALTER TABLE public.product_revisions ENABLE ROW LEVEL SECURITY;\n\nDROP POLICY IF EXISTS product_revisions_read_policy ON public.product_revisions;\nCREATE POLICY product_revisions_read_policy ON public.product_revisions\n FOR SELECT TO authenticated USING (true);\n\nDROP POLICY IF EXISTS product_revisions_insert_policy ON public.product_revisions;\nCREATE POLICY product_revisions_insert_policy ON public.product_revisions\n FOR INSERT TO authenticated\n WITH CHECK (((SELECT public.is_admin() AS is_admin) IS TRUE));\n\nDROP POLICY IF EXISTS product_revisions_update_policy ON public.product_revisions;\nCREATE POLICY product_revisions_update_policy ON public.product_revisions\n FOR UPDATE TO authenticated\n USING (((SELECT public.is_admin() AS is_admin) IS TRUE))\n WITH CHECK (((SELECT public.is_admin() AS is_admin) IS TRUE));\n\nDROP POLICY IF EXISTS product_revisions_delete_policy ON public.product_revisions;\nCREATE POLICY product_revisions_delete_policy ON public.product_revisions\n FOR DELETE TO authenticated\n USING (((SELECT public.is_admin() AS is_admin) IS TRUE));\n\nGRANT ALL ON TABLE public.product_revisions TO anon;\nGRANT ALL ON TABLE public.product_revisions TO authenticated;\nGRANT ALL ON TABLE public.product_revisions TO service_role;\nGRANT ALL ON SEQUENCE public.product_revisions_id_seq TO anon;\nGRANT ALL ON SEQUENCE public.product_revisions_id_seq TO authenticated;\nGRANT ALL ON SEQUENCE public.product_revisions_id_seq TO service_role;\n\n-- ---------------------------------------------------------------------------\n-- 3. Revision baseline backfill\n--\n-- The JSON shape must match FullPageContent / FullPostContent / FullProductContent\n-- in apps/nextblock/app/cms/revisions/utils.ts exactly, or the first diff taken\n-- against a baseline row will be full of phantom operations.\n--\n-- Timestamps are rendered with an explicit millisecond-precision UTC format so they\n-- match JavaScript's Date#toISOString() (\"2026-07-03T17:52:15.643Z\"). Postgres'\n-- default jsonb rendering of timestamptz (\"2026-07-03T17:52:15.643901+00:00\") would\n-- differ from the value the application writes and produce a spurious diff on the\n-- very next save.\n-- ---------------------------------------------------------------------------\n\n-- 3a. Pages\nINSERT INTO public.page_revisions (page_id, author_id, version, revision_type, content)\nSELECT\n p.id,\n NULL::uuid,\n p.version,\n 'snapshot'::public.revision_type,\n jsonb_build_object(\n 'meta', jsonb_build_object(\n 'title', p.title,\n 'slug', p.slug,\n 'language_id', p.language_id,\n 'status', p.status,\n 'meta_title', p.meta_title,\n 'meta_description', p.meta_description,\n 'custom_canonical', p.custom_canonical,\n 'published_at', to_char(p.published_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),\n 'feature_image_id', p.feature_image_id\n ),\n 'blocks', COALESCE((\n SELECT jsonb_agg(\n jsonb_build_object(\n 'language_id', b.language_id,\n 'block_type', b.block_type,\n 'content', b.content,\n 'order', b.\"order\"\n ) ORDER BY b.\"order\" ASC, b.id ASC\n )\n FROM public.blocks b\n WHERE b.page_id = p.id\n ), '[]'::jsonb)\n )\n FROM public.pages p\n WHERE NOT EXISTS (\n SELECT 1 FROM public.page_revisions r\n WHERE r.page_id = p.id\n AND r.revision_type = 'snapshot'\n AND r.version <= p.version\n )\nON CONFLICT (page_id, version) DO NOTHING;\n\n-- 3b. Posts\nINSERT INTO public.post_revisions (post_id, author_id, version, revision_type, content)\nSELECT\n po.id,\n NULL::uuid,\n po.version,\n 'snapshot'::public.revision_type,\n jsonb_build_object(\n 'meta', jsonb_build_object(\n 'title', po.title,\n 'slug', po.slug,\n 'language_id', po.language_id,\n 'status', po.status,\n 'meta_title', po.meta_title,\n 'meta_description', po.meta_description,\n 'custom_canonical', po.custom_canonical,\n 'published_at', to_char(po.published_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),\n 'feature_image_id', po.feature_image_id,\n 'label', po.label,\n 'excerpt', po.excerpt,\n 'subtitle', po.subtitle\n ),\n 'blocks', COALESCE((\n SELECT jsonb_agg(\n jsonb_build_object(\n 'language_id', b.language_id,\n 'block_type', b.block_type,\n 'content', b.content,\n 'order', b.\"order\"\n ) ORDER BY b.\"order\" ASC, b.id ASC\n )\n FROM public.blocks b\n WHERE b.post_id = po.id\n ), '[]'::jsonb)\n )\n FROM public.posts po\n WHERE NOT EXISTS (\n SELECT 1 FROM public.post_revisions r\n WHERE r.post_id = po.id\n AND r.revision_type = 'snapshot'\n AND r.version <= po.version\n )\nON CONFLICT (post_id, version) DO NOTHING;\n\n-- 3c. Products.\n--\n-- Content only. price/prices/sale_*/scheduled_*/stock/sku/average_rating/total_reviews\n-- are deliberately excluded from the snapshot: pricing and inventory are mutated from\n-- outside the editor (promotions, Freemius sync, order fulfilment), ratings are derived\n-- aggregates, and inventory_items is keyed by bare SKU text with no FK to products — so\n-- replaying commerce state on restore would reach rows the editor never touched.\n-- Restoring a product restores its content, not its commerce state.\nINSERT INTO public.product_revisions (product_id, author_id, version, revision_type, content)\nSELECT\n pr.id,\n NULL::uuid,\n pr.version,\n 'snapshot'::public.revision_type,\n jsonb_build_object(\n 'meta', jsonb_build_object(\n 'title', pr.title,\n 'slug', pr.slug,\n 'language_id', pr.language_id,\n 'status', pr.status,\n 'meta_title', pr.meta_title,\n 'meta_description', pr.meta_description,\n 'custom_canonical', pr.custom_canonical,\n 'published_at', to_char(pr.published_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"'),\n 'short_description', pr.short_description,\n 'description_json', pr.description_json\n ),\n 'blocks', COALESCE((\n SELECT jsonb_agg(\n jsonb_build_object(\n 'language_id', b.language_id,\n 'block_type', b.block_type,\n 'content', b.content,\n 'order', b.\"order\"\n ) ORDER BY b.\"order\" ASC, b.id ASC\n )\n FROM public.blocks b\n WHERE b.product_id = pr.id\n ), '[]'::jsonb)\n )\n FROM public.products pr\n WHERE NOT EXISTS (\n SELECT 1 FROM public.product_revisions r\n WHERE r.product_id = pr.id\n AND r.revision_type = 'snapshot'\n AND r.version <= pr.version\n )\nON CONFLICT (product_id, version) DO NOTHING;\n"
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
"version": "00000000000017",
|
|
104
|
+
"name": "00000000000017_cortex_ai_mcp_server.sql",
|
|
105
|
+
"sql": "-- Cortex AI MCP (Model Context Protocol) server access.\n--\n-- Adds the bearer-token store that gates /api/mcp, the endpoint that exposes the\n-- Cortex AI tool registry to external MCP clients (Claude Code, Claude Desktop,\n-- Cursor, VS Code). Two pieces:\n--\n-- 1. public.mcp_access_tokens — one row per issued token. We store ONLY the\n-- SHA-256 hash of the token, never the token itself: the plaintext is shown\n-- to the admin exactly once at mint time and is unrecoverable afterwards, so\n-- a database leak cannot be replayed against the MCP endpoint. `token_prefix`\n-- is the non-secret leading fragment kept purely so the UI can tell two tokens\n-- apart in a list.\n--\n-- 2. cortex_ai_mcp_settings — a non-secret JSON site_settings row holding the\n-- server on/off switch and the localhost-trust flag. It is added to all four\n-- site_settings policies so only authenticated ADMINs can read or write it;\n-- the MCP route itself reads it through the service-role client, which\n-- bypasses RLS.\n--\n-- Forward-only. Recreates the four site_settings policies idempotently, preserving\n-- every key already in each policy's sensitive array (note that\n-- language_detection_settings stays anon-READABLE and so is absent from the SELECT\n-- policy, exactly as migration 00000000000012 left it).\n\nCREATE TABLE IF NOT EXISTS public.mcp_access_tokens (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n name text NOT NULL,\n -- Lowercase hex SHA-256 of the plaintext token. Unique so a lookup is a single\n -- indexed equality probe and duplicate mints are impossible.\n token_hash text NOT NULL UNIQUE,\n -- Non-secret display fragment, e.g. \"nbmcp_a1b2c3d4\". Never enough to authenticate.\n token_prefix text NOT NULL,\n -- 'read' grants the read-only tools; 'write' additionally grants the mutating ones.\n scopes text[] NOT NULL DEFAULT ARRAY['read', 'write']::text[],\n created_by uuid REFERENCES auth.users (id) ON DELETE SET NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n last_used_at timestamptz,\n expires_at timestamptz,\n revoked_at timestamptz\n);\n\nCOMMENT ON TABLE public.mcp_access_tokens IS\n 'Bearer tokens for the Cortex AI MCP server at /api/mcp. Stores SHA-256 hashes only; plaintext is displayed once at mint time.';\n\nCREATE INDEX IF NOT EXISTS mcp_access_tokens_token_hash_idx\n ON public.mcp_access_tokens (token_hash);\n\n-- Orders the admin token list newest-first without a sort.\nCREATE INDEX IF NOT EXISTS mcp_access_tokens_created_at_idx\n ON public.mcp_access_tokens (created_at DESC);\n\nALTER TABLE public.mcp_access_tokens ENABLE ROW LEVEL SECURITY;\n\n-- Tokens are credentials: admin-only, with no anon or WRITER access at all. The\n-- MCP route verifies them with the service-role client, which bypasses RLS.\nDROP POLICY IF EXISTS mcp_access_tokens_admin_select ON public.mcp_access_tokens;\nCREATE POLICY mcp_access_tokens_admin_select ON public.mcp_access_tokens\n FOR SELECT TO authenticated\n USING ((SELECT public.get_current_user_role()) = 'ADMIN'::public.user_role);\n\nDROP POLICY IF EXISTS mcp_access_tokens_admin_insert ON public.mcp_access_tokens;\nCREATE POLICY mcp_access_tokens_admin_insert ON public.mcp_access_tokens\n FOR INSERT TO authenticated\n WITH CHECK ((SELECT public.get_current_user_role()) = 'ADMIN'::public.user_role);\n\nDROP POLICY IF EXISTS mcp_access_tokens_admin_update ON public.mcp_access_tokens;\nCREATE POLICY mcp_access_tokens_admin_update ON public.mcp_access_tokens\n FOR UPDATE TO authenticated\n USING ((SELECT public.get_current_user_role()) = 'ADMIN'::public.user_role)\n WITH CHECK ((SELECT public.get_current_user_role()) = 'ADMIN'::public.user_role);\n\nDROP POLICY IF EXISTS mcp_access_tokens_admin_delete ON public.mcp_access_tokens;\nCREATE POLICY mcp_access_tokens_admin_delete ON public.mcp_access_tokens\n FOR DELETE TO authenticated\n USING ((SELECT public.get_current_user_role()) = 'ADMIN'::public.user_role);\n\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.mcp_access_tokens TO authenticated;\nGRANT ALL ON public.mcp_access_tokens TO service_role;\n\n-- Add cortex_ai_mcp_settings to the admin-only site_settings group (all four policies).\nDROP POLICY IF EXISTS site_settings_read_policy ON public.site_settings;\nCREATE POLICY site_settings_read_policy ON public.site_settings FOR SELECT USING (((key <> ALL (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) OR ((key = ANY (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT auth.role() AS role) = 'authenticated'::text) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role))));\n\nDROP POLICY IF EXISTS site_settings_insert_policy ON public.site_settings;\nCREATE POLICY site_settings_insert_policy ON public.site_settings FOR INSERT TO authenticated WITH CHECK ((((key <> ALL (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'language_detection_settings'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = ANY (ARRAY['ADMIN'::public.user_role, 'WRITER'::public.user_role]))) OR ((key = ANY (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'language_detection_settings'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role))));\n\nDROP POLICY IF EXISTS site_settings_update_policy ON public.site_settings;\nCREATE POLICY site_settings_update_policy ON public.site_settings FOR UPDATE TO authenticated USING ((((key <> ALL (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'language_detection_settings'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = ANY (ARRAY['ADMIN'::public.user_role, 'WRITER'::public.user_role]))) OR ((key = ANY (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'language_detection_settings'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role)))) WITH CHECK ((((key <> ALL (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'language_detection_settings'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = ANY (ARRAY['ADMIN'::public.user_role, 'WRITER'::public.user_role]))) OR ((key = ANY (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'language_detection_settings'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role))));\n\nDROP POLICY IF EXISTS site_settings_delete_policy ON public.site_settings;\nCREATE POLICY site_settings_delete_policy ON public.site_settings FOR DELETE TO authenticated USING ((((key <> ALL (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'language_detection_settings'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = ANY (ARRAY['ADMIN'::public.user_role, 'WRITER'::public.user_role]))) OR ((key = ANY (ARRAY['cortex_ai_openrouter_api_key'::text, 'bot_protection_secret'::text, 'email_secret'::text, 'payment_secret'::text, 'language_detection_settings'::text, 'cortex_ai_pexels_api_key'::text, 'cortex_ai_unsplash_access_key'::text, 'cortex_ai_mcp_settings'::text])) AND (( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role))));\n"
|
|
101
106
|
}
|
|
102
107
|
];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/// <reference types="next" />
|
|
2
2
|
/// <reference types="next/image-types/global" />
|
|
3
|
-
import "./.next/
|
|
4
|
-
import "./.next/
|
|
3
|
+
import "./.next/types/routes.d.ts";
|
|
4
|
+
import "./.next/types/root-params.d.ts";
|
|
5
5
|
|
|
6
6
|
// NOTE: This file should not be edited
|
|
7
7
|
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|