@vigylx/mcp-servers 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ /**
3
+ * Deciding whether a statement is a read, before it reaches the database.
4
+ *
5
+ * This is a typo filter, not the security boundary. The boundary is a
6
+ * `BEGIN TRANSACTION READ ONLY` wrapper, which Postgres itself enforces. Both
7
+ * exist because the string check gives a clear error for an obvious mistake,
8
+ * and the transaction stops everything the string check cannot see.
9
+ *
10
+ * The build guide used only the string check — `sql.startsWith('select') ||
11
+ * sql.startsWith('with')` — and that is genuinely unsafe. Measured against a
12
+ * real Neon database on 2026-10-14:
13
+ *
14
+ * WITH gone AS (DELETE FROM users WHERE id=1 RETURNING *) SELECT * FROM gone
15
+ * -> allowed by the check, deleted the row
16
+ * SELECT 1; DROP TABLE users
17
+ * -> allowed by the check, dropped the table
18
+ *
19
+ * Postgres allows data-modifying CTEs, and node-postgres sends a query with no
20
+ * parameters over the simple protocol, which permits multiple statements.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.STATEMENT_TIMEOUT_MS = exports.DEFAULT_ROWS = exports.MAX_ROWS = void 0;
24
+ exports.stripLiterals = stripLiterals;
25
+ exports.checkReadOnly = checkReadOnly;
26
+ exports.clampRows = clampRows;
27
+ exports.isValidIdentifier = isValidIdentifier;
28
+ exports.redactConnectionString = redactConnectionString;
29
+ const NL = String.fromCharCode(10);
30
+ /** Rows returned to the model. Beyond this nobody reads it and the prompt suffers. */
31
+ exports.MAX_ROWS = 200;
32
+ exports.DEFAULT_ROWS = 50;
33
+ /** A query that runs longer than this is a mistake or an attack. */
34
+ exports.STATEMENT_TIMEOUT_MS = 10_000;
35
+ /**
36
+ * Remove comments and string literals.
37
+ *
38
+ * Both can hide a semicolon or a keyword: `SELECT 1 /* ; DROP TABLE x *​/` and
39
+ * `SELECT ';DROP TABLE x'` are each harmless, while `SELECT 1; DROP TABLE x`
40
+ * is not, and they are indistinguishable without this.
41
+ */
42
+ function stripLiterals(sql) {
43
+ let out = '';
44
+ let index = 0;
45
+ while (index < sql.length) {
46
+ const two = sql.slice(index, index + 2);
47
+ if (two === '--') {
48
+ const end = sql.indexOf(NL, index);
49
+ index = end === -1 ? sql.length : end;
50
+ continue;
51
+ }
52
+ if (two === '/*') {
53
+ const end = sql.indexOf('*/', index + 2);
54
+ index = end === -1 ? sql.length : end + 2;
55
+ out += ' ';
56
+ continue;
57
+ }
58
+ const char = sql[index];
59
+ if (char === "'" || char === '"') {
60
+ const quote = char;
61
+ index += 1;
62
+ while (index < sql.length) {
63
+ if (sql[index] === quote) {
64
+ // A doubled quote is an escaped quote, not the end.
65
+ if (sql[index + 1] === quote)
66
+ index += 2;
67
+ else
68
+ break;
69
+ }
70
+ else {
71
+ index += 1;
72
+ }
73
+ }
74
+ index += 1;
75
+ out += quote + quote;
76
+ continue;
77
+ }
78
+ // $tag$ ... $tag$ dollar quoting.
79
+ if (char === '$') {
80
+ const match = /^\$[A-Za-z_]*\$/.exec(sql.slice(index));
81
+ if (match) {
82
+ const tag = match[0];
83
+ const end = sql.indexOf(tag, index + tag.length);
84
+ index = end === -1 ? sql.length : end + tag.length;
85
+ out += ' ';
86
+ continue;
87
+ }
88
+ }
89
+ out += char;
90
+ index += 1;
91
+ }
92
+ return out;
93
+ }
94
+ /** Keywords that write, wherever they appear — including inside a CTE. */
95
+ const WRITING = [
96
+ 'insert',
97
+ 'update',
98
+ 'delete',
99
+ 'truncate',
100
+ 'drop',
101
+ 'create',
102
+ 'alter',
103
+ 'grant',
104
+ 'revoke',
105
+ 'comment',
106
+ 'merge',
107
+ 'copy',
108
+ 'vacuum',
109
+ 'reindex',
110
+ 'cluster',
111
+ 'refresh',
112
+ 'call',
113
+ 'do',
114
+ 'set',
115
+ 'reset',
116
+ 'lock',
117
+ 'listen',
118
+ 'notify',
119
+ 'prepare',
120
+ 'execute',
121
+ 'begin',
122
+ 'commit',
123
+ 'rollback',
124
+ 'savepoint',
125
+ 'security',
126
+ ];
127
+ /**
128
+ * Is this one read-only statement?
129
+ *
130
+ * Deliberately strict: a rejected legitimate query is an inconvenience, a
131
+ * permitted write is data loss.
132
+ */
133
+ function checkReadOnly(sql) {
134
+ const raw = sql.trim();
135
+ if (raw === '')
136
+ return { ok: false, reason: 'The query is empty.' };
137
+ if (raw.length > 20_000)
138
+ return { ok: false, reason: 'That query is too long.' };
139
+ const bare = stripLiterals(raw).trim();
140
+ const lower = bare.toLowerCase();
141
+ // One statement only. node-postgres sends a parameterless query over the
142
+ // simple protocol, which happily runs "SELECT 1; DROP TABLE users".
143
+ const withoutTrailing = bare.replace(/;\s*$/, '');
144
+ if (withoutTrailing.includes(';')) {
145
+ return {
146
+ ok: false,
147
+ reason: 'Only one statement at a time. Remove the semicolon and anything after it.',
148
+ };
149
+ }
150
+ if (!/^(select|with|table|values|explain|show)\b/.test(lower)) {
151
+ return {
152
+ ok: false,
153
+ reason: 'Only read queries are allowed: SELECT, WITH, TABLE, VALUES, SHOW or EXPLAIN.',
154
+ };
155
+ }
156
+ // A WITH clause may contain INSERT, UPDATE or DELETE, and Postgres runs it.
157
+ // This is the case the guide's check misses entirely.
158
+ for (const keyword of WRITING) {
159
+ const pattern = new RegExp('(?:^|[^A-Za-z0-9_])' + keyword + '(?:[^A-Za-z0-9_]|$)', 'i');
160
+ if (pattern.test(lower)) {
161
+ return {
162
+ ok: false,
163
+ reason: `That query contains "${keyword.toUpperCase()}", which can modify data. ` +
164
+ 'Only plain reads are allowed.',
165
+ };
166
+ }
167
+ }
168
+ // SELECT ... INTO creates a table.
169
+ if (/\binto\b/.test(lower) && !/\binsert\b/.test(lower)) {
170
+ return { ok: false, reason: 'SELECT ... INTO creates a table, which is a write.' };
171
+ }
172
+ // EXPLAIN ANALYZE executes the statement it is explaining. Postgres accepts
173
+ // both spellings, so both are refused.
174
+ if (/^explain\b/.test(lower) && /\banaly[sz]e\b/.test(lower)) {
175
+ return { ok: false, reason: 'EXPLAIN ANALYZE runs the query it explains. Use plain EXPLAIN.' };
176
+ }
177
+ return { ok: true };
178
+ }
179
+ function clampRows(requested) {
180
+ if (requested === undefined || !Number.isFinite(requested))
181
+ return exports.DEFAULT_ROWS;
182
+ return Math.min(exports.MAX_ROWS, Math.max(1, Math.floor(requested)));
183
+ }
184
+ /**
185
+ * A table name for `db_schema`.
186
+ *
187
+ * Passed as a parameter to information_schema, so injection is not the risk;
188
+ * this keeps the error useful instead of returning an empty column list for
189
+ * something that was never a table name.
190
+ */
191
+ function isValidIdentifier(name) {
192
+ return /^[A-Za-z_][A-Za-z0-9_$]{0,62}$/.test(name);
193
+ }
194
+ /** Hide the password before a connection string reaches a log or a model. */
195
+ function redactConnectionString(url) {
196
+ return url.replace(/:\/\/([^:@/]+):[^@]*@/, '://$1:***@');
197
+ }
198
+ //# sourceMappingURL=sql.js.map
@@ -0,0 +1,21 @@
1
+ export interface ServiceAccount {
2
+ readonly project_id: string;
3
+ readonly client_email: string;
4
+ readonly private_key: string;
5
+ }
6
+ export interface CredentialSource {
7
+ readonly env?: Record<string, string | undefined>;
8
+ readonly readFile?: (path: string) => string;
9
+ }
10
+ /**
11
+ * Read the service account from `FIREBASE_SERVICE_ACCOUNT` (base64 of the JSON)
12
+ * or `FIREBASE_SERVICE_ACCOUNT_FILE` (a path).
13
+ *
14
+ * The base64 form is what the build guide specifies and what survives being put
15
+ * in an env var. The file form exists because it is what the Firebase console
16
+ * hands you, and copying a path is safer than copying a private key.
17
+ *
18
+ * Errors never quote the value. A malformed key is still a key.
19
+ */
20
+ export declare function loadServiceAccount(source?: CredentialSource): ServiceAccount;
21
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadServiceAccount = loadServiceAccount;
4
+ /**
5
+ * Loading the Firebase service account, without putting it anywhere it can leak.
6
+ */
7
+ const node_fs_1 = require("node:fs");
8
+ /** The fields firebase-admin needs; anything else in the file is ignored. */
9
+ function validate(parsed, origin) {
10
+ if (typeof parsed !== 'object' || parsed === null) {
11
+ throw new Error(`${origin} is not a JSON object`);
12
+ }
13
+ const account = parsed;
14
+ for (const field of ['project_id', 'client_email', 'private_key']) {
15
+ if (typeof account[field] !== 'string' || account[field] === '') {
16
+ throw new Error(`${origin} is missing "${field}" — is it a service account key?`);
17
+ }
18
+ }
19
+ return account;
20
+ }
21
+ /**
22
+ * Read the service account from `FIREBASE_SERVICE_ACCOUNT` (base64 of the JSON)
23
+ * or `FIREBASE_SERVICE_ACCOUNT_FILE` (a path).
24
+ *
25
+ * The base64 form is what the build guide specifies and what survives being put
26
+ * in an env var. The file form exists because it is what the Firebase console
27
+ * hands you, and copying a path is safer than copying a private key.
28
+ *
29
+ * Errors never quote the value. A malformed key is still a key.
30
+ */
31
+ function loadServiceAccount(source = {}) {
32
+ const env = source.env ?? process.env;
33
+ const read = source.readFile ?? ((path) => (0, node_fs_1.readFileSync)(path, 'utf8'));
34
+ const encoded = env.FIREBASE_SERVICE_ACCOUNT?.trim();
35
+ if (encoded) {
36
+ let decoded;
37
+ try {
38
+ decoded = Buffer.from(encoded, 'base64').toString('utf8');
39
+ }
40
+ catch {
41
+ throw new Error('FIREBASE_SERVICE_ACCOUNT is not valid base64');
42
+ }
43
+ let parsed;
44
+ try {
45
+ parsed = JSON.parse(decoded);
46
+ }
47
+ catch {
48
+ throw new Error('FIREBASE_SERVICE_ACCOUNT did not decode to JSON. It should be the ' +
49
+ 'base64 of the whole service account file.');
50
+ }
51
+ return validate(parsed, 'FIREBASE_SERVICE_ACCOUNT');
52
+ }
53
+ const path = env.FIREBASE_SERVICE_ACCOUNT_FILE?.trim();
54
+ if (path) {
55
+ let contents;
56
+ try {
57
+ contents = read(path);
58
+ }
59
+ catch {
60
+ throw new Error(`FIREBASE_SERVICE_ACCOUNT_FILE points at a file that cannot be read: ${path}`);
61
+ }
62
+ let parsed;
63
+ try {
64
+ parsed = JSON.parse(contents);
65
+ }
66
+ catch {
67
+ throw new Error(`${path} is not valid JSON`);
68
+ }
69
+ return validate(parsed, path);
70
+ }
71
+ throw new Error('No Firebase credentials. Set FIREBASE_SERVICE_ACCOUNT (base64 of the ' +
72
+ 'service account JSON) or FIREBASE_SERVICE_ACCOUNT_FILE (a path to it). ' +
73
+ 'Get one from Firebase console → Project settings → Service accounts.');
74
+ }
75
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Firebase MCP server.
4
+ *
5
+ * Answers questions about a Firebase project over stdio, so Vigyl can turn
6
+ * "how many users signed up today?" into a real number.
7
+ *
8
+ * Read-only by design: nothing here writes, deletes or changes configuration.
9
+ * A tool that could delete a collection would be one prompt injection away from
10
+ * doing it, and the approval gate lives in the daemon, not here.
11
+ */
12
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
+ /** firebase-admin v13 dropped the `import * as admin` namespace the guide uses. */
14
+ type Firestore = import('firebase-admin/firestore').Firestore;
15
+ type Auth = import('firebase-admin/auth').Auth;
16
+ interface FirebaseHandles {
17
+ db: Firestore;
18
+ auth: Auth;
19
+ projectId: string;
20
+ }
21
+ export declare function registerFirebaseTools(server: McpServer, handles: FirebaseHandles): void;
22
+ export {};
23
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,272 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.registerFirebaseTools = registerFirebaseTools;
38
+ /**
39
+ * Firebase MCP server.
40
+ *
41
+ * Answers questions about a Firebase project over stdio, so Vigyl can turn
42
+ * "how many users signed up today?" into a real number.
43
+ *
44
+ * Read-only by design: nothing here writes, deletes or changes configuration.
45
+ * A tool that could delete a collection would be one prompt injection away from
46
+ * doing it, and the approval gate lives in the daemon, not here.
47
+ */
48
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
49
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
50
+ const zod_1 = require("zod");
51
+ const untrusted_1 = require("../shared/untrusted");
52
+ const credentials_1 = require("./credentials");
53
+ const query_1 = require("./query");
54
+ const SERVER_NAME = 'vigyl-firebase';
55
+ const VERSION = '0.2.0';
56
+ /** Where the operator is, for anything that means "today". */
57
+ const DEFAULT_TIME_ZONE = process.env.VIGYL_TIMEZONE?.trim() || 'UTC';
58
+ async function connect() {
59
+ const account = (0, credentials_1.loadServiceAccount)();
60
+ const { initializeApp, cert } = await Promise.resolve().then(() => __importStar(require('firebase-admin/app')));
61
+ const { getFirestore } = await Promise.resolve().then(() => __importStar(require('firebase-admin/firestore')));
62
+ const { getAuth } = await Promise.resolve().then(() => __importStar(require('firebase-admin/auth')));
63
+ const app = initializeApp({
64
+ credential: cert({
65
+ projectId: account.project_id,
66
+ clientEmail: account.client_email,
67
+ privateKey: account.private_key,
68
+ }),
69
+ });
70
+ return { db: getFirestore(app), auth: getAuth(app), projectId: account.project_id };
71
+ }
72
+ /**
73
+ * Walk Auth users, with a ceiling.
74
+ *
75
+ * Returns `exact: false` when the ceiling was hit, so the caller can say "at
76
+ * least" instead of stating a wrong number confidently.
77
+ */
78
+ async function countUsers(auth, since) {
79
+ let count = 0;
80
+ let scanned = 0;
81
+ let pageToken;
82
+ let pages = 0;
83
+ do {
84
+ const page = await auth.listUsers(1000, pageToken);
85
+ scanned += page.users.length;
86
+ count += since
87
+ ? page.users.filter((user) => {
88
+ const created = user.metadata.creationTime;
89
+ return created !== undefined && new Date(created) >= since;
90
+ }).length
91
+ : page.users.length;
92
+ pageToken = page.pageToken;
93
+ pages += 1;
94
+ } while (pageToken && pages < query_1.MAX_AUTH_PAGES);
95
+ return { count, exact: pageToken === undefined, scanned };
96
+ }
97
+ /**
98
+ * Declared outside the call because zod's inference on the nested object
99
+ * exceeds TypeScript's instantiation depth when inlined into registerTool.
100
+ */
101
+ const FIRESTORE_QUERY_SHAPE = {
102
+ collection: zod_1.z
103
+ .string()
104
+ .describe('Collection name, e.g. "users". A subcollection path like "users/u1/sessions" also works.'),
105
+ limit: zod_1.z
106
+ .number()
107
+ .int()
108
+ .optional()
109
+ .describe(`How many documents to return (default ${query_1.DEFAULT_LIMIT}, max ${query_1.MAX_LIMIT}).`),
110
+ orderBy: zod_1.z.string().optional().describe('Field to order by.'),
111
+ direction: zod_1.z.enum(['asc', 'desc']).optional().describe('Order direction, default asc.'),
112
+ where: zod_1.z
113
+ .object({
114
+ field: zod_1.z.string(),
115
+ operator: zod_1.z.enum(['==', '!=', '<', '<=', '>', '>=']),
116
+ value: zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.boolean()]),
117
+ })
118
+ .optional()
119
+ .describe('Optional filter.'),
120
+ };
121
+ function registerFirebaseTools(server, handles) {
122
+ const { db, auth, projectId } = handles;
123
+ const registerTool = server.registerTool.bind(server);
124
+ registerTool('firestore_query', {
125
+ title: 'Query Firestore',
126
+ description: 'Read documents from a Firestore collection, newest first if an orderBy ' +
127
+ 'is given. Read-only. Returns at most ' + query_1.MAX_LIMIT + ' documents.',
128
+ inputSchema: FIRESTORE_QUERY_SHAPE,
129
+ annotations: { readOnlyHint: true },
130
+ }, async (raw) => {
131
+ const args = raw;
132
+ const { collection, limit, orderBy, direction, where } = args;
133
+ if (!(0, query_1.isAllowedCollection)(collection)) {
134
+ return (0, untrusted_1.errorResult)(`"${collection}" is not a collection name this server will read. Use a ` +
135
+ 'plain name such as "users", or a subcollection path such as "users/u1/sessions".');
136
+ }
137
+ const operator = query_1.WHERE_OPERATORS.find((candidate) => candidate === where?.operator);
138
+ if (where && !operator) {
139
+ return (0, untrusted_1.errorResult)(`Unsupported operator: ${where.operator}`);
140
+ }
141
+ const capped = (0, query_1.clampLimit)(limit);
142
+ try {
143
+ let query = db.collection(collection);
144
+ if (where && operator)
145
+ query = query.where(where.field, operator, where.value);
146
+ if (orderBy)
147
+ query = query.orderBy(orderBy, direction ?? 'asc');
148
+ query = query.limit(capped);
149
+ const snapshot = await query.get();
150
+ const documents = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
151
+ return (0, untrusted_1.dataResult)(`firestore ${projectId}/${collection}`, {
152
+ collection,
153
+ returned: documents.length,
154
+ limit: capped,
155
+ truncated: documents.length === capped,
156
+ documents,
157
+ });
158
+ }
159
+ catch (error) {
160
+ return (0, untrusted_1.errorResult)(describeFirestoreError(error, collection, orderBy));
161
+ }
162
+ });
163
+ registerTool('auth_user_count', {
164
+ title: 'Count Firebase Auth users',
165
+ description: 'Total number of users in Firebase Authentication.',
166
+ inputSchema: {},
167
+ annotations: { readOnlyHint: true },
168
+ }, async () => {
169
+ try {
170
+ const { count, exact, scanned } = await countUsers(auth);
171
+ return (0, untrusted_1.dataResult)(`firebase auth ${projectId}`, {
172
+ totalUsers: count,
173
+ exact,
174
+ note: exact
175
+ ? undefined
176
+ : `Stopped after scanning ${scanned} users; the real total is higher.`,
177
+ });
178
+ }
179
+ catch (error) {
180
+ return (0, untrusted_1.errorResult)(describeAuthError(error));
181
+ }
182
+ });
183
+ registerTool('auth_users_today', {
184
+ title: 'Count sign-ups today',
185
+ description: 'How many Firebase Auth users were created since midnight in the ' +
186
+ 'configured time zone. Note: Firebase reports the real creation time, ' +
187
+ 'which cannot be backdated, so seeded test users all appear as today.',
188
+ inputSchema: {
189
+ timeZone: zod_1.z
190
+ .string()
191
+ .optional()
192
+ .describe(`IANA time zone deciding when "today" starts (default ${DEFAULT_TIME_ZONE}).`),
193
+ },
194
+ annotations: { readOnlyHint: true },
195
+ }, async (raw) => {
196
+ const { timeZone } = raw;
197
+ const zone = timeZone?.trim() || DEFAULT_TIME_ZONE;
198
+ if (!(0, query_1.isValidTimeZone)(zone)) {
199
+ return (0, untrusted_1.errorResult)(`"${zone}" is not a time zone this system knows. Use an IANA name like Asia/Kolkata.`);
200
+ }
201
+ try {
202
+ const since = (0, query_1.startOfToday)(zone);
203
+ const { count, exact, scanned } = await countUsers(auth, since);
204
+ return (0, untrusted_1.dataResult)(`firebase auth ${projectId}`, {
205
+ signupsToday: count,
206
+ since: since.toISOString(),
207
+ timeZone: zone,
208
+ exact,
209
+ note: exact ? undefined : `Stopped after scanning ${scanned} users; there may be more.`,
210
+ });
211
+ }
212
+ catch (error) {
213
+ return (0, untrusted_1.errorResult)(describeAuthError(error));
214
+ }
215
+ });
216
+ }
217
+ /**
218
+ * Turn a Firestore failure into something the operator can act on.
219
+ *
220
+ * The raw error is not relayed: it can carry the project id, internal hostnames
221
+ * and occasionally a token fragment. The missing-index case gets its own
222
+ * message because it is the one every new query hits and the fix is specific.
223
+ */
224
+ function describeFirestoreError(error, collection, orderBy) {
225
+ const code = error.code;
226
+ const message = String(error?.message ?? error);
227
+ if (/requires an index/i.test(message)) {
228
+ return (`Firestore needs a composite index for this query on "${collection}"` +
229
+ (orderBy ? ` (filtering and ordering by "${orderBy}")` : '') +
230
+ '. Create it in the Firebase console, then ask again.');
231
+ }
232
+ if (code === 7 || /permission|PERMISSION_DENIED/i.test(message)) {
233
+ return `The service account is not allowed to read "${collection}".`;
234
+ }
235
+ if (code === 5 || /NOT_FOUND/i.test(message)) {
236
+ return `No collection named "${collection}" in this project.`;
237
+ }
238
+ if (/UNAVAILABLE|ECONNREFUSED|ENOTFOUND|deadline/i.test(message)) {
239
+ return 'Could not reach Firestore. Check the network and try again.';
240
+ }
241
+ return `Firestore query on "${collection}" failed.`;
242
+ }
243
+ function describeAuthError(error) {
244
+ const message = String(error?.message ?? error);
245
+ if (/insufficient permission|PERMISSION_DENIED/i.test(message)) {
246
+ return 'The service account is not allowed to list Authentication users.';
247
+ }
248
+ if (/UNAVAILABLE|ECONNREFUSED|ENOTFOUND|deadline/i.test(message)) {
249
+ return 'Could not reach Firebase Authentication. Check the network and try again.';
250
+ }
251
+ return 'Reading Firebase Authentication failed.';
252
+ }
253
+ /**
254
+ * Top-level await does not compile under `module: commonjs`, which is what the
255
+ * build guide's version used. This is the same server, started properly.
256
+ */
257
+ async function main() {
258
+ const handles = await connect();
259
+ const server = new mcp_js_1.McpServer({ name: SERVER_NAME, version: VERSION });
260
+ registerFirebaseTools(server, handles);
261
+ // stdout is the protocol channel: anything written to it that is not a
262
+ // message corrupts the stream, so diagnostics go to stderr.
263
+ await server.connect(new stdio_js_1.StdioServerTransport());
264
+ process.stderr.write(`${SERVER_NAME} ready for project ${handles.projectId}\n`);
265
+ }
266
+ if (require.main === module) {
267
+ main().catch((error) => {
268
+ process.stderr.write(`${SERVER_NAME} failed to start: ${error.message}\n`);
269
+ process.exit(1);
270
+ });
271
+ }
272
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The decisions a Firestore query makes before it touches the network.
3
+ *
4
+ * Separated from the server so they can be tested without credentials: what
5
+ * counts as a legal collection name, how big a page may be, and where "today"
6
+ * starts.
7
+ */
8
+ /** A page bigger than this is rarely read and always expensive. */
9
+ export declare const MAX_LIMIT = 100;
10
+ export declare const DEFAULT_LIMIT = 10;
11
+ /**
12
+ * Pages of 1,000 Auth users to walk before giving up.
13
+ *
14
+ * `listUsers` is the only way to count, and on a large project it never ends.
15
+ * The count is reported as "at least" when the cap is hit, rather than pretending
16
+ * to be exact or hanging the command.
17
+ */
18
+ export declare const MAX_AUTH_PAGES = 20;
19
+ export declare function clampLimit(requested: number | undefined): number;
20
+ /**
21
+ * Is this a collection the server will read?
22
+ *
23
+ * Firestore accepts a slash-separated path, so `users/u1/sessions` is a valid
24
+ * collection reference — and so is anything else with an odd number of
25
+ * segments. Allowing a free-form path would let a prompt walk the whole
26
+ * database a level at a time, so only plain names and explicit subcollection
27
+ * paths of known shape are accepted, and nothing with traversal in it.
28
+ */
29
+ export declare function isAllowedCollection(name: string): boolean;
30
+ export type WhereOperator = '==' | '!=' | '<' | '<=' | '>' | '>=';
31
+ export declare const WHERE_OPERATORS: readonly WhereOperator[];
32
+ /**
33
+ * The start of today, in a named IANA zone.
34
+ *
35
+ * "How many users signed up today?" is asked by a person in a place. The server
36
+ * runs wherever it runs, and on a UTC box the answer is wrong for most of the
37
+ * day in Asia — by 05:30 for the operator of this project.
38
+ */
39
+ export declare function startOfToday(timeZone: string, now?: Date): Date;
40
+ /** Reject a time zone the platform does not know, rather than silently using UTC. */
41
+ export declare function isValidTimeZone(timeZone: string): boolean;
42
+ //# sourceMappingURL=query.d.ts.map