@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/client.js ADDED
@@ -0,0 +1,117 @@
1
+ export class FilessApiError extends Error {
2
+ status;
3
+ method;
4
+ path;
5
+ details;
6
+ constructor(message, status, method, path, details) {
7
+ super(message);
8
+ this.status = status;
9
+ this.method = method;
10
+ this.path = path;
11
+ this.details = details;
12
+ this.name = "FilessApiError";
13
+ }
14
+ }
15
+ export function normalizePanelPath(path) {
16
+ const trimmed = path.trim();
17
+ if (!trimmed.startsWith("/"))
18
+ throw new Error(`Path must start with "/": ${path}`);
19
+ if (/[?#]/.test(trimmed))
20
+ throw new Error("Put query parameters in `query`, not in the path.");
21
+ const segments = trimmed.split("/");
22
+ if (segments.some(segment => segment === ".." || segment === "."))
23
+ throw new Error("Relative path segments are not allowed.");
24
+ if (/\/:[A-Za-z]/.test(trimmed))
25
+ throw new Error(`Replace the :placeholders in the path with real values: ${path}`);
26
+ return trimmed.replace(/\/+/g, "/");
27
+ }
28
+ function readMessage(payload) {
29
+ if (typeof payload === "string")
30
+ return payload.trim() || null;
31
+ if (!payload || typeof payload !== "object")
32
+ return null;
33
+ const data = payload;
34
+ for (const value of [data.message, data.msg, data.error, data.error?.message]) {
35
+ if (typeof value === "string" && value.trim())
36
+ return value;
37
+ }
38
+ return null;
39
+ }
40
+ export function unwrapEnvelope(payload) {
41
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
42
+ const keys = Object.keys(payload);
43
+ if (keys.includes("data") && keys.every(key => ["data", "msg", "message", "meta", "pagination"].includes(key))) {
44
+ const record = payload;
45
+ const extra = keys.filter(key => key === "meta" || key === "pagination");
46
+ if (extra.length === 0)
47
+ return record.data;
48
+ return { data: record.data, ...Object.fromEntries(extra.map(key => [key, record[key]])) };
49
+ }
50
+ }
51
+ return payload;
52
+ }
53
+ export class FilessClient {
54
+ options;
55
+ apiUrl;
56
+ fetchImpl;
57
+ constructor(options) {
58
+ this.options = options;
59
+ if (!options.token)
60
+ throw new Error("A Filess MCP token is required (FILESS_TOKEN).");
61
+ this.apiUrl = options.apiUrl.replace(/\/+$/, "");
62
+ this.fetchImpl = options.fetchImpl ?? fetch;
63
+ }
64
+ get panelUrl() {
65
+ return `${this.apiUrl}/p`;
66
+ }
67
+ async request(method, path, options = {}) {
68
+ const normalized = normalizePanelPath(path);
69
+ const url = new URL(`${this.panelUrl}${normalized}`);
70
+ for (const [key, value] of Object.entries(options.query ?? {})) {
71
+ if (value !== undefined && value !== null && value !== "")
72
+ url.searchParams.set(key, String(value));
73
+ }
74
+ const headers = {
75
+ Accept: "application/json",
76
+ Authorization: `Bearer ${this.options.token}`,
77
+ "User-Agent": "filess-mcp/0.1",
78
+ ...options.headers,
79
+ };
80
+ let body;
81
+ if (options.body !== undefined && method !== "GET") {
82
+ headers["Content-Type"] = "application/json";
83
+ body = JSON.stringify(options.body);
84
+ }
85
+ const controller = new AbortController();
86
+ const timer = setTimeout(() => controller.abort(), this.options.timeoutMs ?? 60_000);
87
+ let response;
88
+ try {
89
+ response = await this.fetchImpl(url, { method, headers, body, signal: controller.signal });
90
+ }
91
+ catch (error) {
92
+ const reason = error instanceof Error && error.name === "AbortError" ? "timed out" : error.message;
93
+ throw new FilessApiError(`Could not reach Filess (${reason})`, 0, method, normalized);
94
+ }
95
+ finally {
96
+ clearTimeout(timer);
97
+ }
98
+ const text = await response.text();
99
+ let payload = text;
100
+ if (text && (response.headers.get("content-type") ?? "").includes("json")) {
101
+ try {
102
+ payload = JSON.parse(text);
103
+ }
104
+ catch {
105
+ payload = text;
106
+ }
107
+ }
108
+ if (!response.ok) {
109
+ const message = readMessage(payload) ?? `HTTP ${response.status}`;
110
+ throw new FilessApiError(message, response.status, method, normalized, payload);
111
+ }
112
+ return unwrapEnvelope(payload);
113
+ }
114
+ get(path, query) {
115
+ return this.request("GET", path, { query });
116
+ }
117
+ }
package/dist/http.js ADDED
@@ -0,0 +1,82 @@
1
+ import { createServer } from "node:http";
2
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
+ import { FilessClient } from "./client.js";
4
+ import { createFilessServer } from "./server.js";
5
+ const MAX_BODY_BYTES = 1_000_000;
6
+ function readBody(req) {
7
+ return new Promise((resolve, reject) => {
8
+ let size = 0;
9
+ const chunks = [];
10
+ req.on("data", (chunk) => {
11
+ size += chunk.length;
12
+ if (size > MAX_BODY_BYTES) {
13
+ reject(new Error("Request body too large"));
14
+ req.destroy();
15
+ return;
16
+ }
17
+ chunks.push(chunk);
18
+ });
19
+ req.on("end", () => {
20
+ const text = Buffer.concat(chunks).toString("utf8");
21
+ try {
22
+ resolve(text ? JSON.parse(text) : undefined);
23
+ }
24
+ catch {
25
+ reject(new Error("Invalid JSON body"));
26
+ }
27
+ });
28
+ req.on("error", reject);
29
+ });
30
+ }
31
+ function sendJson(res, status, payload, headers = {}) {
32
+ res.writeHead(status, { "Content-Type": "application/json", ...headers }).end(JSON.stringify(payload));
33
+ }
34
+ export function startHttpServer(options) {
35
+ const httpServer = createServer(async (req, res) => {
36
+ const url = new URL(req.url ?? "/", "http://localhost");
37
+ if (url.pathname === "/health") {
38
+ res.writeHead(200).end("OK");
39
+ return;
40
+ }
41
+ if (url.pathname !== "/mcp") {
42
+ sendJson(res, 404, { error: "Not found. The MCP endpoint is /mcp" });
43
+ return;
44
+ }
45
+ if (req.method !== "POST") {
46
+ sendJson(res, 405, { jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed" }, id: null }, { Allow: "POST" });
47
+ return;
48
+ }
49
+ const auth = req.headers.authorization ?? "";
50
+ const token = auth.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : "";
51
+ if (!token) {
52
+ sendJson(res, 401, { error: "Missing MCP token. Send Authorization: Bearer <token> (create it in the Filess panel)." }, { "WWW-Authenticate": "Bearer" });
53
+ return;
54
+ }
55
+ let body;
56
+ try {
57
+ body = await readBody(req);
58
+ }
59
+ catch (error) {
60
+ sendJson(res, 400, { jsonrpc: "2.0", error: { code: -32700, message: error.message }, id: null });
61
+ return;
62
+ }
63
+ const server = createFilessServer(new FilessClient({ apiUrl: options.apiUrl, token }));
64
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
65
+ res.on("close", () => {
66
+ void transport.close();
67
+ void server.close();
68
+ });
69
+ try {
70
+ await server.connect(transport);
71
+ await transport.handleRequest(req, res, body);
72
+ }
73
+ catch (error) {
74
+ if (!res.headersSent)
75
+ sendJson(res, 500, { jsonrpc: "2.0", error: { code: -32603, message: error.message }, id: null });
76
+ }
77
+ });
78
+ httpServer.listen(options.port, options.host, () => {
79
+ console.error(`Filess MCP (HTTP) listening on http://${options.host}:${options.port}/mcp → ${options.apiUrl}`);
80
+ });
81
+ return httpServer;
82
+ }
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { FilessClient } from "./client.js";
4
+ import { startHttpServer } from "./http.js";
5
+ import { createFilessServer } from "./server.js";
6
+ const DEFAULT_API_URL = "https://backend.filess.io/api";
7
+ function argValue(name) {
8
+ const index = process.argv.indexOf(name);
9
+ return index >= 0 ? process.argv[index + 1] : undefined;
10
+ }
11
+ async function main() {
12
+ const apiUrl = argValue("--api-url") ?? process.env.FILESS_API_URL ?? DEFAULT_API_URL;
13
+ if (process.argv.includes("--http")) {
14
+ const port = Number(argValue("--port") ?? process.env.PORT ?? 8787);
15
+ const host = argValue("--host") ?? process.env.HOST ?? "127.0.0.1";
16
+ startHttpServer({ apiUrl, port, host });
17
+ return;
18
+ }
19
+ const token = process.env.FILESS_TOKEN;
20
+ if (!token) {
21
+ console.error("FILESS_TOKEN is not set. Create an MCP token in the Filess panel (User settings → API tokens → Connect your AI) and pass it as FILESS_TOKEN.");
22
+ process.exit(1);
23
+ }
24
+ const server = createFilessServer(new FilessClient({ apiUrl, token }));
25
+ await server.connect(new StdioServerTransport());
26
+ console.error(`Filess MCP (stdio) connected → ${apiUrl}`);
27
+ }
28
+ main().catch(error => {
29
+ console.error(error);
30
+ process.exit(1);
31
+ });
package/dist/server.js ADDED
@@ -0,0 +1,64 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { catalog } from "./catalog.js";
4
+ import { registerTools } from "./tools.js";
5
+ export const SERVER_VERSION = "0.1.1";
6
+ const INSTRUCTIONS = `You are connected to a Filess account (managed databases, Git hosting, tunnels and device management).
7
+ - Call filess_account_overview first: it returns organizations, namespaces (workspaces) and resource IDs.
8
+ - Dedicated resources are scoped as /org/<organization>/<namespace>/...; shared (free) databases live under /shared and need no organization.
9
+ - Prefer the dedicated tools (hosting_*, database_status, shared_database_create). For anything else, discover the operation with filess_find_endpoints and run it with filess_get (read) or filess_call (write).
10
+ - You act with the user's own permissions. Destructive, billable or service-interrupting actions require the user's explicit consent (confirm=true).
11
+ - Payments cannot be completed by you: when a response contains a Stripe URL, give it to the user.
12
+ - Credential management, MFA, account deletion and MFA-protected device actions (wipe, lock, scripts) are only available in the web panel.`;
13
+ export function createFilessServer(client) {
14
+ const server = new McpServer({ name: "filess", version: SERVER_VERSION }, { instructions: INSTRUCTIONS });
15
+ registerTools(server, client);
16
+ server.registerResource("api-catalog", "filess://catalog", {
17
+ title: "Filess panel API catalogue",
18
+ description: "Every operation of the Filess panel API available to MCP tokens (method, path, required permissions).",
19
+ mimeType: "application/json",
20
+ }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(catalog) }] }));
21
+ server.registerResource("profile", "filess://me", { title: "Current Filess user and organizations", mimeType: "application/json" }, async (uri) => {
22
+ const [user, organizations] = await Promise.all([client.get("/user/my"), client.get("/user/organizations")]);
23
+ return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify({ user, organizations }) }] };
24
+ });
25
+ server.registerPrompt("diagnose-hosting-app", {
26
+ title: "Diagnose a hosting app",
27
+ description: "Find out why a hosting app is down or failing to deploy and propose a fix.",
28
+ argsSchema: { app: z.string().describe("App name or ID (optional context: organization/namespace)") },
29
+ }, ({ app }) => ({
30
+ messages: [{
31
+ role: "user",
32
+ content: {
33
+ type: "text",
34
+ text: `Diagnose the Filess hosting app "${app}". 1) Locate it with filess_account_overview. 2) Read hosting_app_status. 3) If the latest deployment failed, read hosting_logs kind=build (and preflight); if it is running but unhealthy, read hosting_logs kind=runtime (also previous=true). 4) Explain the root cause in plain words and propose concrete fixes (env vars, port, build system, code). Ask before deploying, restarting or changing settings.`,
35
+ },
36
+ }],
37
+ }));
38
+ server.registerPrompt("deploy-from-git", {
39
+ title: "Deploy a Git repository",
40
+ description: "Put a Git repository online with Filess hosting, end to end.",
41
+ argsSchema: { repositoryUrl: z.string() },
42
+ }, ({ repositoryUrl }) => ({
43
+ messages: [{
44
+ role: "user",
45
+ content: {
46
+ type: "text",
47
+ text: `Deploy ${repositoryUrl} on Filess. Find my organization and namespace with filess_account_overview (ask if there are several). Inspect the repository to guess the port and required env vars. Tell me the cost implications and ask for my confirmation, then use hosting_create_app, set env vars with hosting_set_env_vars, start hosting_deploy if needed and follow hosting_logs until it is live. If I need to pay, give me the checkout link. Finish with the public URL.`,
48
+ },
49
+ }],
50
+ }));
51
+ server.registerPrompt("account-health", {
52
+ title: "Account health check",
53
+ description: "Review every service in the account and flag problems, risks and savings.",
54
+ }, () => ({
55
+ messages: [{
56
+ role: "user",
57
+ content: {
58
+ type: "text",
59
+ text: "Review my Filess account with filess_account_overview. For each service, flag anything down, failing, unbacked-up, near limits or unused. Use database_status and hosting_app_status where something looks wrong. Give me a short prioritized list of actions; do not change anything without asking.",
60
+ },
61
+ }],
62
+ }));
63
+ return server;
64
+ }