@filess/mcp 0.1.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.
package/dist/tools.js ADDED
@@ -0,0 +1,382 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { FilessApiError } from "./client.js";
4
+ import { catalogDomains, isSensitiveCall, searchCatalog } from "./catalog.js";
5
+ const slug = z.string().min(1).regex(/^[A-Za-z0-9._-]+$/, "Use the slug, not the display name");
6
+ const scope = {
7
+ organization: slug.describe("Organization slug (see filess_account_overview)"),
8
+ namespace: slug.describe("Namespace (workspace) slug inside the organization"),
9
+ };
10
+ const queryShape = z.record(z.union([z.string(), z.number(), z.boolean()])).optional().describe("Query string parameters");
11
+ function ok(value, note) {
12
+ const text = JSON.stringify(value, (_key, v) => (typeof v === "bigint" ? v.toString() : v), 2);
13
+ return { content: [{ type: "text", text: note ? `${note}\n\n${text}` : text }] };
14
+ }
15
+ function fail(error) {
16
+ if (error instanceof FilessApiError) {
17
+ const hints = {
18
+ 0: "The Filess API is unreachable. Check FILESS_API_URL and connectivity.",
19
+ 401: "The MCP token is invalid, expired or revoked. Create a new one in the Filess panel (User settings → API tokens → Connect your AI).",
20
+ 403: "The user lacks permission for this action, or it is reserved to the web panel (credentials, MFA, account deletion). Some device actions also need recent MFA in the panel.",
21
+ 404: "Not found in this organization/namespace. Verify slugs and IDs with filess_account_overview.",
22
+ 409: "Conflict with the current state (e.g. organization being deleted, operation already running). Re-read the resource state.",
23
+ };
24
+ const details = error.details && typeof error.details === "object" ? `\nDetails: ${JSON.stringify(error.details).slice(0, 2000)}` : "";
25
+ return {
26
+ isError: true,
27
+ content: [{ type: "text", text: `Filess API error ${error.status} on ${error.method} ${error.path}: ${error.message}${hints[error.status] ? `\nHint: ${hints[error.status]}` : ""}${details}` }],
28
+ };
29
+ }
30
+ return { isError: true, content: [{ type: "text", text: error.message ?? String(error) }] };
31
+ }
32
+ async function run(action) {
33
+ try {
34
+ return await action();
35
+ }
36
+ catch (error) {
37
+ return fail(error);
38
+ }
39
+ }
40
+ export function compact(value) {
41
+ if (Array.isArray(value))
42
+ return value.map(compact);
43
+ if (!value || typeof value !== "object")
44
+ return value;
45
+ const result = {};
46
+ for (const [key, field] of Object.entries(value)) {
47
+ if (field === null || typeof field === "number" || typeof field === "boolean")
48
+ result[key] = field;
49
+ else if (typeof field === "string")
50
+ result[key] = field.length > 300 ? `${field.slice(0, 300)}…` : field;
51
+ }
52
+ return result;
53
+ }
54
+ function asList(value) {
55
+ if (Array.isArray(value))
56
+ return value;
57
+ if (value && typeof value === "object") {
58
+ for (const key of ["items", "data", "rows", "results", "databases", "projects", "tunnels"]) {
59
+ const inner = value[key];
60
+ if (Array.isArray(inner))
61
+ return inner;
62
+ }
63
+ }
64
+ return [];
65
+ }
66
+ async function settle(promise) {
67
+ try {
68
+ return await promise;
69
+ }
70
+ catch (error) {
71
+ return { error: error instanceof FilessApiError ? `${error.status} ${error.message}` : error.message };
72
+ }
73
+ }
74
+ const ns = (organization, namespace) => `/org/${organization}/${namespace}`;
75
+ const hosting = (organization, namespace) => `${ns(organization, namespace)}/hosting`;
76
+ export function registerTools(server, client) {
77
+ server.registerTool("filess_account_overview", {
78
+ title: "Account overview",
79
+ description: "START HERE. Snapshot of the user's Filess account: profile, organizations, namespaces (workspaces), dedicated databases, hosting apps with runtime status, tunnels, shared (free) databases, pending invitations and unread notifications. Returns the slugs/IDs every other tool needs.",
80
+ inputSchema: {
81
+ organization: slug.optional().describe("Limit to one organization slug"),
82
+ },
83
+ annotations: { readOnlyHint: true, openWorldHint: false },
84
+ }, ({ organization }) => run(async () => {
85
+ const [user, organizations, shared, invitations, notifications] = await Promise.all([
86
+ settle(client.get("/user/my")),
87
+ client.get("/user/organizations"),
88
+ settle(client.get("/shared/databases", { rowsPerPage: 50 })),
89
+ settle(client.get("/user/invitations/pending")),
90
+ settle(client.get("/user/notifications")),
91
+ ]);
92
+ const orgs = asList(organizations).filter(org => !organization || org.slug === organization);
93
+ const orgViews = await Promise.all(orgs.map(async (org) => {
94
+ const orgSlug = String(org.slug);
95
+ const namespaces = asList(await settle(client.get(`/org/${orgSlug}/ns`)));
96
+ const nsViews = await Promise.all(namespaces.map(async (namespace) => {
97
+ const nsSlug = String(namespace.slug);
98
+ const [databases, apps, runtime, tunnels] = await Promise.all([
99
+ settle(client.get(`${ns(orgSlug, nsSlug)}/databases`)),
100
+ settle(client.get(`${hosting(orgSlug, nsSlug)}/projects`)),
101
+ settle(client.get(`${hosting(orgSlug, nsSlug)}/projects/runtime-status`)),
102
+ settle(client.get(`${ns(orgSlug, nsSlug)}/tunnels`)),
103
+ ]);
104
+ return {
105
+ ...compact(namespace),
106
+ dedicatedDatabases: "error" in databases ? databases : compact(asList(databases)),
107
+ hostingApps: "error" in apps ? apps : compact(asList(apps)),
108
+ hostingRuntime: "error" in runtime ? runtime : runtime,
109
+ tunnels: "error" in tunnels ? tunnels : compact(asList(tunnels)),
110
+ };
111
+ }));
112
+ return { ...compact(org), namespaces: nsViews };
113
+ }));
114
+ const unread = asList(notifications).filter(item => !item.read && !item.isRead);
115
+ return ok({
116
+ user: compact(user),
117
+ organizations: orgViews,
118
+ sharedDatabases: "error" in shared ? shared : compact(asList(shared)),
119
+ pendingInvitations: compact(asList(invitations)),
120
+ unreadNotifications: unread.length,
121
+ panelHint: "Web panel: https://panel.filess.io — dedicated resources live under /dedicated/<org>/<namespace>/..., shared databases under /shared.",
122
+ });
123
+ }));
124
+ server.registerTool("filess_find_endpoints", {
125
+ title: "Find Filess API endpoints",
126
+ description: `Search the full catalogue of Filess panel API operations (everything the web panel can do). Use it to discover the method and path for any action not covered by a dedicated tool, then call it with filess_get or filess_call. Domains: ${catalogDomains.join(", ")}. Paths contain :placeholders you must replace.`,
127
+ inputSchema: {
128
+ query: z.string().optional().describe('Free-text, e.g. "backup restore", "domain", "env vars", "invite"'),
129
+ domain: z.enum(catalogDomains).optional(),
130
+ method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional(),
131
+ limit: z.number().int().min(1).max(200).optional(),
132
+ },
133
+ annotations: { readOnlyHint: true, openWorldHint: false },
134
+ }, params => run(async () => ok(searchCatalog(params))));
135
+ server.registerTool("filess_get", {
136
+ title: "Read from Filess",
137
+ description: "Read-only GET against the Filess panel API. `path` is relative to the panel API, e.g. /org/acme/main/databases/42 or /shared/databases/abc/stats. Find paths with filess_find_endpoints.",
138
+ inputSchema: { path: z.string().describe("Path starting with /, placeholders replaced"), query: queryShape },
139
+ annotations: { readOnlyHint: true, openWorldHint: false },
140
+ }, ({ path, query }) => run(async () => ok(await client.get(path, query))));
141
+ server.registerTool("filess_call", {
142
+ title: "Change something in Filess",
143
+ description: "Write operation (POST/PUT/PATCH/DELETE) against the Filess panel API, acting as the user with their permissions. Use filess_find_endpoints to find the path. Deletions, restores, rollbacks, plan changes, payments, connection kills and similar require confirm=true — only set it after the user explicitly agreed to that specific action. Payment steps return a Stripe URL the user must open themselves.",
144
+ inputSchema: {
145
+ method: z.enum(["POST", "PUT", "PATCH", "DELETE"]),
146
+ path: z.string().describe("Path starting with /, placeholders replaced"),
147
+ body: z.unknown().optional().describe("JSON body"),
148
+ query: queryShape,
149
+ confirm: z.boolean().optional().describe("Required for destructive, billing or service-interrupting actions"),
150
+ idempotencyKey: z.string().max(200).optional().describe("Optional; makes retries safe on endpoints that support Idempotency-Key"),
151
+ },
152
+ annotations: { destructiveHint: true, openWorldHint: false },
153
+ }, ({ method, path, body, query, confirm, idempotencyKey }) => run(async () => {
154
+ if (isSensitiveCall(method, path) && confirm !== true) {
155
+ return {
156
+ isError: true,
157
+ content: [{ type: "text", text: `${method} ${path} is destructive, billable or interrupts a service. Explain the consequence to the user, get explicit approval, then retry with confirm=true.` }],
158
+ };
159
+ }
160
+ const result = await client.request(method, path, {
161
+ body,
162
+ query,
163
+ headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined,
164
+ });
165
+ return ok(result ?? { ok: true });
166
+ }));
167
+ server.registerTool("hosting_app_status", {
168
+ title: "Hosting app status",
169
+ description: "Everything about one hosting app at once: configuration, live runtime status, latest deployments, domains, environment variable names (never values), linked database and pending configuration. Use it to diagnose an app before acting.",
170
+ inputSchema: { ...scope, appId: z.string().describe("Hosting app (project) ID") },
171
+ annotations: { readOnlyHint: true, openWorldHint: false },
172
+ }, ({ organization, namespace, appId }) => run(async () => {
173
+ const base = `${hosting(organization, namespace)}/projects/${appId}`;
174
+ const [project, runtime, deployments, domains, envVars, database] = await Promise.all([
175
+ client.get(base),
176
+ settle(client.get(`${base}/runtime-status`)),
177
+ settle(client.get(`${base}/deployments`)),
178
+ settle(client.get(`${base}/domains`)),
179
+ settle(client.get(`${base}/env-vars`)),
180
+ settle(client.get(`${base}/database`)),
181
+ ]);
182
+ const envList = asList(envVars).map(item => {
183
+ const v = item;
184
+ return { key: v.key, scope: v.scope, secret: v.isSecret };
185
+ });
186
+ return ok({
187
+ app: project,
188
+ runtime,
189
+ latestDeployments: Array.isArray(deployments) ? compact(deployments.slice(0, 5)) : deployments,
190
+ domains: Array.isArray(domains) ? compact(domains) : domains,
191
+ environmentVariables: "error" in envVars ? envVars : envList,
192
+ database,
193
+ });
194
+ }));
195
+ server.registerTool("hosting_create_app", {
196
+ title: "Create hosting app from Git",
197
+ description: "Create a hosting app from a Git repository. Only repositoryUrl is required: name, subdomain and region are derived when omitted. Creating an app is billable: confirm with the user first. If the response contains a Stripe checkout URL, the user must open it to pay; the app deploys after payment. Then call hosting_deploy if no deployment started.",
198
+ inputSchema: {
199
+ ...scope,
200
+ repositoryUrl: z.string().url(),
201
+ name: z.string().min(1).max(63).optional(),
202
+ branch: z.string().optional().describe("Defaults to the repository default branch"),
203
+ subdomain: z.string().regex(/^[a-z0-9-]+$/).optional(),
204
+ regionId: z.string().optional().describe("From GET /org/:org/:ns/hosting/regions; first active region when omitted"),
205
+ exposedPort: z.number().int().min(1).max(65535).optional().describe("Port your app listens on (default 3000)"),
206
+ buildSystem: z.enum(["heroku", "nixpacks", "dockerfile", "docker_compose"]).optional(),
207
+ repoAuthMethod: z.enum(["public", "pat", "oauth", "deploy_key"]).optional().describe("public for public repos; private repos need the panel to connect access"),
208
+ databaseId: z.string().optional().describe("Dedicated database to link"),
209
+ confirm: z.literal(true).describe("The user agreed to create a billable app"),
210
+ },
211
+ annotations: { destructiveHint: false, openWorldHint: false },
212
+ }, input => run(async () => {
213
+ const base = hosting(input.organization, input.namespace);
214
+ let regionId = input.regionId;
215
+ if (!regionId) {
216
+ const regions = asList(await client.get(`${base}/regions`));
217
+ regionId = (regions.find(region => region.isActive !== false) ?? regions[0])?.id;
218
+ if (!regionId)
219
+ throw new Error("No hosting region is available for this namespace.");
220
+ }
221
+ const repoName = input.repositoryUrl.replace(/\.git$/, "").split(/[/:]/).filter(Boolean).pop() ?? "app";
222
+ const name = input.name ?? repoName;
223
+ const subdomain = input.subdomain ?? `${repoName}-${randomUUID().slice(0, 6)}`.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").slice(0, 50);
224
+ const result = await client.request("POST", `${base}/projects`, {
225
+ headers: { "Idempotency-Key": randomUUID() },
226
+ body: {
227
+ name,
228
+ repositoryUrl: input.repositoryUrl,
229
+ branch: input.branch,
230
+ subdomain,
231
+ regionId,
232
+ exposedPort: input.exposedPort,
233
+ buildSystem: input.buildSystem,
234
+ repoAuthMethod: input.repoAuthMethod ?? "public",
235
+ databaseId: input.databaseId,
236
+ },
237
+ });
238
+ const checkout = result?.stripeCheckoutSession?.url;
239
+ return ok(result, checkout ? `Payment required: ask the user to open ${checkout} to activate the app.` : undefined);
240
+ }));
241
+ server.registerTool("hosting_deploy", {
242
+ title: "Deploy hosting app",
243
+ description: "Start a new deployment of a hosting app (latest commit of its branch unless commitSha is given). Follow progress with hosting_logs kind=build and hosting_app_status.",
244
+ inputSchema: {
245
+ ...scope,
246
+ appId: z.string(),
247
+ commitSha: z.string().optional(),
248
+ forceBuild: z.boolean().optional().describe("Rebuild even if an image for the commit exists"),
249
+ },
250
+ annotations: { destructiveHint: false, openWorldHint: false },
251
+ }, ({ organization, namespace, appId, commitSha, forceBuild }) => run(async () => ok(await client.request("POST", `${hosting(organization, namespace)}/projects/${appId}/deployments`, { body: { commitSha, forceBuild } }))));
252
+ server.registerTool("hosting_logs", {
253
+ title: "Hosting logs",
254
+ description: "Read logs of a hosting app. kind=runtime: live container output. kind=build / preflight: logs of a deployment (deploymentId required; take it from hosting_app_status).",
255
+ inputSchema: {
256
+ ...scope,
257
+ kind: z.enum(["runtime", "build", "preflight"]),
258
+ appId: z.string().optional().describe("Required for runtime logs"),
259
+ deploymentId: z.string().optional().describe("Required for build/preflight logs"),
260
+ tailLines: z.number().int().min(1).max(5000).optional(),
261
+ sinceSeconds: z.number().int().min(1).optional(),
262
+ previous: z.boolean().optional().describe("Runtime only: logs of the previous (crashed) container"),
263
+ service: z.string().optional().describe("Runtime only: compose service"),
264
+ },
265
+ annotations: { readOnlyHint: true, openWorldHint: false },
266
+ }, input => run(async () => {
267
+ const base = hosting(input.organization, input.namespace);
268
+ if (input.kind === "runtime") {
269
+ if (!input.appId)
270
+ throw new Error("appId is required for runtime logs");
271
+ return ok(await client.get(`${base}/projects/${input.appId}/runtime-logs`, {
272
+ tailLines: input.tailLines ?? 200,
273
+ sinceSeconds: input.sinceSeconds,
274
+ previous: input.previous,
275
+ service: input.service,
276
+ }));
277
+ }
278
+ if (!input.deploymentId)
279
+ throw new Error("deploymentId is required for build/preflight logs");
280
+ const path = input.kind === "build" ? "build-logs" : "preflight-logs";
281
+ return ok(await client.get(`${base}/deployments/${input.deploymentId}/${path}`, { tailLines: input.tailLines }));
282
+ }));
283
+ server.registerTool("hosting_set_env_vars", {
284
+ title: "Set hosting environment variables",
285
+ description: "Create or update environment variables of a hosting app in one call. Pass `variables` or a `dotenv` block (KEY=value lines). scope=runtime (default) needs a restart to apply; scope=build applies on the next deployment.",
286
+ inputSchema: {
287
+ ...scope,
288
+ appId: z.string(),
289
+ variables: z.array(z.object({
290
+ key: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),
291
+ value: z.string(),
292
+ secret: z.boolean().optional(),
293
+ scope: z.enum(["runtime", "build"]).optional(),
294
+ })).optional(),
295
+ dotenv: z.string().optional(),
296
+ scope: z.enum(["runtime", "build"]).optional().describe("Default scope for dotenv entries"),
297
+ secret: z.boolean().optional().describe("Mark dotenv entries as secret (default true)"),
298
+ overwrite: z.boolean().optional().describe("Overwrite existing keys (default true)"),
299
+ },
300
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: false },
301
+ }, input => run(async () => {
302
+ const entries = [
303
+ ...(input.variables ?? []).map(v => ({ key: v.key, value: v.value, isSecret: v.secret ?? true, scope: v.scope ?? "runtime" })),
304
+ ...parseDotenv(input.dotenv ?? "").map(([key, value]) => ({ key, value, isSecret: input.secret ?? true, scope: input.scope ?? "runtime" })),
305
+ ];
306
+ if (entries.length === 0)
307
+ throw new Error("Provide `variables` or a non-empty `dotenv` block.");
308
+ const result = await client.request("PUT", `${hosting(input.organization, input.namespace)}/projects/${input.appId}/env-vars/bulk`, {
309
+ body: { entries, conflictPolicy: input.overwrite === false ? "skip" : "override" },
310
+ });
311
+ const summary = result;
312
+ return ok({ created: summary.created, updated: summary.updated, skipped: summary.skipped }, "Runtime variables apply after hosting_restart; build variables on the next hosting_deploy.");
313
+ }));
314
+ server.registerTool("hosting_restart", {
315
+ title: "Restart hosting app",
316
+ description: "Restart the running containers of a hosting app (applies runtime configuration). Causes a brief interruption: confirm with the user.",
317
+ inputSchema: { ...scope, appId: z.string(), confirm: z.literal(true) },
318
+ annotations: { destructiveHint: true, openWorldHint: false },
319
+ }, ({ organization, namespace, appId }) => run(async () => ok(await client.request("POST", `${hosting(organization, namespace)}/projects/${appId}/restart`))));
320
+ server.registerTool("database_status", {
321
+ title: "Dedicated database status",
322
+ description: "Everything about one dedicated database: details and connection info, live status, plan, backups, backup schedule and recent alerts.",
323
+ inputSchema: { ...scope, databaseId: z.string() },
324
+ annotations: { readOnlyHint: true, openWorldHint: false },
325
+ }, ({ organization, namespace, databaseId }) => run(async () => {
326
+ const base = `${ns(organization, namespace)}/databases/${databaseId}`;
327
+ const [database, status, backups, schedule, alertRules] = await Promise.all([
328
+ client.get(base),
329
+ settle(client.get(`${base}/metrics/status`)),
330
+ settle(client.get(`${base}/backup`)),
331
+ settle(client.get(`${base}/backup/schedule`)),
332
+ settle(client.get(`${base}/alerts/rules`)),
333
+ ]);
334
+ return ok({
335
+ database,
336
+ status,
337
+ backups: Array.isArray(backups) ? compact(backups.slice(0, 10)) : backups,
338
+ backupSchedule: schedule,
339
+ alertRules,
340
+ });
341
+ }));
342
+ server.registerTool("shared_database_create", {
343
+ title: "Create shared database",
344
+ description: "Fastest way to get a database: creates a shared database (free tier available) without organization or payment. `engine` is matched by name (mysql, mariadb, postgresql, mongodb...). Returns connection details.",
345
+ inputSchema: {
346
+ engine: z.string().describe("Engine name or motor ID"),
347
+ name: z.string().min(1).describe("Database name"),
348
+ region: z.string().optional().describe("Region code/ID from GET /shared/databases/meta/regions"),
349
+ },
350
+ annotations: { destructiveHint: false, openWorldHint: false },
351
+ }, ({ engine, name, region }) => run(async () => {
352
+ const motors = asList(await client.get("/shared/databases/meta/motors"));
353
+ const wanted = engine.toLowerCase().replace(/sql$/, "");
354
+ const motor = motors.find(m => String(m.id) === engine)
355
+ ?? motors.find(m => [m.name, m.slug, m.motor, m.engine].some(v => typeof v === "string" && v.toLowerCase().replace(/sql$/, "") === wanted))
356
+ ?? motors.find(m => [m.name, m.slug, m.motor, m.engine].some(v => typeof v === "string" && v.toLowerCase().includes(wanted)));
357
+ if (!motor) {
358
+ return ok(compact(motors), `No engine matches "${engine}". Available engines:`);
359
+ }
360
+ return ok(await client.request("POST", "/shared/databases", { body: { motorId: String(motor.id), dbName: name, region } }));
361
+ }));
362
+ }
363
+ export function parseDotenv(text) {
364
+ const entries = [];
365
+ for (const rawLine of text.split(/\r?\n/)) {
366
+ const line = rawLine.trim().replace(/^export\s+/, "");
367
+ if (!line || line.startsWith("#"))
368
+ continue;
369
+ const index = line.indexOf("=");
370
+ if (index <= 0)
371
+ continue;
372
+ const key = line.slice(0, index).trim();
373
+ let value = line.slice(index + 1).trim();
374
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))
375
+ value = value.slice(1, -1);
376
+ else
377
+ value = value.replace(/\s+#.*$/, "");
378
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
379
+ entries.push([key, value]);
380
+ }
381
+ return entries;
382
+ }
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@filess/mcp",
3
+ "version": "0.1.1",
4
+ "description": "Model Context Protocol server for Filess: lets AI agents see and operate a Filess account.",
5
+ "keywords": [
6
+ "mcp",
7
+ "model-context-protocol",
8
+ "filess",
9
+ "ai",
10
+ "agents",
11
+ "hosting",
12
+ "database"
13
+ ],
14
+ "homepage": "https://filess.io",
15
+ "type": "module",
16
+ "bin": {
17
+ "filess-mcp": "dist/index.js"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "build": "tsc -p tsconfig.json && node -e \"require('fs').copyFileSync('src/catalog.json','dist/catalog.json')\"",
31
+ "typecheck": "tsc -p tsconfig.json --noEmit",
32
+ "start": "node dist/index.js",
33
+ "start:http": "node dist/index.js --http",
34
+ "catalog": "bun scripts/generate-catalog.ts",
35
+ "test": "bun test ./test"
36
+ },
37
+ "dependencies": {
38
+ "@modelcontextprotocol/sdk": "^1.32.2",
39
+ "zod": "^3.25.76"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.10.0",
43
+ "typescript": "^5.6.3"
44
+ }
45
+ }