@supabase/mcp-server-supabase 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,296 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var F={name:"@supabase/mcp-server-supabase",version:"0.4.1",description:"MCP server for interacting with Supabase",license:"Apache-2.0",type:"module",main:"dist/index.cjs",types:"dist/index.d.ts",sideEffects:!1,scripts:{build:"tsup --clean",prepublishOnly:"npm run build",test:"vitest","test:unit":"vitest --project unit","test:e2e":"vitest --project e2e","test:integration":"vitest --project integration","test:coverage":"vitest --coverage","generate:management-api-types":"openapi-typescript https://api.supabase.com/api/v1-json -o ./src/management-api/types.ts"},files:["dist/**/*"],bin:{"mcp-server-supabase":"./dist/stdio.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts",default:"./dist/index.cjs"}},dependencies:{"@deno/eszip":"^0.84.0","@modelcontextprotocol/sdk":"^1.4.1","@supabase/mcp-utils":"0.2.0","common-tags":"^1.8.2","openapi-fetch":"^0.13.5",zod:"^3.24.1"},devDependencies:{"@ai-sdk/anthropic":"^1.2.9","@electric-sql/pglite":"^0.2.17","@total-typescript/tsconfig":"^1.0.4","@types/common-tags":"^1.8.4","@types/node":"^22.8.6","@vitest/coverage-v8":"^2.1.9",ai:"^4.3.4","date-fns":"^4.1.0",dotenv:"^16.5.0",msw:"^2.7.3",nanoid:"^5.1.5","openapi-typescript":"^7.5.0","openapi-typescript-helpers":"^0.0.15",prettier:"^3.3.3",tsup:"^8.3.5",tsx:"^4.19.2",typescript:"^5.6.3",vitest:"^2.1.9"}};var _mcputils = require('@supabase/mcp-utils');var _openapifetch = require('openapi-fetch'); var _openapifetch2 = _interopRequireDefault(_openapifetch);var _zod = require('zod');function P(e,r,t={}){return _openapifetch2.default.call(void 0, {baseUrl:e,headers:{Authorization:`Bearer ${r}`,...t}})}var ue=_zod.z.object({message:_zod.z.string()});function l(e,r){if("error"in e){if(e.response.status===401)throw new Error("Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SUPABASE_ACCESS_TOKEN.");let{data:t}=ue.safeParse(e.error);throw t?new Error(t.message):new Error(r)}}var fe=10,he=.01344;async function C(e,r){let t=await e.GET("/v1/organizations/{slug}",{params:{path:{slug:r}}});l(t,"Failed to fetch organization");let o=await e.GET("/v1/projects");l(o,"Failed to fetch projects");let n=t.data,s=o.data.filter(c=>c.organization_id===r&&!["INACTIVE","GOING_DOWN","REMOVED"].includes(c.status)),i=0;return n.plan!=="free"&&s.length>0&&(i=fe),{type:"project",recurrence:"monthly",amount:i}}function x(){return{type:"branch",recurrence:"hourly",amount:he}}function U(e){return Object.fromEntries(e.split(`
2
+ `).map(r=>r.split(/=(.*)/)).filter(([r])=>r).map(([r,t])=>[r,_nullishCoalesce(t, () => (""))]))}async function A(e,r){let t=JSON.stringify(e,(s,i)=>i&&typeof i=="object"&&!Array.isArray(i)?Object.keys(i).sort().reduce((c,p)=>(c[p]=i[p],c),{}):i),o=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(o))).slice(0,r)}function d({description:e,parameters:r,inject:t,execute:o}){if(!t||Object.values(t).every(s=>s===void 0))return _mcputils.tool.call(void 0, {description:e,parameters:r,execute:o});let n=Object.fromEntries(Object.entries(t).filter(([s,i])=>i!==void 0).map(([s])=>[s,!0]));return _mcputils.tool.call(void 0, {description:e,parameters:r.omit(n),execute:s=>o({...s,...t})})}function H({managementApiClient:e,projectId:r}){let t=r;return{create_branch:d({description:"Creates a development branch on a Supabase project. This will apply all migrations from the main project to a fresh branch database. Note that production data will not carry over. The branch will get its own project_id via the resulting project_ref. Use this ID to execute queries and migrations on the branch.",parameters:_zod.z.object({project_id:_zod.z.string(),name:_zod.z.string().default("develop").describe("Name of the branch to create"),confirm_cost_id:_zod.z.string({required_error:"User must confirm understanding of costs before creating a branch."}).describe("The cost confirmation ID. Call `confirm_cost` first.")}),inject:{project_id:t},execute:async({project_id:o,name:n,confirm_cost_id:s})=>{let i=x();if(await A(i)!==s)throw new Error("Cost confirmation ID does not match the expected cost of creating a branch.");let p=await e.POST("/v1/projects/{ref}/branches",{params:{path:{ref:o}},body:{branch_name:n}});if(l(p,"Failed to create branch"),p.data.is_default){await e.PATCH("/v1/branches/{branch_id}",{params:{path:{branch_id:p.data.id}},body:{branch_name:"main"}});let m=await e.POST("/v1/projects/{ref}/branches",{params:{path:{ref:o}},body:{branch_name:n}});return l(m,"Failed to create branch"),m.data}return p.data}}),list_branches:d({description:"Lists all development branches of a Supabase project. This will return branch details including status which you can use to check when operations like merge/rebase/reset complete.",parameters:_zod.z.object({project_id:_zod.z.string()}),inject:{project_id:t},execute:async({project_id:o})=>{let n=await e.GET("/v1/projects/{ref}/branches",{params:{path:{ref:o}}});return n.response.status===422?[]:(l(n,"Failed to list branches"),n.data)}}),delete_branch:_mcputils.tool.call(void 0, {description:"Deletes a development branch.",parameters:_zod.z.object({branch_id:_zod.z.string()}),execute:async({branch_id:o})=>{let n=await e.DELETE("/v1/branches/{branch_id}",{params:{path:{branch_id:o}}});return l(n,"Failed to delete branch"),n.data}}),merge_branch:_mcputils.tool.call(void 0, {description:"Merges migrations and edge functions from a development branch to production.",parameters:_zod.z.object({branch_id:_zod.z.string()}),execute:async({branch_id:o})=>{let n=await e.POST("/v1/branches/{branch_id}/merge",{params:{path:{branch_id:o}},body:{}});return l(n,"Failed to merge branch"),n.data}}),reset_branch:_mcputils.tool.call(void 0, {description:"Resets migrations of a development branch. Any untracked data or schema changes will be lost.",parameters:_zod.z.object({branch_id:_zod.z.string(),migration_version:_zod.z.string().optional().describe("Reset your development branch to a specific migration version.")}),execute:async({branch_id:o,migration_version:n})=>{let s=await e.POST("/v1/branches/{branch_id}/reset",{params:{path:{branch_id:o}},body:{migration_version:n}});return l(s,"Failed to reset branch"),s.data}}),rebase_branch:_mcputils.tool.call(void 0, {description:"Rebases a development branch on production. This will effectively run any newer migrations from production onto this branch to help handle migration drift.",parameters:_zod.z.object({branch_id:_zod.z.string()}),execute:async({branch_id:o})=>{let n=await e.POST("/v1/branches/{branch_id}/push",{params:{path:{branch_id:o}},body:{}});return l(n,"Failed to rebase branch"),n.data}})}}var _commontags = require('common-tags');var G=`-- Adapted from information_schema.columns
3
+
4
+ SELECT
5
+ c.oid :: int8 AS table_id,
6
+ nc.nspname AS schema,
7
+ c.relname AS table,
8
+ (c.oid || '.' || a.attnum) AS id,
9
+ a.attnum AS ordinal_position,
10
+ a.attname AS name,
11
+ CASE
12
+ WHEN a.atthasdef THEN pg_get_expr(ad.adbin, ad.adrelid)
13
+ ELSE NULL
14
+ END AS default_value,
15
+ CASE
16
+ WHEN t.typtype = 'd' THEN CASE
17
+ WHEN bt.typelem <> 0 :: oid
18
+ AND bt.typlen = -1 THEN 'ARRAY'
19
+ WHEN nbt.nspname = 'pg_catalog' THEN format_type(t.typbasetype, NULL)
20
+ ELSE 'USER-DEFINED'
21
+ END
22
+ ELSE CASE
23
+ WHEN t.typelem <> 0 :: oid
24
+ AND t.typlen = -1 THEN 'ARRAY'
25
+ WHEN nt.nspname = 'pg_catalog' THEN format_type(a.atttypid, NULL)
26
+ ELSE 'USER-DEFINED'
27
+ END
28
+ END AS data_type,
29
+ COALESCE(bt.typname, t.typname) AS format,
30
+ a.attidentity IN ('a', 'd') AS is_identity,
31
+ CASE
32
+ a.attidentity
33
+ WHEN 'a' THEN 'ALWAYS'
34
+ WHEN 'd' THEN 'BY DEFAULT'
35
+ ELSE NULL
36
+ END AS identity_generation,
37
+ a.attgenerated IN ('s') AS is_generated,
38
+ NOT (
39
+ a.attnotnull
40
+ OR t.typtype = 'd' AND t.typnotnull
41
+ ) AS is_nullable,
42
+ (
43
+ c.relkind IN ('r', 'p')
44
+ OR c.relkind IN ('v', 'f') AND pg_column_is_updatable(c.oid, a.attnum, FALSE)
45
+ ) AS is_updatable,
46
+ uniques.table_id IS NOT NULL AS is_unique,
47
+ check_constraints.definition AS "check",
48
+ array_to_json(
49
+ array(
50
+ SELECT
51
+ enumlabel
52
+ FROM
53
+ pg_catalog.pg_enum enums
54
+ WHERE
55
+ enums.enumtypid = coalesce(bt.oid, t.oid)
56
+ OR enums.enumtypid = coalesce(bt.typelem, t.typelem)
57
+ ORDER BY
58
+ enums.enumsortorder
59
+ )
60
+ ) AS enums,
61
+ col_description(c.oid, a.attnum) AS comment
62
+ FROM
63
+ pg_attribute a
64
+ LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid
65
+ AND a.attnum = ad.adnum
66
+ JOIN (
67
+ pg_class c
68
+ JOIN pg_namespace nc ON c.relnamespace = nc.oid
69
+ ) ON a.attrelid = c.oid
70
+ JOIN (
71
+ pg_type t
72
+ JOIN pg_namespace nt ON t.typnamespace = nt.oid
73
+ ) ON a.atttypid = t.oid
74
+ LEFT JOIN (
75
+ pg_type bt
76
+ JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid
77
+ ) ON t.typtype = 'd'
78
+ AND t.typbasetype = bt.oid
79
+ LEFT JOIN (
80
+ SELECT DISTINCT ON (table_id, ordinal_position)
81
+ conrelid AS table_id,
82
+ conkey[1] AS ordinal_position
83
+ FROM pg_catalog.pg_constraint
84
+ WHERE contype = 'u' AND cardinality(conkey) = 1
85
+ ) AS uniques ON uniques.table_id = c.oid AND uniques.ordinal_position = a.attnum
86
+ LEFT JOIN (
87
+ -- We only select the first column check
88
+ SELECT DISTINCT ON (table_id, ordinal_position)
89
+ conrelid AS table_id,
90
+ conkey[1] AS ordinal_position,
91
+ substring(
92
+ pg_get_constraintdef(pg_constraint.oid, true),
93
+ 8,
94
+ length(pg_get_constraintdef(pg_constraint.oid, true)) - 8
95
+ ) AS "definition"
96
+ FROM pg_constraint
97
+ WHERE contype = 'c' AND cardinality(conkey) = 1
98
+ ORDER BY table_id, ordinal_position, oid asc
99
+ ) AS check_constraints ON check_constraints.table_id = c.oid AND check_constraints.ordinal_position = a.attnum
100
+ WHERE
101
+ NOT pg_is_other_temp_schema(nc.oid)
102
+ AND a.attnum > 0
103
+ AND NOT a.attisdropped
104
+ AND (c.relkind IN ('r', 'v', 'm', 'f', 'p'))
105
+ AND (
106
+ pg_has_role(c.relowner, 'USAGE')
107
+ OR has_column_privilege(
108
+ c.oid,
109
+ a.attnum,
110
+ 'SELECT, INSERT, UPDATE, REFERENCES'
111
+ )
112
+ )
113
+ `;var z=`SELECT
114
+ e.name,
115
+ n.nspname AS schema,
116
+ e.default_version,
117
+ x.extversion AS installed_version,
118
+ e.comment
119
+ FROM
120
+ pg_available_extensions() e(name, default_version, comment)
121
+ LEFT JOIN pg_extension x ON e.name = x.extname
122
+ LEFT JOIN pg_namespace n ON x.extnamespace = n.oid
123
+ `;var B=`SELECT
124
+ c.oid :: int8 AS id,
125
+ nc.nspname AS schema,
126
+ c.relname AS name,
127
+ c.relrowsecurity AS rls_enabled,
128
+ c.relforcerowsecurity AS rls_forced,
129
+ CASE
130
+ WHEN c.relreplident = 'd' THEN 'DEFAULT'
131
+ WHEN c.relreplident = 'i' THEN 'INDEX'
132
+ WHEN c.relreplident = 'f' THEN 'FULL'
133
+ ELSE 'NOTHING'
134
+ END AS replica_identity,
135
+ pg_total_relation_size(format('%I.%I', nc.nspname, c.relname)) :: int8 AS bytes,
136
+ pg_size_pretty(
137
+ pg_total_relation_size(format('%I.%I', nc.nspname, c.relname))
138
+ ) AS size,
139
+ pg_stat_get_live_tuples(c.oid) AS live_rows_estimate,
140
+ pg_stat_get_dead_tuples(c.oid) AS dead_rows_estimate,
141
+ obj_description(c.oid) AS comment,
142
+ coalesce(pk.primary_keys, '[]') as primary_keys,
143
+ coalesce(
144
+ jsonb_agg(relationships) filter (where relationships is not null),
145
+ '[]'
146
+ ) as relationships
147
+ FROM
148
+ pg_namespace nc
149
+ JOIN pg_class c ON nc.oid = c.relnamespace
150
+ left join (
151
+ select
152
+ table_id,
153
+ jsonb_agg(_pk.*) as primary_keys
154
+ from (
155
+ select
156
+ n.nspname as schema,
157
+ c.relname as table_name,
158
+ a.attname as name,
159
+ c.oid :: int8 as table_id
160
+ from
161
+ pg_index i,
162
+ pg_class c,
163
+ pg_attribute a,
164
+ pg_namespace n
165
+ where
166
+ i.indrelid = c.oid
167
+ and c.relnamespace = n.oid
168
+ and a.attrelid = c.oid
169
+ and a.attnum = any (i.indkey)
170
+ and i.indisprimary
171
+ ) as _pk
172
+ group by table_id
173
+ ) as pk
174
+ on pk.table_id = c.oid
175
+ left join (
176
+ select
177
+ c.oid :: int8 as id,
178
+ c.conname as constraint_name,
179
+ nsa.nspname as source_schema,
180
+ csa.relname as source_table_name,
181
+ sa.attname as source_column_name,
182
+ nta.nspname as target_table_schema,
183
+ cta.relname as target_table_name,
184
+ ta.attname as target_column_name
185
+ from
186
+ pg_constraint c
187
+ join (
188
+ pg_attribute sa
189
+ join pg_class csa on sa.attrelid = csa.oid
190
+ join pg_namespace nsa on csa.relnamespace = nsa.oid
191
+ ) on sa.attrelid = c.conrelid and sa.attnum = any (c.conkey)
192
+ join (
193
+ pg_attribute ta
194
+ join pg_class cta on ta.attrelid = cta.oid
195
+ join pg_namespace nta on cta.relnamespace = nta.oid
196
+ ) on ta.attrelid = c.confrelid and ta.attnum = any (c.confkey)
197
+ where
198
+ c.contype = 'f'
199
+ ) as relationships
200
+ on (relationships.source_schema = nc.nspname and relationships.source_table_name = c.relname)
201
+ or (relationships.target_table_schema = nc.nspname and relationships.target_table_name = c.relname)
202
+ WHERE
203
+ c.relkind IN ('r', 'p')
204
+ AND NOT pg_is_other_temp_schema(nc.oid)
205
+ AND (
206
+ pg_has_role(c.relowner, 'USAGE')
207
+ OR has_table_privilege(
208
+ c.oid,
209
+ 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
210
+ )
211
+ OR has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
212
+ )
213
+ group by
214
+ c.oid,
215
+ c.relname,
216
+ c.relrowsecurity,
217
+ c.relforcerowsecurity,
218
+ c.relreplident,
219
+ nc.nspname,
220
+ pk.primary_keys
221
+ `;var Ee=["information_schema","pg_catalog","pg_toast","_timescaledb_internal"];function q(e=[]){let r=_commontags.stripIndent`
222
+ with
223
+ tables as (${B}),
224
+ columns as (${G})
225
+ select
226
+ *,
227
+ ${Se("columns","columns.table_id = tables.id")}
228
+ from tables
229
+ `;return r+=`
230
+ `,e.length>0?r+=`where schema in (${e.map(t=>`'${t}'`).join(",")})`:r+=`where schema not in (${Ee.map(t=>`'${t}'`).join(",")})`,r}function K(){return z}var Se=(e,r)=>_commontags.stripIndent`
231
+ COALESCE(
232
+ (
233
+ SELECT
234
+ array_agg(row_to_json(${e})) FILTER (WHERE ${r})
235
+ FROM
236
+ ${e}
237
+ ),
238
+ '{}'
239
+ ) AS ${e}
240
+ `;var Te=_zod.z.object({schema:_zod.z.string(),table_name:_zod.z.string(),name:_zod.z.string(),table_id:_zod.z.number().int()}),je=_zod.z.object({id:_zod.z.number().int(),constraint_name:_zod.z.string(),source_schema:_zod.z.string(),source_table_name:_zod.z.string(),source_column_name:_zod.z.string(),target_table_schema:_zod.z.string(),target_table_name:_zod.z.string(),target_column_name:_zod.z.string()}),Ae=_zod.z.object({table_id:_zod.z.number().int(),schema:_zod.z.string(),table:_zod.z.string(),id:_zod.z.string().regex(/^(\d+)\.(\d+)$/),ordinal_position:_zod.z.number().int(),name:_zod.z.string(),default_value:_zod.z.any(),data_type:_zod.z.string(),format:_zod.z.string(),is_identity:_zod.z.boolean(),identity_generation:_zod.z.union([_zod.z.literal("ALWAYS"),_zod.z.literal("BY DEFAULT"),_zod.z.null()]),is_generated:_zod.z.boolean(),is_nullable:_zod.z.boolean(),is_updatable:_zod.z.boolean(),is_unique:_zod.z.boolean(),enums:_zod.z.array(_zod.z.string()),check:_zod.z.union([_zod.z.string(),_zod.z.null()]),comment:_zod.z.union([_zod.z.string(),_zod.z.null()])}),$=_zod.z.object({id:_zod.z.number().int(),schema:_zod.z.string(),name:_zod.z.string(),rls_enabled:_zod.z.boolean(),rls_forced:_zod.z.boolean(),replica_identity:_zod.z.union([_zod.z.literal("DEFAULT"),_zod.z.literal("INDEX"),_zod.z.literal("FULL"),_zod.z.literal("NOTHING")]),bytes:_zod.z.number().int(),size:_zod.z.string(),live_rows_estimate:_zod.z.number().int(),dead_rows_estimate:_zod.z.number().int(),comment:_zod.z.string().nullable(),columns:_zod.z.array(Ae).optional(),primary_keys:_zod.z.array(Te),relationships:_zod.z.array(je)}),J=_zod.z.object({name:_zod.z.string(),schema:_zod.z.union([_zod.z.string(),_zod.z.null()]),default_version:_zod.z.string(),installed_version:_zod.z.union([_zod.z.string(),_zod.z.null()]),comment:_zod.z.union([_zod.z.string(),_zod.z.null()])});function Y({managementApiClient:e,projectId:r,readOnly:t}){async function o(i,c){let p=await e.POST("/v1/projects/{ref}/database/query",{params:{path:{ref:i}},body:{query:c,read_only:t}});return l(p,"Failed to execute SQL query"),p.data}let n=r;return{list_tables:d({description:"Lists all tables in one or more schemas.",parameters:_zod.z.object({project_id:_zod.z.string(),schemas:_zod.z.array(_zod.z.string()).describe("List of schemas to include. Defaults to all schemas.").default(["public"])}),inject:{project_id:n},execute:async({project_id:i,schemas:c})=>{let p=q(c);return(await o(i,p)).map(h=>$.parse(h))}}),list_extensions:d({description:"Lists all extensions in the database.",parameters:_zod.z.object({project_id:_zod.z.string()}),inject:{project_id:n},execute:async({project_id:i})=>{let c=K();return(await o(i,c)).map(_=>J.parse(_))}}),list_migrations:d({description:"Lists all migrations in the database.",parameters:_zod.z.object({project_id:_zod.z.string()}),inject:{project_id:n},execute:async({project_id:i})=>{let c=await e.GET("/v1/projects/{ref}/database/migrations",{params:{path:{ref:i}}});return l(c,"Failed to fetch migrations"),c.data}}),apply_migration:d({description:"Applies a migration to the database. Use this when executing DDL operations. Do not hardcode references to generated IDs in data migrations.",parameters:_zod.z.object({project_id:_zod.z.string(),name:_zod.z.string().describe("The name of the migration in snake_case"),query:_zod.z.string().describe("The SQL query to apply")}),inject:{project_id:n},execute:async({project_id:i,name:c,query:p})=>{if(t)throw new Error("Cannot apply migration in read-only mode.");let m=await e.POST("/v1/projects/{ref}/database/migrations",{params:{path:{ref:i}},body:{name:c,query:p}});return l(m,"Failed to apply migration"),m.data}}),execute_sql:d({description:"Executes raw SQL in the Postgres database. Use `apply_migration` instead for DDL operations.",parameters:_zod.z.object({project_id:_zod.z.string(),query:_zod.z.string().describe("The SQL query to execute")}),inject:{project_id:n},execute:async({query:i,project_id:c})=>await o(c,i)})}}function V(e,r=100){switch(e){case"api":return _commontags.stripIndent`
241
+ select id, identifier, timestamp, event_message, request.method, request.path, response.status_code
242
+ from edge_logs
243
+ cross join unnest(metadata) as m
244
+ cross join unnest(m.request) as request
245
+ cross join unnest(m.response) as response
246
+ order by timestamp desc
247
+ limit ${r}
248
+ `;case"branch-action":return _commontags.stripIndent`
249
+ select workflow_run, workflow_run_logs.timestamp, id, event_message from workflow_run_logs
250
+ order by timestamp desc
251
+ limit ${r}
252
+ `;case"postgres":return _commontags.stripIndent`
253
+ select identifier, postgres_logs.timestamp, id, event_message, parsed.error_severity from postgres_logs
254
+ cross join unnest(metadata) as m
255
+ cross join unnest(m.parsed) as parsed
256
+ order by timestamp desc
257
+ limit ${r}
258
+ `;case"edge-function":return _commontags.stripIndent`
259
+ select id, function_edge_logs.timestamp, event_message, response.status_code, request.method, m.function_id, m.execution_time_ms, m.deployment_id, m.version from function_edge_logs
260
+ cross join unnest(metadata) as m
261
+ cross join unnest(m.response) as response
262
+ cross join unnest(m.request) as request
263
+ order by timestamp desc
264
+ limit ${r}
265
+ `;case"auth":return _commontags.stripIndent`
266
+ select id, auth_logs.timestamp, event_message, metadata.level, metadata.status, metadata.path, metadata.msg as msg, metadata.error from auth_logs
267
+ cross join unnest(metadata) as metadata
268
+ order by timestamp desc
269
+ limit ${r}
270
+ `;case"storage":return _commontags.stripIndent`
271
+ select id, storage_logs.timestamp, event_message from storage_logs
272
+ order by timestamp desc
273
+ limit ${r}
274
+ `;case"realtime":return _commontags.stripIndent`
275
+ select id, realtime_logs.timestamp, event_message from realtime_logs
276
+ order by timestamp desc
277
+ limit ${r}
278
+ `;default:throw new Error(`unsupported log service type: ${e}`)}}function Z({managementApiClient:e,projectId:r}){let t=r;return{get_logs:d({description:"Gets logs for a Supabase project by service type. Use this to help debug problems with your app. This will only return logs within the last minute. If the logs you are looking for are older than 1 minute, re-run your test to reproduce them.",parameters:_zod.z.object({project_id:_zod.z.string(),service:_zod.z.enum(["api","branch-action","postgres","edge-function","auth","storage","realtime"]).describe("The service to fetch logs for")}),inject:{project_id:t},execute:async({project_id:o,service:n})=>{let s=n==="branch-action"?new Date(Date.now()-3e5):void 0,i=await e.GET("/v1/projects/{ref}/analytics/endpoints/logs.all",{params:{path:{ref:o},query:{iso_timestamp_start:_optionalChain([s, 'optionalAccess', _2 => _2.toISOString, 'call', _3 => _3()]),sql:V(n)}}});return l(i,"Failed to fetch logs"),i.data}})}}function Q({managementApiClient:e,projectId:r}){let t=r;return{get_project_url:d({description:"Gets the API URL for a project.",parameters:_zod.z.object({project_id:_zod.z.string()}),inject:{project_id:t},execute:async({project_id:o})=>`https://${o}.supabase.co`}),get_anon_key:d({description:"Gets the anonymous API key for a project.",parameters:_zod.z.object({project_id:_zod.z.string()}),inject:{project_id:t},execute:async({project_id:o})=>{let n=await e.GET("/v1/projects/{ref}/api-keys",{params:{path:{ref:o},query:{reveal:!1}}});l(n,"Failed to fetch API keys");let s=_optionalChain([n, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.find, 'call', _6 => _6(i=>i.name==="anon")]);if(!s)throw new Error("Anonymous key not found");return s.api_key}}),generate_typescript_types:d({description:"Generates TypeScript types for a project.",parameters:_zod.z.object({project_id:_zod.z.string()}),inject:{project_id:t},execute:async({project_id:o})=>{let n=await e.GET("/v1/projects/{ref}/types/typescript",{params:{path:{ref:o}}});return l(n,"Failed to fetch TypeScript types"),n.data}})}}var _url = require('url');var _eszip = require('@deno/eszip');var _posix = require('path/posix');var w=await _eszip.Parser.createInstance(),Oe=_zod.z.object({version:_zod.z.number(),sources:_zod.z.array(_zod.z.string()),sourcesContent:_zod.z.array(_zod.z.string()).optional(),names:_zod.z.array(_zod.z.string()),mappings:_zod.z.string()});async function X(e,r="/"){let t=[];if(e instanceof ReadableStream){let s=e.getReader({mode:"byob"});t=await w.parse(s)}else t=await w.parseBytes(e);await w.load();let o=t.filter(s=>s.startsWith("file://"));return await Promise.all(o.map(async s=>{let i=await w.getModuleSource(s),c=await w.getModuleSourceMap(s),p=_posix.relative.call(void 0, r,_url.fileURLToPath.call(void 0, s,{windows:!1})),m=new File([i],p,{type:"text/plain"});if(!c)return m;let _=Oe.parse(JSON.parse(c)),[h]=_nullishCoalesce(_.sourcesContent, () => ([]));return h?new File([h],p,{type:"application/typescript"}):m}))}function Ce(e,r,t){return`${e}_${r}_${t}`}function Ie(e){return`/tmp/user_fn_${e}/`}var te=_commontags.codeBlock`
279
+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";
280
+
281
+ Deno.serve(async (req: Request) => {
282
+ const data = {
283
+ message: "Hello there!"
284
+ };
285
+
286
+ return new Response(JSON.stringify(data), {
287
+ headers: {
288
+ 'Content-Type': 'application/json',
289
+ 'Connection': 'keep-alive'
290
+ }
291
+ });
292
+ });
293
+ `;async function v(e,r,t){let o=await e.GET("/v1/projects/{ref}/functions/{function_slug}",{params:{path:{ref:r,function_slug:t}}});if(o.error)return{data:void 0,error:o.error};l(o,"Failed to fetch Edge Function");let n=o.data,s=Ce(r,n.id,n.version),i=Ie(s),c=n.entrypoint_path?_url.fileURLToPath.call(void 0, n.entrypoint_path,{windows:!1}).replace(i,""):void 0,p=n.import_map_path?_url.fileURLToPath.call(void 0, n.import_map_path,{windows:!1}).replace(i,""):void 0,m=await e.GET("/v1/projects/{ref}/functions/{function_slug}/body",{params:{path:{ref:r,function_slug:t}},parseAs:"arrayBuffer"});l(m,"Failed to fetch Edge Function eszip bundle");let _=await X(new Uint8Array(m.data),i),h=await Promise.all(_.map(async N=>({name:N.name,content:await N.text()})));return{data:{...n,entrypoint_path:c,import_map_path:p,files:h},error:void 0}}function ne({managementApiClient:e,projectId:r}){let t=r;return{list_edge_functions:d({description:"Lists all Edge Functions in a Supabase project.",parameters:_zod.z.object({project_id:_zod.z.string()}),inject:{project_id:t},execute:async({project_id:o})=>{let n=await e.GET("/v1/projects/{ref}/functions",{params:{path:{ref:o}}});return l(n,"Failed to fetch Edge Functions"),await Promise.all(n.data.map(async i=>{let{data:c,error:p}=await v(e,o,i.slug);if(p)throw p;return c}))}}),deploy_edge_function:d({description:`Deploys an Edge Function to a Supabase project. If the function already exists, this will create a new version. Example:
294
+
295
+ ${te}`,parameters:_zod.z.object({project_id:_zod.z.string(),name:_zod.z.string().describe("The name of the function"),entrypoint_path:_zod.z.string().default("index.ts").describe("The entrypoint of the function"),import_map_path:_zod.z.string().describe("The import map for the function.").optional(),files:_zod.z.array(_zod.z.object({name:_zod.z.string(),content:_zod.z.string()})).describe("The files to upload. This should include the entrypoint and any relative dependencies.")}),inject:{project_id:t},execute:async({project_id:o,name:n,entrypoint_path:s,import_map_path:i,files:c})=>{let{data:p}=await v(e,o,n),m=c.find(h=>["deno.json","import_map.json"].includes(h.name));i??=_nullishCoalesce(_optionalChain([p, 'optionalAccess', _7 => _7.import_map_path]), () => (_optionalChain([m, 'optionalAccess', _8 => _8.name])));let _=await e.POST("/v1/projects/{ref}/functions/deploy",{params:{path:{ref:o},query:{slug:n}},body:{metadata:{name:n,entrypoint_path:s,import_map_path:i},file:c},bodySerializer(h){let j=new FormData,N=new Blob([JSON.stringify(h.metadata)],{type:"application/json"});return j.append("metadata",N),_optionalChain([h, 'access', _9 => _9.file, 'optionalAccess', _10 => _10.forEach, 'call', _11 => _11(pe=>{let M=pe,ge=new Blob([M.content],{type:"application/typescript"});j.append("file",ge,M.name)})]),j}});return l(_,"Failed to deploy Edge Function"),_.data}})}}var ve="ABCDEFGHIJKLMNOPQRSTUVWXYZ",Le="abcdefghijklmnopqrstuvwxyz",Me="0123456789",Fe="!@#$%^&*()_+~`|}{[]:;?><,./-=",ae=({length:e=10,numbers:r=!1,symbols:t=!1,uppercase:o=!0,lowercase:n=!0}={})=>{let s="";if(o&&(s+=ve),n&&(s+=Le),r&&(s+=Me),t&&(s+=Fe),s.length===0)throw new Error("at least one character set must be selected");let i=new Uint32Array(e);crypto.getRandomValues(i);let c="";for(let p=0;p<e;p++){let m=i[p]%s.length;c+=s.charAt(m)}return c};var De=6371,Pe="https://www.cloudflare.com/cdn-cgi/trace",Ue={AF:{lat:33,lng:65},AX:{lat:60.116667,lng:19.9},AL:{lat:41,lng:20},DZ:{lat:28,lng:3},AS:{lat:-14.3333,lng:-170},AD:{lat:42.5,lng:1.6},AO:{lat:-12.5,lng:18.5},AI:{lat:18.25,lng:-63.1667},AQ:{lat:-90,lng:0},AG:{lat:17.05,lng:-61.8},AR:{lat:-34,lng:-64},AM:{lat:40,lng:45},AW:{lat:12.5,lng:-69.9667},AU:{lat:-27,lng:133},AT:{lat:47.3333,lng:13.3333},AZ:{lat:40.5,lng:47.5},BS:{lat:24.25,lng:-76},BH:{lat:26,lng:50.55},BD:{lat:24,lng:90},BB:{lat:13.1667,lng:-59.5333},BY:{lat:53,lng:28},BE:{lat:50.8333,lng:4},BZ:{lat:17.25,lng:-88.75},BJ:{lat:9.5,lng:2.25},BM:{lat:32.3333,lng:-64.75},BT:{lat:27.5,lng:90.5},BO:{lat:-17,lng:-65},BQ:{lat:12.183333,lng:-68.233333},BA:{lat:44,lng:18},BW:{lat:-22,lng:24},BV:{lat:-54.4333,lng:3.4},BR:{lat:-10,lng:-55},IO:{lat:-6,lng:71.5},BN:{lat:4.5,lng:114.6667},BG:{lat:43,lng:25},BF:{lat:13,lng:-2},MM:{lat:22,lng:98},BI:{lat:-3.5,lng:30},KH:{lat:13,lng:105},CM:{lat:6,lng:12},CA:{lat:60,lng:-95},CV:{lat:16,lng:-24},KY:{lat:19.5,lng:-80.5},CF:{lat:7,lng:21},TD:{lat:15,lng:19},CL:{lat:-30,lng:-71},CN:{lat:35,lng:105},CX:{lat:-10.5,lng:105.6667},CC:{lat:-12.5,lng:96.8333},CO:{lat:4,lng:-72},KM:{lat:-12.1667,lng:44.25},CD:{lat:0,lng:25},CG:{lat:-1,lng:15},CK:{lat:-21.2333,lng:-159.7667},CR:{lat:10,lng:-84},CI:{lat:8,lng:-5},HR:{lat:45.1667,lng:15.5},CU:{lat:21.5,lng:-80},CW:{lat:12.166667,lng:-68.966667},CY:{lat:35,lng:33},CZ:{lat:49.75,lng:15.5},DK:{lat:56,lng:10},DJ:{lat:11.5,lng:43},DM:{lat:15.4167,lng:-61.3333},DO:{lat:19,lng:-70.6667},EC:{lat:-2,lng:-77.5},EG:{lat:27,lng:30},SV:{lat:13.8333,lng:-88.9167},GQ:{lat:2,lng:10},ER:{lat:15,lng:39},EE:{lat:59,lng:26},ET:{lat:8,lng:38},FK:{lat:-51.75,lng:-59},FO:{lat:62,lng:-7},FJ:{lat:-18,lng:175},FI:{lat:64,lng:26},FR:{lat:46,lng:2},GF:{lat:4,lng:-53},PF:{lat:-15,lng:-140},TF:{lat:-43,lng:67},GA:{lat:-1,lng:11.75},GM:{lat:13.4667,lng:-16.5667},GE:{lat:42,lng:43.5},DE:{lat:51,lng:9},GH:{lat:8,lng:-2},GI:{lat:36.1833,lng:-5.3667},GR:{lat:39,lng:22},GL:{lat:72,lng:-40},GD:{lat:12.1167,lng:-61.6667},GP:{lat:16.25,lng:-61.5833},GU:{lat:13.4667,lng:144.7833},GT:{lat:15.5,lng:-90.25},GG:{lat:49.5,lng:-2.56},GW:{lat:12,lng:-15},GN:{lat:11,lng:-10},GY:{lat:5,lng:-59},HT:{lat:19,lng:-72.4167},HM:{lat:-53.1,lng:72.5167},VA:{lat:41.9,lng:12.45},HN:{lat:15,lng:-86.5},HK:{lat:22.25,lng:114.1667},HU:{lat:47,lng:20},IS:{lat:65,lng:-18},IN:{lat:20,lng:77},ID:{lat:-5,lng:120},IR:{lat:32,lng:53},IQ:{lat:33,lng:44},IE:{lat:53,lng:-8},IM:{lat:54.23,lng:-4.55},IL:{lat:31.5,lng:34.75},IT:{lat:42.8333,lng:12.8333},JM:{lat:18.25,lng:-77.5},JP:{lat:36,lng:138},JE:{lat:49.21,lng:-2.13},JO:{lat:31,lng:36},KZ:{lat:48,lng:68},KE:{lat:1,lng:38},KI:{lat:1.4167,lng:173},KP:{lat:40,lng:127},KR:{lat:37,lng:127.5},XK:{lat:42.583333,lng:21},KW:{lat:29.3375,lng:47.6581},KG:{lat:41,lng:75},LA:{lat:18,lng:105},LV:{lat:57,lng:25},LB:{lat:33.8333,lng:35.8333},LS:{lat:-29.5,lng:28.5},LR:{lat:6.5,lng:-9.5},LY:{lat:25,lng:17},LI:{lat:47.1667,lng:9.5333},LT:{lat:56,lng:24},LU:{lat:49.75,lng:6.1667},MO:{lat:22.1667,lng:113.55},MK:{lat:41.8333,lng:22},MG:{lat:-20,lng:47},MW:{lat:-13.5,lng:34},MY:{lat:2.5,lng:112.5},MV:{lat:3.25,lng:73},ML:{lat:17,lng:-4},MT:{lat:35.8333,lng:14.5833},MH:{lat:9,lng:168},MQ:{lat:14.6667,lng:-61},MR:{lat:20,lng:-12},MU:{lat:-20.2833,lng:57.55},YT:{lat:-12.8333,lng:45.1667},MX:{lat:23,lng:-102},FM:{lat:6.9167,lng:158.25},MD:{lat:47,lng:29},MC:{lat:43.7333,lng:7.4},MN:{lat:46,lng:105},ME:{lat:42,lng:19},MS:{lat:16.75,lng:-62.2},MA:{lat:32,lng:-5},MZ:{lat:-18.25,lng:35},NA:{lat:-22,lng:17},NR:{lat:-.5333,lng:166.9167},NP:{lat:28,lng:84},AN:{lat:12.25,lng:-68.75},NL:{lat:52.5,lng:5.75},NC:{lat:-21.5,lng:165.5},NZ:{lat:-41,lng:174},NI:{lat:13,lng:-85},NE:{lat:16,lng:8},NG:{lat:10,lng:8},NU:{lat:-19.0333,lng:-169.8667},NF:{lat:-29.0333,lng:167.95},MP:{lat:15.2,lng:145.75},NO:{lat:62,lng:10},OM:{lat:21,lng:57},PK:{lat:30,lng:70},PW:{lat:7.5,lng:134.5},PS:{lat:32,lng:35.25},PA:{lat:9,lng:-80},PG:{lat:-6,lng:147},PY:{lat:-23,lng:-58},PE:{lat:-10,lng:-76},PH:{lat:13,lng:122},PN:{lat:-24.7,lng:-127.4},PL:{lat:52,lng:20},PT:{lat:39.5,lng:-8},PR:{lat:18.25,lng:-66.5},QA:{lat:25.5,lng:51.25},RE:{lat:-21.1,lng:55.6},RO:{lat:46,lng:25},RU:{lat:60,lng:100},RW:{lat:-2,lng:30},BL:{lat:17.897728,lng:-62.834244},SH:{lat:-15.9333,lng:-5.7},KN:{lat:17.3333,lng:-62.75},LC:{lat:13.8833,lng:-61.1333},MF:{lat:18.075278,lng:-63.06},PM:{lat:46.8333,lng:-56.3333},VC:{lat:13.25,lng:-61.2},WS:{lat:-13.5833,lng:-172.3333},SM:{lat:43.7667,lng:12.4167},ST:{lat:1,lng:7},SA:{lat:25,lng:45},SN:{lat:14,lng:-14},RS:{lat:44,lng:21},SC:{lat:-4.5833,lng:55.6667},SL:{lat:8.5,lng:-11.5},SG:{lat:1.3667,lng:103.8},SX:{lat:18.033333,lng:-63.05},SK:{lat:48.6667,lng:19.5},SI:{lat:46,lng:15},SB:{lat:-8,lng:159},SO:{lat:10,lng:49},ZA:{lat:-29,lng:24},GS:{lat:-54.5,lng:-37},SS:{lat:8,lng:30},ES:{lat:40,lng:-4},LK:{lat:7,lng:81},SD:{lat:15,lng:30},SR:{lat:4,lng:-56},SJ:{lat:78,lng:20},SZ:{lat:-26.5,lng:31.5},SE:{lat:62,lng:15},CH:{lat:47,lng:8},SY:{lat:35,lng:38},TW:{lat:23.5,lng:121},TJ:{lat:39,lng:71},TZ:{lat:-6,lng:35},TH:{lat:15,lng:100},TL:{lat:-8.55,lng:125.5167},TG:{lat:8,lng:1.1667},TK:{lat:-9,lng:-172},TO:{lat:-20,lng:-175},TT:{lat:11,lng:-61},TN:{lat:34,lng:9},TR:{lat:39,lng:35},TM:{lat:40,lng:60},TC:{lat:21.75,lng:-71.5833},TV:{lat:-8,lng:178},UG:{lat:1,lng:32},UA:{lat:49,lng:32},AE:{lat:24,lng:54},GB:{lat:54,lng:-2},UM:{lat:19.2833,lng:166.6},US:{lat:38,lng:-97},UY:{lat:-33,lng:-56},UZ:{lat:41,lng:64},VU:{lat:-16,lng:167},VE:{lat:8,lng:-66},VN:{lat:16,lng:106},VG:{lat:18.5,lng:-64.5},VI:{lat:18.3333,lng:-64.8333},WF:{lat:-13.3,lng:-176.2},EH:{lat:24.5,lng:-13},YE:{lat:15,lng:48},ZM:{lat:-15,lng:30},ZW:{lat:-20,lng:30}},L={WEST_US:{code:"us-west-1",displayName:"West US (North California)",location:{lat:37.774929,lng:-122.419418}},EAST_US:{code:"us-east-1",displayName:"East US (North Virginia)",location:{lat:37.926868,lng:-78.024902}},EAST_US_2:{code:"us-east-2",displayName:"East US (Ohio)",location:{lat:39.9612,lng:-82.9988}},CENTRAL_CANADA:{code:"ca-central-1",displayName:"Canada (Central)",location:{lat:56.130367,lng:-106.346771}},WEST_EU:{code:"eu-west-1",displayName:"West EU (Ireland)",location:{lat:53.3498,lng:-6.2603}},WEST_EU_2:{code:"eu-west-2",displayName:"West Europe (London)",location:{lat:51.507351,lng:-.127758}},WEST_EU_3:{code:"eu-west-3",displayName:"West EU (Paris)",location:{lat:2.352222,lng:48.856613}},CENTRAL_EU:{code:"eu-central-1",displayName:"Central EU (Frankfurt)",location:{lat:50.110924,lng:8.682127}},CENTRAL_EU_2:{code:"eu-central-2",displayName:"Central Europe (Zurich)",location:{lat:47.3744489,lng:8.5410422}},NORTH_EU:{code:"eu-north-1",displayName:"North EU (Stockholm)",location:{lat:59.3251172,lng:18.0710935}},SOUTH_ASIA:{code:"ap-south-1",displayName:"South Asia (Mumbai)",location:{lat:18.9733536,lng:72.8281049}},SOUTHEAST_ASIA:{code:"ap-southeast-1",displayName:"Southeast Asia (Singapore)",location:{lat:1.357107,lng:103.8194992}},NORTHEAST_ASIA:{code:"ap-northeast-1",displayName:"Northeast Asia (Tokyo)",location:{lat:35.6895,lng:139.6917}},NORTHEAST_ASIA_2:{code:"ap-northeast-2",displayName:"Northeast Asia (Seoul)",location:{lat:37.5665,lng:126.978}},OCEANIA:{code:"ap-southeast-2",displayName:"Oceania (Sydney)",location:{lat:-33.8688,lng:151.2093}},SOUTH_AMERICA:{code:"sa-east-1",displayName:"South America (S\xE3o Paulo)",location:{lat:-1.2043218,lng:-47.1583944}}},oe=Object.values(L).map(e=>e.code);function re(e){let t=Object.entries(L).map(([n,s])=>[n,ke(e,s.location)]).reduce((n,s)=>n===void 0||s[1]<n[1]?s:n,void 0);if(!t)throw new Error("no closest region found");let[o]=t;return L[o]}async function se(){let r=await(await fetch(Pe)).text(),o=U(r).loc;if(!o)throw new Error("location not found");return o}function ie(e){let r=Ue[e];if(!r)throw new Error(`unknown location code: ${e}`);return r}function ke(e,r){let t=R(r.lat-e.lat),o=R(r.lng-e.lng),n=Math.sin(t/2)*Math.sin(t/2)+Math.cos(R(e.lat))*Math.cos(R(r.lat))*Math.sin(o/2)*Math.sin(o/2),s=2*Math.atan2(Math.sqrt(n),Math.sqrt(1-n));return De*s}function R(e){return e*(Math.PI/180)}function le({managementApiClient:e}){async function r(){return re(ie(await se())).code}return{list_organizations:_mcputils.tool.call(void 0, {description:"Lists all organizations that the user is a member of.",parameters:_zod.z.object({}),execute:async()=>{let t=await e.GET("/v1/organizations");return l(t,"Failed to fetch organizations"),t.data}}),get_organization:_mcputils.tool.call(void 0, {description:"Gets details for an organization. Includes subscription plan.",parameters:_zod.z.object({id:_zod.z.string().describe("The organization ID")}),execute:async({id:t})=>{let o=await e.GET("/v1/organizations/{slug}",{params:{path:{slug:t}}});return l(o,"Failed to fetch organization"),o.data}}),list_projects:_mcputils.tool.call(void 0, {description:"Lists all Supabase projects for the user. Use this to help discover the project ID of the project that the user is working on.",parameters:_zod.z.object({}),execute:async()=>{let t=await e.GET("/v1/projects");return l(t,"Failed to fetch projects"),t.data}}),get_project:_mcputils.tool.call(void 0, {description:"Gets details for a Supabase project.",parameters:_zod.z.object({id:_zod.z.string().describe("The project ID")}),execute:async({id:t})=>{let o=await e.GET("/v1/projects/{ref}",{params:{path:{ref:t}}});return l(o,"Failed to fetch project"),o.data}}),get_cost:_mcputils.tool.call(void 0, {description:"Gets the cost of creating a new project or branch. Never assume organization as costs can be different for each.",parameters:_zod.z.object({type:_zod.z.enum(["project","branch"]),organization_id:_zod.z.string().describe("The organization ID. Always ask the user.")}),execute:async({type:t,organization_id:o})=>{function n(s){return`The new ${t} will cost $${s.amount} ${s.recurrence}. You must repeat this to the user and confirm their understanding.`}switch(t){case"project":{let s=await C(e,o);return n(s)}case"branch":{let s=x();return n(s)}default:throw new Error(`Unknown cost type: ${t}`)}}}),confirm_cost:_mcputils.tool.call(void 0, {description:"Ask the user to confirm their understanding of the cost of creating a new project or branch. Call `get_cost` first. Returns a unique ID for this confirmation which should be passed to `create_project` or `create_branch`.",parameters:_zod.z.object({type:_zod.z.enum(["project","branch"]),recurrence:_zod.z.enum(["hourly","monthly"]),amount:_zod.z.number()}),execute:async t=>await A(t)}),create_project:_mcputils.tool.call(void 0, {description:"Creates a new Supabase project. Always ask the user which organization to create the project in. The project can take a few minutes to initialize - use `get_project` to check the status.",parameters:_zod.z.object({name:_zod.z.string().describe("The name of the project"),region:_zod.z.optional(_zod.z.enum(oe).describe("The region to create the project in. Defaults to the closest region.")),organization_id:_zod.z.string(),confirm_cost_id:_zod.z.string({required_error:"User must confirm understanding of costs before creating a project."}).describe("The cost confirmation ID. Call `confirm_cost` first.")}),execute:async({name:t,region:o,organization_id:n,confirm_cost_id:s})=>{let i=await C(e,n);if(await A(i)!==s)throw new Error("Cost confirmation ID does not match the expected cost of creating a project.");let p=await e.POST("/v1/projects",{body:{name:t,region:await _asyncNullishCoalesce(o, async () => (await r())),organization_id:n,db_pass:ae({length:16,numbers:!0,uppercase:!0,lowercase:!0})}});return l(p,"Failed to create project"),p.data}}),pause_project:_mcputils.tool.call(void 0, {description:"Pauses a Supabase project.",parameters:_zod.z.object({project_id:_zod.z.string()}),execute:async({project_id:t})=>{let o=await e.POST("/v1/projects/{ref}/pause",{params:{path:{ref:t}}});l(o,"Failed to pause project")}}),restore_project:_mcputils.tool.call(void 0, {description:"Restores a Supabase project.",parameters:_zod.z.object({project_id:_zod.z.string()}),execute:async({project_id:t})=>{let o=await e.POST("/v1/projects/{ref}/restore",{params:{path:{ref:t}},body:{}});l(o,"Failed to restore project")}})}}var{version:ce}=F;function hn(e){let r=_nullishCoalesce(e.platform.apiUrl, () => ("https://api.supabase.com")),t=e.projectId,o=e.readOnly,n;return _mcputils.createMcpServer.call(void 0, {name:"supabase",version:ce,onInitialize({clientInfo:i}){n=P(r,e.platform.accessToken,{"User-Agent":`supabase-mcp/${ce} (${i.name}/${i.version})`})},tools:()=>{let i={};return t||Object.assign(i,le({managementApiClient:n})),Object.assign(i,Y({managementApiClient:n,projectId:t,readOnly:o}),ne({managementApiClient:n,projectId:t}),Z({managementApiClient:n,projectId:t}),Q({managementApiClient:n,projectId:t}),H({managementApiClient:n,projectId:t})),i}})}exports.a = F; exports.b = hn;
296
+ //# sourceMappingURL=chunk-E2XY45Q4.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json","../src/server.ts","../src/management-api/index.ts","../src/tools/branching-tools.ts","../src/pg-meta/columns.sql","../src/pg-meta/extensions.sql","../src/pg-meta/tables.sql","../src/pg-meta/index.ts","../src/pg-meta/types.ts","../src/logs.ts","../src/tools/development-tools.ts","../src/edge-function.ts","../src/tools/edge-function-tools.ts","../src/password.ts"],"names":["package_default","createManagementApiClient","baseUrl","accessToken","headers","createClient","cost","stripIndent"],"mappings":"AAAA,04BAAAA,CAAAA,CAAA,CACE,IAAA,CAAQ,+BAAA,CACR,OAAA,CAAW,OAAA,CACX,WAAA,CAAe,0CAAA,CACf,OAAA,CAAW,YAAA,CACX,IAAA,CAAQ,QAAA,CACR,IAAA,CAAQ,gBAAA,CACR,KAAA,CAAS,iBAAA,CACT,WAAA,CAAe,CAAA,CAAA,CACf,OAAA,CAAW,CACT,KAAA,CAAS,cAAA,CACT,cAAA,CAAkB,eAAA,CAClB,IAAA,CAAQ,QAAA,CACR,WAAA,CAAa,uBAAA,CACb,UAAA,CAAY,sBAAA,CACZ,kBAAA,CAAoB,8BAAA,CACpB,eAAA,CAAiB,mBAAA,CACjB,+BAAA,CAAiC,0FACnC,CAAA,CACA,KAAA,CAAS,CACP,WACF,CAAA,CACA,GAAA,CAAO,CACL,qBAAA,CAAuB,iBACzB,CAAA,CACA,OAAA,CAAW,CACT,GAAA,CAAK,CACH,MAAA,CAAU,iBAAA,CACV,KAAA,CAAS,mBAAA,CACT,OAAA,CAAW,kBACb,CACF,CAAA,CACA,YAAA,CAAgB,CACd,aAAA,CAAe,SAAA,CACf,2BAAA,CAA6B,QAAA,CAC7B,qBAAA,CAAuB,OAAA,CACvB,aAAA,CAAe,QAAA,CACf,eAAA,CAAiB,SAAA,CACjB,GAAA,CAAO,SACT,CAAA,CACA,eAAA,CAAmB,CACjB,mBAAA,CAAqB,QAAA,CACrB,sBAAA,CAAwB,SAAA,CACxB,4BAAA,CAA8B,QAAA,CAC9B,oBAAA,CAAsB,QAAA,CACtB,aAAA,CAAe,SAAA,CACf,qBAAA,CAAuB,QAAA,CACvB,EAAA,CAAM,QAAA,CACN,UAAA,CAAY,QAAA,CACZ,MAAA,CAAU,SAAA,CACV,GAAA,CAAO,QAAA,CACP,MAAA,CAAU,QAAA,CACV,oBAAA,CAAsB,QAAA,CACtB,4BAAA,CAA8B,SAAA,CAC9B,QAAA,CAAY,QAAA,CACZ,IAAA,CAAQ,QAAA,CACR,GAAA,CAAO,SAAA,CACP,UAAA,CAAc,QAAA,CACd,MAAA,CAAU,QACZ,CACF,CAAA,CC5DA,+CAA2C,yGCIpC,0BAMW,SAGFC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAkC,CAAC,CAAA,CACnC,CACA,OAAOC,oCAAAA,CACL,OAAA,CAAAH,CAAAA,CACA,OAAA,CAAS,CACP,aAAA,CAAe,CAAA,OAAA,EAAUC,CAAW,CAAA,CAAA;ACmB5BG;ACxCd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACgBYC;AAAA;AAEgB,iBAAA;AACE,kBAAA;AAAA;AAAA;AAGwC,MAAA;AAAA;AAI7D,EAAA;AAsBAA;AAAA;AAAA;AAAA;AAIyD,gCAAA;AAAA;AAEhD,UAAA;AAAA;AAAA;AAGD,SAAA;ACeiB,EAAA;ACzDrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAOQ,cAAA;AAGRA,MAAAA;AAAA;AAAA;AAGQ,cAAA;AAGRA,MAAAA;AAAA;AAAA;AAAA;AAAA;AAKQ,cAAA;AAGRA,MAAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMQ,cAAA;AAGRA,MAAAA;AAAA;AAAA;AAAA;AAIQ,cAAA;AAGRA,MAAAA;AAAA;AAAA;AAGQ,cAAA;AAGRA,MAAAA;AAAA;AAAA;AAGQ,cAAA;ACTX,MAAA;AC7ByB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACmChB;AAAA;ACpBC","file":"/Users/grichardson/Documents/dev/supabase/mcp-server-supabase/packages/mcp-server-supabase/dist/chunk-E2XY45Q4.cjs","sourcesContent":["{\n \"name\": \"@supabase/mcp-server-supabase\",\n \"version\": \"0.4.1\",\n \"description\": \"MCP server for interacting with Supabase\",\n \"license\": \"Apache-2.0\",\n \"type\": \"module\",\n \"main\": \"dist/index.cjs\",\n \"types\": \"dist/index.d.ts\",\n \"sideEffects\": false,\n \"scripts\": {\n \"build\": \"tsup --clean\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"vitest\",\n \"test:unit\": \"vitest --project unit\",\n \"test:e2e\": \"vitest --project e2e\",\n \"test:integration\": \"vitest --project integration\",\n \"test:coverage\": \"vitest --coverage\",\n \"generate:management-api-types\": \"openapi-typescript https://api.supabase.com/api/v1-json -o ./src/management-api/types.ts\"\n },\n \"files\": [\n \"dist/**/*\"\n ],\n \"bin\": {\n \"mcp-server-supabase\": \"./dist/stdio.js\"\n },\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"dependencies\": {\n \"@deno/eszip\": \"^0.84.0\",\n \"@modelcontextprotocol/sdk\": \"^1.4.1\",\n \"@supabase/mcp-utils\": \"0.2.0\",\n \"common-tags\": \"^1.8.2\",\n \"openapi-fetch\": \"^0.13.5\",\n \"zod\": \"^3.24.1\"\n },\n \"devDependencies\": {\n \"@ai-sdk/anthropic\": \"^1.2.9\",\n \"@electric-sql/pglite\": \"^0.2.17\",\n \"@total-typescript/tsconfig\": \"^1.0.4\",\n \"@types/common-tags\": \"^1.8.4\",\n \"@types/node\": \"^22.8.6\",\n \"@vitest/coverage-v8\": \"^2.1.9\",\n \"ai\": \"^4.3.4\",\n \"date-fns\": \"^4.1.0\",\n \"dotenv\": \"^16.5.0\",\n \"msw\": \"^2.7.3\",\n \"nanoid\": \"^5.1.5\",\n \"openapi-typescript\": \"^7.5.0\",\n \"openapi-typescript-helpers\": \"^0.0.15\",\n \"prettier\": \"^3.3.3\",\n \"tsup\": \"^8.3.5\",\n \"tsx\": \"^4.19.2\",\n \"typescript\": \"^5.6.3\",\n \"vitest\": \"^2.1.9\"\n }\n}\n","import { createMcpServer, type Tool } from '@supabase/mcp-utils';\nimport packageJson from '../package.json' with { type: 'json' };\nimport {\n createManagementApiClient,\n type ManagementApiClient,\n} from './management-api/index.js';\nimport { getBranchingTools } from './tools/branching-tools.js';\nimport { getDatabaseOperationTools } from './tools/database-operation-tools.js';\nimport { getDebuggingTools } from './tools/debugging-tools.js';\nimport { getDevelopmentTools } from './tools/development-tools.js';\nimport { getEdgeFunctionTools } from './tools/edge-function-tools.js';\nimport { getProjectManagementTools } from './tools/project-management-tools.js';\n\nconst { version } = packageJson;\n\nexport type SupabasePlatformOptions = {\n /**\n * The access token for the Supabase Management API.\n */\n accessToken: string;\n\n /**\n * The API URL for the Supabase Management API.\n */\n apiUrl?: string;\n};\n\nexport type SupabaseMcpServerOptions = {\n /**\n * Platform options for Supabase.\n */\n platform: SupabasePlatformOptions;\n\n /**\n * The project ID to scope the server to.\n *\n * If undefined, the server will have access\n * to all organizations and projects for the user.\n */\n projectId?: string;\n\n /**\n * Executes database queries in read-only mode if true.\n */\n readOnly?: boolean;\n};\n\n/**\n * Creates an MCP server for interacting with Supabase.\n */\nexport function createSupabaseMcpServer(options: SupabaseMcpServerOptions) {\n const managementApiUrl =\n options.platform.apiUrl ?? 'https://api.supabase.com';\n const projectId = options.projectId;\n const readOnly = options.readOnly;\n\n let managementApiClient: ManagementApiClient;\n\n const server = createMcpServer({\n name: 'supabase',\n version,\n onInitialize({ clientInfo }) {\n managementApiClient = createManagementApiClient(\n managementApiUrl,\n options.platform.accessToken,\n {\n 'User-Agent': `supabase-mcp/${version} (${clientInfo.name}/${clientInfo.version})`,\n }\n );\n },\n tools: () => {\n const tools: Record<string, Tool> = {};\n\n // Add account-level tools only if projectId is not provided\n if (!projectId) {\n Object.assign(\n tools,\n getProjectManagementTools({ managementApiClient })\n );\n }\n\n // Add project-level tools\n Object.assign(\n tools,\n getDatabaseOperationTools({\n managementApiClient,\n projectId,\n readOnly,\n }),\n getEdgeFunctionTools({\n managementApiClient,\n projectId,\n }),\n getDebuggingTools({\n managementApiClient,\n projectId,\n }),\n getDevelopmentTools({\n managementApiClient,\n projectId,\n }),\n getBranchingTools({\n managementApiClient,\n projectId,\n })\n );\n\n return tools;\n },\n });\n\n return server;\n}\n","import createClient, {\n type Client,\n type FetchResponse,\n type ParseAsResponse,\n} from 'openapi-fetch';\nimport type {\n MediaType,\n ResponseObjectMap,\n SuccessResponse,\n} from 'openapi-typescript-helpers';\nimport { z } from 'zod';\nimport type { paths } from './types.js';\n\nexport function createManagementApiClient(\n baseUrl: string,\n accessToken: string,\n headers: Record<string, string> = {}\n) {\n return createClient<paths>({\n baseUrl,\n headers: {\n Authorization: `Bearer ${accessToken}`,\n ...headers,\n },\n });\n}\n\nexport type ManagementApiClient = Client<paths>;\n\nexport type SuccessResponseType<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n> = {\n data: ParseAsResponse<SuccessResponse<ResponseObjectMap<T>, Media>, Options>;\n error?: never;\n response: Response;\n};\n\nconst errorSchema = z.object({\n message: z.string(),\n});\n\nexport function assertSuccess<\n T extends Record<string | number, any>,\n Options,\n Media extends MediaType,\n>(\n response: FetchResponse<T, Options, Media>,\n fallbackMessage: string\n): asserts response is SuccessResponseType<T, Options, Media> {\n if ('error' in response) {\n if (response.response.status === 401) {\n throw new Error(\n 'Unauthorized. Please provide a valid access token to the MCP server via the --access-token flag or SUPABASE_ACCESS_TOKEN.'\n );\n }\n\n const { data: errorContent } = errorSchema.safeParse(response.error);\n\n if (errorContent) {\n throw new Error(errorContent.message);\n }\n\n throw new Error(fallbackMessage);\n }\n}\n","import { tool } from '@supabase/mcp-utils';\nimport { z } from 'zod';\nimport {\n assertSuccess,\n type ManagementApiClient,\n} from '../management-api/index.js';\nimport { getBranchCost } from '../pricing.js';\nimport { hashObject } from '../util.js';\nimport { injectableTool } from './util.js';\n\nexport type BranchingToolsOptions = {\n managementApiClient: ManagementApiClient;\n projectId?: string;\n};\n\nexport function getBranchingTools({\n managementApiClient,\n projectId,\n}: BranchingToolsOptions) {\n const project_id = projectId;\n\n return {\n create_branch: injectableTool({\n description:\n 'Creates a development branch on a Supabase project. This will apply all migrations from the main project to a fresh branch database. Note that production data will not carry over. The branch will get its own project_id via the resulting project_ref. Use this ID to execute queries and migrations on the branch.',\n parameters: z.object({\n project_id: z.string(),\n name: z\n .string()\n .default('develop')\n .describe('Name of the branch to create'),\n confirm_cost_id: z\n .string({\n required_error:\n 'User must confirm understanding of costs before creating a branch.',\n })\n .describe('The cost confirmation ID. Call `confirm_cost` first.'),\n }),\n inject: { project_id },\n execute: async ({ project_id, name, confirm_cost_id }) => {\n const cost = getBranchCost();\n const costHash = await hashObject(cost);\n if (costHash !== confirm_cost_id) {\n throw new Error(\n 'Cost confirmation ID does not match the expected cost of creating a branch.'\n );\n }\n\n const createBranchResponse = await managementApiClient.POST(\n '/v1/projects/{ref}/branches',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n body: {\n branch_name: name,\n },\n }\n );\n\n assertSuccess(createBranchResponse, 'Failed to create branch');\n\n // Creating a default branch means we just enabled branching\n // TODO: move this logic to API eventually.\n if (createBranchResponse.data.is_default) {\n await managementApiClient.PATCH('/v1/branches/{branch_id}', {\n params: {\n path: {\n branch_id: createBranchResponse.data.id,\n },\n },\n body: {\n branch_name: 'main',\n },\n });\n\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/branches',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n body: {\n branch_name: name,\n },\n }\n );\n\n assertSuccess(response, 'Failed to create branch');\n\n return response.data;\n }\n\n return createBranchResponse.data;\n },\n }),\n list_branches: injectableTool({\n description:\n 'Lists all development branches of a Supabase project. This will return branch details including status which you can use to check when operations like merge/rebase/reset complete.',\n parameters: z.object({\n project_id: z.string(),\n }),\n inject: { project_id },\n execute: async ({ project_id }) => {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/branches',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n }\n );\n\n // There are no branches if branching is disabled\n if (response.response.status === 422) return [];\n assertSuccess(response, 'Failed to list branches');\n\n return response.data;\n },\n }),\n delete_branch: tool({\n description: 'Deletes a development branch.',\n parameters: z.object({\n branch_id: z.string(),\n }),\n execute: async ({ branch_id }) => {\n const response = await managementApiClient.DELETE(\n '/v1/branches/{branch_id}',\n {\n params: {\n path: {\n branch_id,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to delete branch');\n\n return response.data;\n },\n }),\n merge_branch: tool({\n description:\n 'Merges migrations and edge functions from a development branch to production.',\n parameters: z.object({\n branch_id: z.string(),\n }),\n execute: async ({ branch_id }) => {\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id}/merge',\n {\n params: {\n path: {\n branch_id,\n },\n },\n body: {},\n }\n );\n\n assertSuccess(response, 'Failed to merge branch');\n\n return response.data;\n },\n }),\n reset_branch: tool({\n description:\n 'Resets migrations of a development branch. Any untracked data or schema changes will be lost.',\n parameters: z.object({\n branch_id: z.string(),\n migration_version: z\n .string()\n .optional()\n .describe(\n 'Reset your development branch to a specific migration version.'\n ),\n }),\n execute: async ({ branch_id, migration_version }) => {\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id}/reset',\n {\n params: {\n path: {\n branch_id,\n },\n },\n body: {\n migration_version,\n },\n }\n );\n\n assertSuccess(response, 'Failed to reset branch');\n\n return response.data;\n },\n }),\n rebase_branch: tool({\n description:\n 'Rebases a development branch on production. This will effectively run any newer migrations from production onto this branch to help handle migration drift.',\n parameters: z.object({\n branch_id: z.string(),\n }),\n execute: async ({ branch_id }) => {\n const response = await managementApiClient.POST(\n '/v1/branches/{branch_id}/push',\n {\n params: {\n path: {\n branch_id,\n },\n },\n body: {},\n }\n );\n\n assertSuccess(response, 'Failed to rebase branch');\n\n return response.data;\n },\n }),\n };\n}\n","-- Adapted from information_schema.columns\n\nSELECT\n c.oid :: int8 AS table_id,\n nc.nspname AS schema,\n c.relname AS table,\n (c.oid || '.' || a.attnum) AS id,\n a.attnum AS ordinal_position,\n a.attname AS name,\n CASE\n WHEN a.atthasdef THEN pg_get_expr(ad.adbin, ad.adrelid)\n ELSE NULL\n END AS default_value,\n CASE\n WHEN t.typtype = 'd' THEN CASE\n WHEN bt.typelem <> 0 :: oid\n AND bt.typlen = -1 THEN 'ARRAY'\n WHEN nbt.nspname = 'pg_catalog' THEN format_type(t.typbasetype, NULL)\n ELSE 'USER-DEFINED'\n END\n ELSE CASE\n WHEN t.typelem <> 0 :: oid\n AND t.typlen = -1 THEN 'ARRAY'\n WHEN nt.nspname = 'pg_catalog' THEN format_type(a.atttypid, NULL)\n ELSE 'USER-DEFINED'\n END\n END AS data_type,\n COALESCE(bt.typname, t.typname) AS format,\n a.attidentity IN ('a', 'd') AS is_identity,\n CASE\n a.attidentity\n WHEN 'a' THEN 'ALWAYS'\n WHEN 'd' THEN 'BY DEFAULT'\n ELSE NULL\n END AS identity_generation,\n a.attgenerated IN ('s') AS is_generated,\n NOT (\n a.attnotnull\n OR t.typtype = 'd' AND t.typnotnull\n ) AS is_nullable,\n (\n c.relkind IN ('r', 'p')\n OR c.relkind IN ('v', 'f') AND pg_column_is_updatable(c.oid, a.attnum, FALSE)\n ) AS is_updatable,\n uniques.table_id IS NOT NULL AS is_unique,\n check_constraints.definition AS \"check\",\n array_to_json(\n array(\n SELECT\n enumlabel\n FROM\n pg_catalog.pg_enum enums\n WHERE\n enums.enumtypid = coalesce(bt.oid, t.oid)\n OR enums.enumtypid = coalesce(bt.typelem, t.typelem)\n ORDER BY\n enums.enumsortorder\n )\n ) AS enums,\n col_description(c.oid, a.attnum) AS comment\nFROM\n pg_attribute a\n LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid\n AND a.attnum = ad.adnum\n JOIN (\n pg_class c\n JOIN pg_namespace nc ON c.relnamespace = nc.oid\n ) ON a.attrelid = c.oid\n JOIN (\n pg_type t\n JOIN pg_namespace nt ON t.typnamespace = nt.oid\n ) ON a.atttypid = t.oid\n LEFT JOIN (\n pg_type bt\n JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid\n ) ON t.typtype = 'd'\n AND t.typbasetype = bt.oid\n LEFT JOIN (\n SELECT DISTINCT ON (table_id, ordinal_position)\n conrelid AS table_id,\n conkey[1] AS ordinal_position\n FROM pg_catalog.pg_constraint\n WHERE contype = 'u' AND cardinality(conkey) = 1\n ) AS uniques ON uniques.table_id = c.oid AND uniques.ordinal_position = a.attnum\n LEFT JOIN (\n -- We only select the first column check\n SELECT DISTINCT ON (table_id, ordinal_position)\n conrelid AS table_id,\n conkey[1] AS ordinal_position,\n substring(\n pg_get_constraintdef(pg_constraint.oid, true),\n 8,\n length(pg_get_constraintdef(pg_constraint.oid, true)) - 8\n ) AS \"definition\"\n FROM pg_constraint\n WHERE contype = 'c' AND cardinality(conkey) = 1\n ORDER BY table_id, ordinal_position, oid asc\n ) AS check_constraints ON check_constraints.table_id = c.oid AND check_constraints.ordinal_position = a.attnum\nWHERE\n NOT pg_is_other_temp_schema(nc.oid)\n AND a.attnum > 0\n AND NOT a.attisdropped\n AND (c.relkind IN ('r', 'v', 'm', 'f', 'p'))\n AND (\n pg_has_role(c.relowner, 'USAGE')\n OR has_column_privilege(\n c.oid,\n a.attnum,\n 'SELECT, INSERT, UPDATE, REFERENCES'\n )\n )\n","SELECT\n e.name,\n n.nspname AS schema,\n e.default_version,\n x.extversion AS installed_version,\n e.comment\nFROM\n pg_available_extensions() e(name, default_version, comment)\n LEFT JOIN pg_extension x ON e.name = x.extname\n LEFT JOIN pg_namespace n ON x.extnamespace = n.oid\n","SELECT\n c.oid :: int8 AS id,\n nc.nspname AS schema,\n c.relname AS name,\n c.relrowsecurity AS rls_enabled,\n c.relforcerowsecurity AS rls_forced,\n CASE\n WHEN c.relreplident = 'd' THEN 'DEFAULT'\n WHEN c.relreplident = 'i' THEN 'INDEX'\n WHEN c.relreplident = 'f' THEN 'FULL'\n ELSE 'NOTHING'\n END AS replica_identity,\n pg_total_relation_size(format('%I.%I', nc.nspname, c.relname)) :: int8 AS bytes,\n pg_size_pretty(\n pg_total_relation_size(format('%I.%I', nc.nspname, c.relname))\n ) AS size,\n pg_stat_get_live_tuples(c.oid) AS live_rows_estimate,\n pg_stat_get_dead_tuples(c.oid) AS dead_rows_estimate,\n obj_description(c.oid) AS comment,\n coalesce(pk.primary_keys, '[]') as primary_keys,\n coalesce(\n jsonb_agg(relationships) filter (where relationships is not null),\n '[]'\n ) as relationships\nFROM\n pg_namespace nc\n JOIN pg_class c ON nc.oid = c.relnamespace\n left join (\n select\n table_id,\n jsonb_agg(_pk.*) as primary_keys\n from (\n select\n n.nspname as schema,\n c.relname as table_name,\n a.attname as name,\n c.oid :: int8 as table_id\n from\n pg_index i,\n pg_class c,\n pg_attribute a,\n pg_namespace n\n where\n i.indrelid = c.oid\n and c.relnamespace = n.oid\n and a.attrelid = c.oid\n and a.attnum = any (i.indkey)\n and i.indisprimary\n ) as _pk\n group by table_id\n ) as pk\n on pk.table_id = c.oid\n left join (\n select\n c.oid :: int8 as id,\n c.conname as constraint_name,\n nsa.nspname as source_schema,\n csa.relname as source_table_name,\n sa.attname as source_column_name,\n nta.nspname as target_table_schema,\n cta.relname as target_table_name,\n ta.attname as target_column_name\n from\n pg_constraint c\n join (\n pg_attribute sa\n join pg_class csa on sa.attrelid = csa.oid\n join pg_namespace nsa on csa.relnamespace = nsa.oid\n ) on sa.attrelid = c.conrelid and sa.attnum = any (c.conkey)\n join (\n pg_attribute ta\n join pg_class cta on ta.attrelid = cta.oid\n join pg_namespace nta on cta.relnamespace = nta.oid\n ) on ta.attrelid = c.confrelid and ta.attnum = any (c.confkey)\n where\n c.contype = 'f'\n ) as relationships\n on (relationships.source_schema = nc.nspname and relationships.source_table_name = c.relname)\n or (relationships.target_table_schema = nc.nspname and relationships.target_table_name = c.relname)\nWHERE\n c.relkind IN ('r', 'p')\n AND NOT pg_is_other_temp_schema(nc.oid)\n AND (\n pg_has_role(c.relowner, 'USAGE')\n OR has_table_privilege(\n c.oid,\n 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'\n )\n OR has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')\n )\ngroup by\n c.oid,\n c.relname,\n c.relrowsecurity,\n c.relforcerowsecurity,\n c.relreplident,\n nc.nspname,\n pk.primary_keys\n","import { stripIndent } from 'common-tags';\nimport columnsSql from './columns.sql';\nimport extensionsSql from './extensions.sql';\nimport tablesSql from './tables.sql';\n\nexport const SYSTEM_SCHEMAS = [\n 'information_schema',\n 'pg_catalog',\n 'pg_toast',\n '_timescaledb_internal',\n];\n\n/**\n * Generates the SQL query to list tables in the database.\n */\nexport function listTablesSql(schemas: string[] = []) {\n let sql = stripIndent`\n with\n tables as (${tablesSql}),\n columns as (${columnsSql})\n select\n *,\n ${coalesceRowsToArray('columns', 'columns.table_id = tables.id')}\n from tables\n `;\n\n sql += '\\n';\n\n if (schemas.length > 0) {\n sql += `where schema in (${schemas.map((s) => `'${s}'`).join(',')})`;\n } else {\n sql += `where schema not in (${SYSTEM_SCHEMAS.map((s) => `'${s}'`).join(',')})`;\n }\n\n return sql;\n}\n\n/**\n * Generates the SQL query to list all extensions in the database.\n */\nexport function listExtensionsSql() {\n return extensionsSql;\n}\n\n/**\n * Generates a SQL segment that coalesces rows into an array of JSON objects.\n */\nexport const coalesceRowsToArray = (source: string, filter: string) => {\n return stripIndent`\n COALESCE(\n (\n SELECT\n array_agg(row_to_json(${source})) FILTER (WHERE ${filter})\n FROM\n ${source}\n ),\n '{}'\n ) AS ${source}\n `;\n};\n","import { z } from 'zod';\n\nexport const postgresPrimaryKeySchema = z.object({\n schema: z.string(),\n table_name: z.string(),\n name: z.string(),\n table_id: z.number().int(),\n});\n\nexport const postgresRelationshipSchema = z.object({\n id: z.number().int(),\n constraint_name: z.string(),\n source_schema: z.string(),\n source_table_name: z.string(),\n source_column_name: z.string(),\n target_table_schema: z.string(),\n target_table_name: z.string(),\n target_column_name: z.string(),\n});\n\nexport const postgresColumnSchema = z.object({\n table_id: z.number().int(),\n schema: z.string(),\n table: z.string(),\n id: z.string().regex(/^(\\d+)\\.(\\d+)$/),\n ordinal_position: z.number().int(),\n name: z.string(),\n default_value: z.any(),\n data_type: z.string(),\n format: z.string(),\n is_identity: z.boolean(),\n identity_generation: z.union([\n z.literal('ALWAYS'),\n z.literal('BY DEFAULT'),\n z.null(),\n ]),\n is_generated: z.boolean(),\n is_nullable: z.boolean(),\n is_updatable: z.boolean(),\n is_unique: z.boolean(),\n enums: z.array(z.string()),\n check: z.union([z.string(), z.null()]),\n comment: z.union([z.string(), z.null()]),\n});\n\nexport const postgresTableSchema = z.object({\n id: z.number().int(),\n schema: z.string(),\n name: z.string(),\n rls_enabled: z.boolean(),\n rls_forced: z.boolean(),\n replica_identity: z.union([\n z.literal('DEFAULT'),\n z.literal('INDEX'),\n z.literal('FULL'),\n z.literal('NOTHING'),\n ]),\n bytes: z.number().int(),\n size: z.string(),\n live_rows_estimate: z.number().int(),\n dead_rows_estimate: z.number().int(),\n comment: z.string().nullable(),\n columns: z.array(postgresColumnSchema).optional(),\n primary_keys: z.array(postgresPrimaryKeySchema),\n relationships: z.array(postgresRelationshipSchema),\n});\n\nexport const postgresExtensionSchema = z.object({\n name: z.string(),\n schema: z.union([z.string(), z.null()]),\n default_version: z.string(),\n installed_version: z.union([z.string(), z.null()]),\n comment: z.union([z.string(), z.null()]),\n});\n\nexport type PostgresPrimaryKey = z.infer<typeof postgresPrimaryKeySchema>;\nexport type PostgresRelationship = z.infer<typeof postgresRelationshipSchema>;\nexport type PostgresColumn = z.infer<typeof postgresColumnSchema>;\nexport type PostgresTable = z.infer<typeof postgresTableSchema>;\nexport type PostgresExtension = z.infer<typeof postgresExtensionSchema>;\n","import { stripIndent } from 'common-tags';\n\nexport function getLogQuery(\n service:\n | 'api'\n | 'branch-action'\n | 'postgres'\n | 'edge-function'\n | 'auth'\n | 'storage'\n | 'realtime',\n limit: number = 100\n) {\n switch (service) {\n case 'api':\n return stripIndent`\n select id, identifier, timestamp, event_message, request.method, request.path, response.status_code\n from edge_logs\n cross join unnest(metadata) as m\n cross join unnest(m.request) as request\n cross join unnest(m.response) as response\n order by timestamp desc\n limit ${limit}\n `;\n case 'branch-action':\n return stripIndent`\n select workflow_run, workflow_run_logs.timestamp, id, event_message from workflow_run_logs\n order by timestamp desc\n limit ${limit}\n `;\n case 'postgres':\n return stripIndent`\n select identifier, postgres_logs.timestamp, id, event_message, parsed.error_severity from postgres_logs\n cross join unnest(metadata) as m\n cross join unnest(m.parsed) as parsed\n order by timestamp desc\n limit ${limit}\n `;\n case 'edge-function':\n return stripIndent`\n select id, function_edge_logs.timestamp, event_message, response.status_code, request.method, m.function_id, m.execution_time_ms, m.deployment_id, m.version from function_edge_logs\n cross join unnest(metadata) as m\n cross join unnest(m.response) as response\n cross join unnest(m.request) as request\n order by timestamp desc\n limit ${limit}\n `;\n case 'auth':\n return stripIndent`\n select id, auth_logs.timestamp, event_message, metadata.level, metadata.status, metadata.path, metadata.msg as msg, metadata.error from auth_logs\n cross join unnest(metadata) as metadata\n order by timestamp desc\n limit ${limit}\n `;\n case 'storage':\n return stripIndent`\n select id, storage_logs.timestamp, event_message from storage_logs\n order by timestamp desc\n limit ${limit}\n `;\n case 'realtime':\n return stripIndent`\n select id, realtime_logs.timestamp, event_message from realtime_logs\n order by timestamp desc\n limit ${limit}\n `;\n default:\n throw new Error(`unsupported log service type: ${service}`);\n }\n}\n","import { z } from 'zod';\nimport {\n assertSuccess,\n type ManagementApiClient,\n} from '../management-api/index.js';\nimport { injectableTool } from './util.js';\n\nexport type DevelopmentToolsOptions = {\n managementApiClient: ManagementApiClient;\n projectId?: string;\n};\n\nexport function getDevelopmentTools({\n managementApiClient,\n projectId,\n}: DevelopmentToolsOptions) {\n const project_id = projectId;\n\n return {\n get_project_url: injectableTool({\n description: 'Gets the API URL for a project.',\n parameters: z.object({\n project_id: z.string(),\n }),\n inject: { project_id },\n execute: async ({ project_id }) => {\n return `https://${project_id}.supabase.co`;\n },\n }),\n get_anon_key: injectableTool({\n description: 'Gets the anonymous API key for a project.',\n parameters: z.object({\n project_id: z.string(),\n }),\n inject: { project_id },\n execute: async ({ project_id }) => {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/api-keys',\n {\n params: {\n path: {\n ref: project_id,\n },\n query: {\n reveal: false,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch API keys');\n\n const anonKey = response.data?.find((key) => key.name === 'anon');\n\n if (!anonKey) {\n throw new Error('Anonymous key not found');\n }\n\n return anonKey.api_key;\n },\n }),\n generate_typescript_types: injectableTool({\n description: 'Generates TypeScript types for a project.',\n parameters: z.object({\n project_id: z.string(),\n }),\n inject: { project_id },\n execute: async ({ project_id }) => {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/types/typescript',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch TypeScript types');\n\n return response.data;\n },\n }),\n };\n}\n","import { codeBlock } from 'common-tags';\nimport { fileURLToPath } from 'node:url';\nimport { extractFiles } from './eszip.js';\nimport {\n assertSuccess,\n type ManagementApiClient,\n} from './management-api/index.js';\n\n/**\n * Gets the deployment ID for an Edge Function.\n */\nexport function getDeploymentId(\n projectId: string,\n functionId: string,\n functionVersion: number\n): string {\n return `${projectId}_${functionId}_${functionVersion}`;\n}\n\n/**\n * Gets the path prefix applied to each file in an Edge Function.\n */\nexport function getPathPrefix(deploymentId: string) {\n return `/tmp/user_fn_${deploymentId}/`;\n}\n\nexport const edgeFunctionExample = codeBlock`\n import \"jsr:@supabase/functions-js/edge-runtime.d.ts\";\n\n Deno.serve(async (req: Request) => {\n const data = {\n message: \"Hello there!\"\n };\n \n return new Response(JSON.stringify(data), {\n headers: {\n 'Content-Type': 'application/json',\n 'Connection': 'keep-alive'\n }\n });\n });\n`;\n\n/**\n * Fetches a full Edge Function from the Supabase Management API.\n\n * - Includes both function metadata and the contents of each file.\n * - Normalizes file paths to be relative to the project root.\n */\nexport async function getFullEdgeFunction(\n managementApiClient: ManagementApiClient,\n projectId: string,\n functionSlug: string\n) {\n const functionResponse = await managementApiClient.GET(\n '/v1/projects/{ref}/functions/{function_slug}',\n {\n params: {\n path: {\n ref: projectId,\n function_slug: functionSlug,\n },\n },\n }\n );\n\n if (functionResponse.error) {\n return {\n data: undefined,\n error: functionResponse.error as { message: string },\n };\n }\n\n assertSuccess(functionResponse, 'Failed to fetch Edge Function');\n\n const edgeFunction = functionResponse.data;\n\n const deploymentId = getDeploymentId(\n projectId,\n edgeFunction.id,\n edgeFunction.version\n );\n\n const pathPrefix = getPathPrefix(deploymentId);\n\n const entrypoint_path = edgeFunction.entrypoint_path\n ? fileURLToPath(edgeFunction.entrypoint_path, { windows: false }).replace(\n pathPrefix,\n ''\n )\n : undefined;\n\n const import_map_path = edgeFunction.import_map_path\n ? fileURLToPath(edgeFunction.import_map_path, { windows: false }).replace(\n pathPrefix,\n ''\n )\n : undefined;\n\n const eszipResponse = await managementApiClient.GET(\n '/v1/projects/{ref}/functions/{function_slug}/body',\n {\n params: {\n path: {\n ref: projectId,\n function_slug: functionSlug,\n },\n },\n parseAs: 'arrayBuffer',\n }\n );\n\n assertSuccess(eszipResponse, 'Failed to fetch Edge Function eszip bundle');\n\n const extractedFiles = await extractFiles(\n new Uint8Array(eszipResponse.data),\n pathPrefix\n );\n\n const files = await Promise.all(\n extractedFiles.map(async (file) => ({\n name: file.name,\n content: await file.text(),\n }))\n );\n\n const normalizedFunction = {\n ...edgeFunction,\n entrypoint_path,\n import_map_path,\n files,\n };\n\n return { data: normalizedFunction, error: undefined };\n}\n","import { z } from 'zod';\nimport { edgeFunctionExample, getFullEdgeFunction } from '../edge-function.js';\nimport {\n assertSuccess,\n type ManagementApiClient,\n} from '../management-api/index.js';\nimport { injectableTool } from './util.js';\n\nexport type EdgeFunctionToolsOptions = {\n managementApiClient: ManagementApiClient;\n projectId?: string;\n};\n\nexport function getEdgeFunctionTools({\n managementApiClient,\n projectId,\n}: EdgeFunctionToolsOptions) {\n const project_id = projectId;\n\n return {\n list_edge_functions: injectableTool({\n description: 'Lists all Edge Functions in a Supabase project.',\n parameters: z.object({\n project_id: z.string(),\n }),\n inject: { project_id },\n execute: async ({ project_id }) => {\n const response = await managementApiClient.GET(\n '/v1/projects/{ref}/functions',\n {\n params: {\n path: {\n ref: project_id,\n },\n },\n }\n );\n\n assertSuccess(response, 'Failed to fetch Edge Functions');\n\n // Fetch files for each Edge Function\n const edgeFunctions = await Promise.all(\n response.data.map(async (listedFunction) => {\n const { data: edgeFunction, error } = await getFullEdgeFunction(\n managementApiClient,\n project_id,\n listedFunction.slug\n );\n\n if (error) {\n throw error;\n }\n\n return edgeFunction;\n })\n );\n\n return edgeFunctions;\n },\n }),\n deploy_edge_function: injectableTool({\n description: `Deploys an Edge Function to a Supabase project. If the function already exists, this will create a new version. Example:\\n\\n${edgeFunctionExample}`,\n parameters: z.object({\n project_id: z.string(),\n name: z.string().describe('The name of the function'),\n entrypoint_path: z\n .string()\n .default('index.ts')\n .describe('The entrypoint of the function'),\n import_map_path: z\n .string()\n .describe('The import map for the function.')\n .optional(),\n files: z\n .array(\n z.object({\n name: z.string(),\n content: z.string(),\n })\n )\n .describe(\n 'The files to upload. This should include the entrypoint and any relative dependencies.'\n ),\n }),\n inject: { project_id },\n execute: async ({\n project_id,\n name,\n entrypoint_path,\n import_map_path,\n files,\n }) => {\n const { data: existingEdgeFunction } = await getFullEdgeFunction(\n managementApiClient,\n project_id,\n name\n );\n\n const import_map_file = files.find((file) =>\n ['deno.json', 'import_map.json'].includes(file.name)\n );\n\n // Use existing import map path or file name heuristic if not provided\n import_map_path ??=\n existingEdgeFunction?.import_map_path ?? import_map_file?.name;\n\n const response = await managementApiClient.POST(\n '/v1/projects/{ref}/functions/deploy',\n {\n params: {\n path: {\n ref: project_id,\n },\n query: { slug: name },\n },\n body: {\n metadata: {\n name,\n entrypoint_path,\n import_map_path,\n },\n file: files as any, // We need to pass file name and content to our serializer\n },\n bodySerializer(body) {\n const formData = new FormData();\n\n const blob = new Blob([JSON.stringify(body.metadata)], {\n type: 'application/json',\n });\n formData.append('metadata', blob);\n\n body.file?.forEach((f: any) => {\n const file: { name: string; content: string } = f;\n const blob = new Blob([file.content], {\n type: 'application/typescript',\n });\n formData.append('file', blob, file.name);\n });\n\n return formData;\n },\n }\n );\n\n assertSuccess(response, 'Failed to deploy Edge Function');\n\n return response.data;\n },\n }),\n };\n}\n","const UPPERCASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\nconst LOWERCASE_CHARS = 'abcdefghijklmnopqrstuvwxyz';\nconst NUMBER_CHARS = '0123456789';\nconst SYMBOL_CHARS = '!@#$%^&*()_+~`|}{[]:;?><,./-=';\n\nexport type GeneratePasswordOptions = {\n length?: number;\n numbers?: boolean;\n uppercase?: boolean;\n lowercase?: boolean;\n symbols?: boolean;\n};\n\n/**\n * Generates a cryptographically secure random password.\n *\n * @returns The generated password\n */\nexport const generatePassword = ({\n length = 10,\n numbers = false,\n symbols = false,\n uppercase = true,\n lowercase = true,\n} = {}) => {\n // Build the character set based on options\n let chars = '';\n if (uppercase) {\n chars += UPPERCASE_CHARS;\n }\n if (lowercase) {\n chars += LOWERCASE_CHARS;\n }\n if (numbers) {\n chars += NUMBER_CHARS;\n }\n if (symbols) {\n chars += SYMBOL_CHARS;\n }\n\n if (chars.length === 0) {\n throw new Error('at least one character set must be selected');\n }\n\n const randomValues = new Uint32Array(length);\n crypto.getRandomValues(randomValues);\n\n // Map random values to our character set\n let password = '';\n for (let i = 0; i < length; i++) {\n const randomIndex = randomValues[i]! % chars.length;\n password += chars.charAt(randomIndex);\n }\n\n return password;\n};\n"]}