@backwrite/mcp 0.2.3 → 0.3.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/README.md +24 -40
- package/dist/index.js +893 -160
- package/dist/index.js.map +1 -1
- package/package.json +16 -7
package/dist/index.js
CHANGED
|
@@ -3,38 +3,82 @@
|
|
|
3
3
|
* @backwrite/mcp — Official Model Context Protocol (MCP) server for Backwrite.
|
|
4
4
|
* Connects AI tools (Lovable, Cursor, Claude Code, Windsurf) directly to Backwrite databases.
|
|
5
5
|
*/
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
6
|
+
import readline from "node:readline";
|
|
7
|
+
const VERSION = "0.3.1";
|
|
8
|
+
const PROTOCOL_VERSION = "2026-07-28";
|
|
9
|
+
function assertSqlIdentifier(raw, label = "identifier") {
|
|
10
|
+
const s = String(raw || "").trim();
|
|
11
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(s)) {
|
|
12
|
+
throw new Error(`Security block: invalid SQL ${label} '${s}'. Only alphanumeric and underscore identifiers are permitted.`);
|
|
13
|
+
}
|
|
14
|
+
return `"${s}"`;
|
|
15
|
+
}
|
|
16
|
+
function sanitizeSelectColumns(raw) {
|
|
17
|
+
const s = String(raw || "*").trim();
|
|
18
|
+
if (!s || s === "*")
|
|
19
|
+
return "*";
|
|
20
|
+
const parts = s.split(",").map((p) => p.trim()).filter(Boolean);
|
|
21
|
+
if (parts.length === 0 || parts.length > 64) {
|
|
22
|
+
throw new Error("Security block: select_columns must specify between 1 and 64 valid column identifiers.");
|
|
23
|
+
}
|
|
24
|
+
return parts.map((col) => assertSqlIdentifier(col, "column")).join(", ");
|
|
25
|
+
}
|
|
26
|
+
function sanitizeVectorLiteral(raw) {
|
|
27
|
+
if (!Array.isArray(raw) || raw.length === 0 || raw.length > 4096) {
|
|
28
|
+
throw new Error("Security block: query_vector/embedding must be a non-empty array of finite numbers (max 4096 dimensions).");
|
|
29
|
+
}
|
|
30
|
+
const nums = raw.map((v) => {
|
|
31
|
+
if (typeof v !== "number" || !Number.isFinite(v)) {
|
|
32
|
+
throw new Error("Security block: embedding vector elements must be finite numbers.");
|
|
33
|
+
}
|
|
34
|
+
return String(v);
|
|
35
|
+
});
|
|
36
|
+
return `[${nums.join(",")}]`;
|
|
16
37
|
}
|
|
17
|
-
|
|
18
|
-
|
|
38
|
+
function assertSafeBaseUrl(raw) {
|
|
39
|
+
let u;
|
|
40
|
+
try {
|
|
41
|
+
u = new URL(raw);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new Error(`Invalid BACKWRITE_URL: ${raw}`);
|
|
45
|
+
}
|
|
46
|
+
if (u.username || u.password || /[\r\n\0]/.test(raw)) {
|
|
47
|
+
throw new Error("Security block: invalid characters or embedded credentials in BACKWRITE_URL.");
|
|
48
|
+
}
|
|
49
|
+
const isLocal = u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "::1";
|
|
50
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && isLocal)) {
|
|
51
|
+
throw new Error(`Security block: BACKWRITE_URL must use HTTPS (got ${u.origin}).`);
|
|
52
|
+
}
|
|
53
|
+
return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
|
|
54
|
+
}
|
|
55
|
+
const BACKWRITE_URL = assertSafeBaseUrl(process.env.BACKWRITE_URL ||
|
|
19
56
|
process.env.BACKWRITE_API_URL ||
|
|
20
|
-
"https://api.backwrite.dev")
|
|
57
|
+
"https://api.backwrite.dev");
|
|
21
58
|
const BACKWRITE_API_KEY = process.env.BACKWRITE_SERVICE_KEY ||
|
|
22
59
|
process.env.BACKWRITE_SECRET_KEY ||
|
|
23
60
|
process.env.BACKWRITE_API_KEY ||
|
|
24
|
-
process.env.BW_KEY ||
|
|
25
61
|
"";
|
|
26
62
|
const DEFAULT_PROJECT_ID = process.env.BACKWRITE_PROJECT_ID || "";
|
|
27
63
|
const DEFAULT_BRANCH_ID = process.env.BACKWRITE_BRANCH_ID || "";
|
|
28
|
-
async function apiRequest(path, method = "GET", body) {
|
|
64
|
+
async function apiRequest(path, method = "GET", body, ctx) {
|
|
65
|
+
if (!path.startsWith("/") || path.startsWith("//") || path.includes("..") || /[\r\n\0]/.test(path)) {
|
|
66
|
+
throw new Error(`Security block: invalid API path '${path}'.`);
|
|
67
|
+
}
|
|
29
68
|
const url = `${BACKWRITE_URL}${path}`;
|
|
30
|
-
const
|
|
31
|
-
|
|
69
|
+
const activeKey = ctx?.requireExplicitKey ? (ctx.apiKey || "") : (ctx?.apiKey || BACKWRITE_API_KEY);
|
|
70
|
+
if (ctx?.requireExplicitKey && !activeKey) {
|
|
71
|
+
throw new Error("Authentication required: provide Authorization: Bearer <token> or apikey header on HTTP MCP requests.");
|
|
72
|
+
}
|
|
73
|
+
if (activeKey && /[\r\n\0]/.test(activeKey)) {
|
|
74
|
+
throw new Error("Security block: malformed authorization token.");
|
|
75
|
+
}
|
|
32
76
|
const headers = {
|
|
33
77
|
Accept: "application/json",
|
|
34
78
|
"Content-Type": "application/json",
|
|
35
79
|
};
|
|
36
80
|
if (method.toUpperCase() !== "GET" && method.toUpperCase() !== "HEAD") {
|
|
37
|
-
headers["Idempotency-Key"] = `
|
|
81
|
+
headers["Idempotency-Key"] = `backwrite_mcp_${crypto.randomUUID()}`;
|
|
38
82
|
}
|
|
39
83
|
if (activeKey) {
|
|
40
84
|
if (activeKey.startsWith("bwk_") || activeKey.startsWith("bw_")) {
|
|
@@ -46,6 +90,7 @@ async function apiRequest(path, method = "GET", body) {
|
|
|
46
90
|
method,
|
|
47
91
|
headers,
|
|
48
92
|
body: body ? JSON.stringify(body) : undefined,
|
|
93
|
+
signal: AbortSignal.timeout(30000),
|
|
49
94
|
});
|
|
50
95
|
const json = await response.json().catch(() => ({}));
|
|
51
96
|
if (!response.ok) {
|
|
@@ -54,15 +99,15 @@ async function apiRequest(path, method = "GET", body) {
|
|
|
54
99
|
}
|
|
55
100
|
return json.data ?? json;
|
|
56
101
|
}
|
|
57
|
-
function resolveProject(projectId) {
|
|
58
|
-
const p = projectId || DEFAULT_PROJECT_ID;
|
|
102
|
+
function resolveProject(projectId, ctx) {
|
|
103
|
+
const p = projectId || ctx?.projectId || DEFAULT_PROJECT_ID;
|
|
59
104
|
if (!p) {
|
|
60
105
|
throw new Error("No project_id specified and BACKWRITE_PROJECT_ID environment variable is not set.");
|
|
61
106
|
}
|
|
62
107
|
return p;
|
|
63
108
|
}
|
|
64
|
-
function resolveBranch(branchId) {
|
|
65
|
-
return branchId || DEFAULT_BRANCH_ID || undefined;
|
|
109
|
+
function resolveBranch(branchId, ctx) {
|
|
110
|
+
return branchId || ctx?.branchId || DEFAULT_BRANCH_ID || undefined;
|
|
66
111
|
}
|
|
67
112
|
// ── Codegen Utilities ────────────────────────────────────────────────────────
|
|
68
113
|
function pgToTs(ty, nullable) {
|
|
@@ -602,52 +647,420 @@ const TOOLS = [
|
|
|
602
647
|
required: ["organization_id", "name"],
|
|
603
648
|
},
|
|
604
649
|
},
|
|
650
|
+
// ── Parallel Agent Sandboxes, Lockfiles, Streaming, Elicitation & Plugins 1.0.0 ──
|
|
651
|
+
{
|
|
652
|
+
name: "backwrite_spawn_worktree",
|
|
653
|
+
description: "Provision an isolated Agent Sandbox combining a disposable Copy-on-Write PostgreSQL 18 branch with Git worktree setup instructions and scoped .env coordinates so parallel AI agents never share state or fight over git locks.",
|
|
654
|
+
inputSchema: {
|
|
655
|
+
type: "object",
|
|
656
|
+
properties: {
|
|
657
|
+
task_name: { type: "string", description: "Short task slug (e.g. 'auth-tests', 'billing-migration')." },
|
|
658
|
+
project_id: { type: "string", description: "Backwrite Project ID (defaults to BACKWRITE_PROJECT_ID)." },
|
|
659
|
+
base_branch: { type: "string", description: "Git base branch (default: main)." },
|
|
660
|
+
mode: { type: "string", enum: ["schema-only", "full-copy"], description: "CoW branch copy mode (default: schema-only)." },
|
|
661
|
+
},
|
|
662
|
+
required: ["task_name"],
|
|
663
|
+
},
|
|
664
|
+
},
|
|
665
|
+
{
|
|
666
|
+
name: "backwrite_sync_schema",
|
|
667
|
+
description: "Apply local SQL, Prisma, or Drizzle migration statements safely to an isolated non-production PostgreSQL 18 branch and automatically run 5-Engine Advisors to catch missing indexes or RLS gaps before merging.",
|
|
668
|
+
inputSchema: {
|
|
669
|
+
type: "object",
|
|
670
|
+
properties: {
|
|
671
|
+
sql: { type: "string", description: "DDL / migration SQL to apply to the disposable branch." },
|
|
672
|
+
project_id: { type: "string", description: "Backwrite Project ID." },
|
|
673
|
+
branch_id: { type: "string", description: "Target non-production branch ID." },
|
|
674
|
+
run_advisors: { type: "boolean", description: "Run 5-Engine Advisors scan after applying DDL (default: true)." },
|
|
675
|
+
},
|
|
676
|
+
required: ["sql", "branch_id"],
|
|
677
|
+
},
|
|
678
|
+
},
|
|
679
|
+
{
|
|
680
|
+
name: "backwrite_workspace_lock",
|
|
681
|
+
description: "Distributed Agent Lockfile protocol backed by Valkey KV. Acquire, inspect, or release exclusive locks on repository file paths so parallel worktree agents flag contested files instead of causing merge conflicts.",
|
|
682
|
+
inputSchema: {
|
|
683
|
+
type: "object",
|
|
684
|
+
properties: {
|
|
685
|
+
action: { type: "string", enum: ["acquire", "release", "check"], description: "Lock operation." },
|
|
686
|
+
file_path: { type: "string", description: "Repository-relative file path (e.g. 'src/router.ts')." },
|
|
687
|
+
agent_id: { type: "string", description: "Unique agent or worktree identifier." },
|
|
688
|
+
branch_id: { type: "string", description: "Backwrite branch ID hosting the Valkey cache." },
|
|
689
|
+
ttl_seconds: { type: "number", description: "Lock TTL in seconds (default: 600)." },
|
|
690
|
+
},
|
|
691
|
+
required: ["action", "file_path", "branch_id"],
|
|
692
|
+
},
|
|
693
|
+
},
|
|
694
|
+
{
|
|
695
|
+
name: "backwrite_agent_emit_event",
|
|
696
|
+
description: "Stream structured agent telemetry (thoughts, tool calls, test results, status transitions) over Backwrite Realtime / NATS JetStream so terminal dashboards (`backwrite top`) and UI consoles can observe parallel agents live.",
|
|
697
|
+
inputSchema: {
|
|
698
|
+
type: "object",
|
|
699
|
+
properties: {
|
|
700
|
+
agent_id: { type: "string", description: "Agent or worktree ID." },
|
|
701
|
+
event: { type: "string", description: "Event type (e.g. 'status', 'thought', 'tool_call', 'test_pass', 'error')." },
|
|
702
|
+
message: { type: "string", description: "Human-readable status message." },
|
|
703
|
+
branch_id: { type: "string", description: "Backwrite branch ID." },
|
|
704
|
+
metadata: { type: "object", description: "Optional structured payload." },
|
|
705
|
+
},
|
|
706
|
+
required: ["agent_id", "event", "message", "branch_id"],
|
|
707
|
+
},
|
|
708
|
+
},
|
|
709
|
+
{
|
|
710
|
+
name: "backwrite_elicit_context",
|
|
711
|
+
description: "Trigger an MCP multi-round Elicitation request when an autonomous agent in an isolated worktree hits an ambiguity (missing env var, destructive DDL confirmation, or business rule question), pausing safely until the operator responds.",
|
|
712
|
+
inputSchema: {
|
|
713
|
+
type: "object",
|
|
714
|
+
properties: {
|
|
715
|
+
question: { type: "string", description: "Clear question for the human operator." },
|
|
716
|
+
reason: { type: "string", description: "Why the agent paused (e.g. 'missing_env_var', 'schema_approval', 'contested_file')." },
|
|
717
|
+
requested_fields: {
|
|
718
|
+
type: "array",
|
|
719
|
+
items: { type: "string" },
|
|
720
|
+
description: "Specific fields or choices required from the operator.",
|
|
721
|
+
},
|
|
722
|
+
agent_id: { type: "string", description: "Optional agent ID." },
|
|
723
|
+
branch_id: { type: "string", description: "Optional branch ID to broadcast the elicitation alert." },
|
|
724
|
+
},
|
|
725
|
+
required: ["question", "reason"],
|
|
726
|
+
},
|
|
727
|
+
},
|
|
728
|
+
{
|
|
729
|
+
name: "backwrite_export_agent_plugin",
|
|
730
|
+
description: "Generate a complete Agent Plugins 1.0.0 directory payload (`plugin.json`, `mcp.json`, live `schema.json`, and `skills/*/SKILL.md` standard operating procedures) tailored to the active Backwrite project so Claude Code, Cursor, Copilot, and Gemini CLI instantly understand your architecture.",
|
|
731
|
+
inputSchema: {
|
|
732
|
+
type: "object",
|
|
733
|
+
properties: {
|
|
734
|
+
name: { type: "string", description: "Plugin package name (e.g. 'my-saas-backwrite-plugin')." },
|
|
735
|
+
project_id: { type: "string", description: "Backwrite Project ID." },
|
|
736
|
+
branch_id: { type: "string", description: "Optional branch ID." },
|
|
737
|
+
include_schema: { type: "boolean", description: "Embed live relational schema snapshot (default: true)." },
|
|
738
|
+
skills: {
|
|
739
|
+
type: "array",
|
|
740
|
+
items: { type: "string" },
|
|
741
|
+
description: "Skills to generate (e.g. ['backwrite-migrations', 'backwrite-deploy', 'database-troubleshooting', 'api-generation']).",
|
|
742
|
+
},
|
|
743
|
+
},
|
|
744
|
+
required: ["name"],
|
|
745
|
+
},
|
|
746
|
+
},
|
|
747
|
+
{
|
|
748
|
+
name: "backwrite_list_snapshots",
|
|
749
|
+
description: "List Point-in-Time Recovery (PITR) and branch snapshots for a Backwrite branch.",
|
|
750
|
+
inputSchema: {
|
|
751
|
+
type: "object",
|
|
752
|
+
properties: {
|
|
753
|
+
branch_id: { type: "string", description: "Branch ID." },
|
|
754
|
+
},
|
|
755
|
+
required: ["branch_id"],
|
|
756
|
+
},
|
|
757
|
+
},
|
|
758
|
+
{
|
|
759
|
+
name: "backwrite_create_snapshot",
|
|
760
|
+
description: "Take a verified point-in-time snapshot of a Backwrite PostgreSQL 18 branch before running risky migrations.",
|
|
761
|
+
inputSchema: {
|
|
762
|
+
type: "object",
|
|
763
|
+
properties: {
|
|
764
|
+
branch_id: { type: "string", description: "Branch ID." },
|
|
765
|
+
label: { type: "string", description: "Human-readable snapshot label." },
|
|
766
|
+
},
|
|
767
|
+
required: ["branch_id"],
|
|
768
|
+
},
|
|
769
|
+
},
|
|
770
|
+
{
|
|
771
|
+
name: "backwrite_cache_set",
|
|
772
|
+
description: "Store a key/value entry with optional TTL in a branch's Valkey 8 in-memory cache.",
|
|
773
|
+
inputSchema: {
|
|
774
|
+
type: "object",
|
|
775
|
+
properties: {
|
|
776
|
+
branch_id: { type: "string", description: "Branch ID." },
|
|
777
|
+
key: { type: "string", description: "Cache key." },
|
|
778
|
+
value: { type: "string", description: "String or JSON-serialized value." },
|
|
779
|
+
ttl_seconds: { type: "number", description: "Optional TTL in seconds (default: 300)." },
|
|
780
|
+
},
|
|
781
|
+
required: ["branch_id", "key", "value"],
|
|
782
|
+
},
|
|
783
|
+
},
|
|
784
|
+
];
|
|
785
|
+
const RESOURCES = [
|
|
786
|
+
{
|
|
787
|
+
uri: "backwrite://schema/current",
|
|
788
|
+
name: "Active PostgreSQL 18 Branch Schema",
|
|
789
|
+
description: "Live tables, columns, primary/foreign keys, indexes, enums, and Row Level Security policies of the active branch.",
|
|
790
|
+
mimeType: "application/json",
|
|
791
|
+
},
|
|
792
|
+
{
|
|
793
|
+
uri: "backwrite://architecture/topology",
|
|
794
|
+
name: "Backwrite Project Architecture & Topology",
|
|
795
|
+
description: "Active project branches, direct :5432 and PgBouncer :6543 endpoints, engines, and isolation metadata.",
|
|
796
|
+
mimeType: "application/json",
|
|
797
|
+
},
|
|
798
|
+
{
|
|
799
|
+
uri: "backwrite://advisors/findings",
|
|
800
|
+
name: "5-Engine Backend Advisor Findings",
|
|
801
|
+
description: "Live security, RLS coverage, index hygiene, and query performance diagnostics for the active project.",
|
|
802
|
+
mimeType: "application/json",
|
|
803
|
+
},
|
|
804
|
+
];
|
|
805
|
+
function slugifyTask(task) {
|
|
806
|
+
return (String(task || "agent-task")
|
|
807
|
+
.toLowerCase()
|
|
808
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
809
|
+
.replace(/^-+|-+$/g, "")
|
|
810
|
+
.slice(0, 36) || "agent-task");
|
|
811
|
+
}
|
|
812
|
+
function buildAgentPluginFiles(name, projectId, branchId, skills, schemaSnapshot) {
|
|
813
|
+
const safeName = slugifyTask(name);
|
|
814
|
+
const selectedSkills = skills.length > 0 ? skills : ["backwrite-migrations", "backwrite-deploy", "database-troubleshooting", "api-generation"];
|
|
815
|
+
const files = {
|
|
816
|
+
"plugin.json": JSON.stringify({
|
|
817
|
+
schemaVersion: "1.0.0",
|
|
818
|
+
name: safeName,
|
|
819
|
+
version: "1.0.0",
|
|
820
|
+
description: `Backwrite Agent Plugin for ${name} — isolated PostgreSQL 18 CoW branching, 36 MCP tools, and standard operating procedures.`,
|
|
821
|
+
mcpConfig: "./mcp.json",
|
|
822
|
+
skillsDir: "./skills",
|
|
823
|
+
backwrite: {
|
|
824
|
+
projectId: projectId || "<YOUR_PROJECT_ID>",
|
|
825
|
+
defaultBranchId: branchId || "<YOUR_BRANCH_ID>",
|
|
826
|
+
},
|
|
827
|
+
}, null, 2),
|
|
828
|
+
"mcp.json": JSON.stringify({
|
|
829
|
+
mcpServers: {
|
|
830
|
+
backwrite: {
|
|
831
|
+
command: "npx",
|
|
832
|
+
args: ["-y", `@backwrite/mcp@${VERSION}`],
|
|
833
|
+
env: {
|
|
834
|
+
BACKWRITE_URL: "https://api.backwrite.dev",
|
|
835
|
+
BACKWRITE_SERVICE_KEY: "${BACKWRITE_SERVICE_KEY}",
|
|
836
|
+
BACKWRITE_PROJECT_ID: "${BACKWRITE_PROJECT_ID}",
|
|
837
|
+
BACKWRITE_BRANCH_ID: "${BACKWRITE_BRANCH_ID}",
|
|
838
|
+
},
|
|
839
|
+
},
|
|
840
|
+
},
|
|
841
|
+
}, null, 2),
|
|
842
|
+
};
|
|
843
|
+
if (schemaSnapshot !== undefined) {
|
|
844
|
+
files["schema.json"] = JSON.stringify(schemaSnapshot, null, 2);
|
|
845
|
+
}
|
|
846
|
+
const skillBodies = {
|
|
847
|
+
"backwrite-migrations": `---
|
|
848
|
+
name: backwrite-migrations
|
|
849
|
+
description: Safe PostgreSQL 18 schema migration SOP using isolated Backwrite CoW branches and Advisors.
|
|
850
|
+
---
|
|
851
|
+
|
|
852
|
+
# Backwrite Migration Standard Operating Procedure
|
|
853
|
+
|
|
854
|
+
1. **Never run untested DDL on production.** Always call \`backwrite_spawn_worktree\` first to provision an isolated PostgreSQL 18 Copy-on-Write branch.
|
|
855
|
+
2. Read the live schema via MCP Resource \`backwrite://schema/current\` or \`backwrite_get_database_schema\`.
|
|
856
|
+
3. Acquire a lock on migration/schema files via \`backwrite_workspace_lock(action="acquire")\` before editing.
|
|
857
|
+
4. Apply DDL to the disposable branch with \`backwrite_sync_schema(run_advisors=true)\` and resolve any missing-index or RLS findings.
|
|
858
|
+
5. Take a snapshot (\`backwrite_create_snapshot\`) before promoting, then hand off for human review via \`backwrite review <agent-id>\`.
|
|
859
|
+
`,
|
|
860
|
+
"backwrite-deploy": `---
|
|
861
|
+
name: backwrite-deploy
|
|
862
|
+
description: Pre-deploy verification checklist for Backwrite projects, PgBouncer :6543 pooling, and PITR snapshots.
|
|
863
|
+
---
|
|
864
|
+
|
|
865
|
+
# Backwrite Deploy Verification SOP
|
|
866
|
+
|
|
867
|
+
1. Inspect \`backwrite://architecture/topology\` and \`backwrite://advisors/findings\`.
|
|
868
|
+
2. Confirm zero critical Advisor findings (RLS enabled on tenant tables, no missing FK indexes).
|
|
869
|
+
3. Ensure application connections use PgBouncer \`pooler.backwrite.dev:6543?sslmode=require\` and migrations use direct \`db.backwrite.dev:5432?sslmode=require\`.
|
|
870
|
+
4. Trigger \`backwrite_create_snapshot\` on the target branch before release.
|
|
871
|
+
`,
|
|
872
|
+
"database-troubleshooting": `---
|
|
873
|
+
name: database-troubleshooting
|
|
874
|
+
description: Diagnose slow queries, lock contention, and schema drift on Backwrite PostgreSQL 18 branches.
|
|
875
|
+
---
|
|
876
|
+
|
|
877
|
+
# Backwrite Database Troubleshooting SOP
|
|
878
|
+
|
|
879
|
+
1. Inspect \`backwrite://advisors/findings\` and \`backwrite_list_advisors\`.
|
|
880
|
+
2. Run \`EXPLAIN (ANALYZE, BUFFERS)\` on a disposable Copy-on-Write branch via \`backwrite_execute_sql\`.
|
|
881
|
+
3. Never mutate production directly while diagnosing; fork a branch with \`backwrite_spawn_worktree\` and reproduce safely.
|
|
882
|
+
`,
|
|
883
|
+
"api-generation": `---
|
|
884
|
+
name: api-generation
|
|
885
|
+
description: Generate strictly typed TypeScript, Drizzle, or Prisma models from the live Backwrite PostgreSQL 18 schema.
|
|
886
|
+
---
|
|
887
|
+
|
|
888
|
+
# Backwrite API & Type Generation SOP
|
|
889
|
+
|
|
890
|
+
1. Read \`backwrite://schema/current\` or call \`backwrite_generate_types(format="typescript"|"drizzle"|"prisma")\`.
|
|
891
|
+
2. Keep server credentials strictly in environment variables (\`BACKWRITE_SERVICE_KEY\`, \`BACKWRITE_PROJECT_ID\`, \`BACKWRITE_BRANCH_ID\`) — never hardcode live IDs in source files.
|
|
892
|
+
3. Verify generated queries against an isolated preview branch before submitting a PR.
|
|
893
|
+
`,
|
|
894
|
+
};
|
|
895
|
+
for (const skill of selectedSkills) {
|
|
896
|
+
const safeSkill = slugifyTask(skill);
|
|
897
|
+
files[`skills/${safeSkill}/SKILL.md`] =
|
|
898
|
+
skillBodies[safeSkill] ||
|
|
899
|
+
`---\nname: ${safeSkill}\ndescription: Custom Backwrite Agent Skill (${safeSkill}).\n---\n\n# ${safeSkill}\n\nAlways fork an isolated PostgreSQL 18 Copy-on-Write branch via \`backwrite_spawn_worktree\` before modifying database state, validate with \`backwrite_sync_schema\`, and request operator input via \`backwrite_elicit_context\` if requirements are ambiguous.\n`;
|
|
900
|
+
}
|
|
901
|
+
return files;
|
|
902
|
+
}
|
|
903
|
+
const PROMPTS = [
|
|
904
|
+
{
|
|
905
|
+
name: "backwrite-safe-migration",
|
|
906
|
+
description: "Safe PostgreSQL 18 schema migration workflow using an isolated CoW branch, Valkey file locks, and 5-Engine Advisors.",
|
|
907
|
+
arguments: [{ name: "change_summary", description: "Describe the schema change you want to apply", required: true }],
|
|
908
|
+
},
|
|
909
|
+
{
|
|
910
|
+
name: "backwrite-debug-slow-query",
|
|
911
|
+
description: "Fork an isolated Copy-on-Write branch to run EXPLAIN (ANALYZE, BUFFERS) and Advisor checks without impacting production.",
|
|
912
|
+
arguments: [{ name: "sql", description: "Slow SQL query to diagnose", required: true }],
|
|
913
|
+
},
|
|
914
|
+
{
|
|
915
|
+
name: "backwrite-rls-audit",
|
|
916
|
+
description: "Inspect every table's Row Level Security policies and Advisors security findings on the active branch.",
|
|
917
|
+
arguments: [],
|
|
918
|
+
},
|
|
919
|
+
{
|
|
920
|
+
name: "backwrite-agent-sandbox",
|
|
921
|
+
description: "Provision a parallel Agent Workspace (Git worktree + disposable Postgres 18 branch) with contested-file lockfiles.",
|
|
922
|
+
arguments: [{ name: "task_name", description: "Short task slug for the sandbox", required: true }],
|
|
923
|
+
},
|
|
605
924
|
];
|
|
606
|
-
|
|
925
|
+
function getPromptMessages(name, args = {}) {
|
|
926
|
+
if (name === "backwrite-safe-migration") {
|
|
927
|
+
return {
|
|
928
|
+
description: "Safe PostgreSQL 18 CoW migration workflow",
|
|
929
|
+
messages: [
|
|
930
|
+
{
|
|
931
|
+
role: "user",
|
|
932
|
+
content: {
|
|
933
|
+
type: "text",
|
|
934
|
+
text: `Apply the following schema change safely on Backwrite: ${args.change_summary || "(describe change)"}.\n1. Call backwrite_spawn_worktree first — never modify production directly.\n2. Read backwrite://schema/current and acquire file locks with backwrite_workspace_lock.\n3. Apply DDL with backwrite_sync_schema(run_advisors=true) and resolve all security/index findings.\n4. Take a snapshot with backwrite_create_snapshot and report the backwrite review command.`,
|
|
935
|
+
},
|
|
936
|
+
},
|
|
937
|
+
],
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
if (name === "backwrite-debug-slow-query") {
|
|
941
|
+
return {
|
|
942
|
+
description: "Isolated slow query analysis on a disposable CoW branch",
|
|
943
|
+
messages: [
|
|
944
|
+
{
|
|
945
|
+
role: "user",
|
|
946
|
+
content: {
|
|
947
|
+
type: "text",
|
|
948
|
+
text: `Diagnose this slow PostgreSQL 18 query safely without touching production: ${args.sql || "(query)"}.\n1. Fork an isolated branch via backwrite_spawn_worktree.\n2. Inspect backwrite://advisors/findings and run EXPLAIN (ANALYZE, BUFFERS) on the disposable branch.\n3. Propose exact index DDL and verify the improved plan before handing off.`,
|
|
949
|
+
},
|
|
950
|
+
},
|
|
951
|
+
],
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
if (name === "backwrite-rls-audit") {
|
|
955
|
+
return {
|
|
956
|
+
description: "Full Row Level Security & Advisors audit",
|
|
957
|
+
messages: [
|
|
958
|
+
{
|
|
959
|
+
role: "user",
|
|
960
|
+
content: {
|
|
961
|
+
type: "text",
|
|
962
|
+
text: "Read backwrite://schema/current and backwrite://advisors/findings. Identify any tables missing RLS or permissive policies, and propose least-privilege CREATE POLICY statements tested on an isolated CoW branch.",
|
|
963
|
+
},
|
|
964
|
+
},
|
|
965
|
+
],
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
if (name === "backwrite-agent-sandbox") {
|
|
969
|
+
return {
|
|
970
|
+
description: "Parallel Agent Sandbox provisioning workflow",
|
|
971
|
+
messages: [
|
|
972
|
+
{
|
|
973
|
+
role: "user",
|
|
974
|
+
content: {
|
|
975
|
+
type: "text",
|
|
976
|
+
text: `Provision a zero-conflict Agent Sandbox for task '${args.task_name || "agent-task"}' via backwrite_spawn_worktree, emit live progress via backwrite_agent_emit_event, lock edited files via backwrite_workspace_lock, and use backwrite_elicit_context if any requirement is ambiguous.`,
|
|
977
|
+
},
|
|
978
|
+
},
|
|
979
|
+
],
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
throw new Error(`Unknown prompt: ${name}`);
|
|
983
|
+
}
|
|
984
|
+
// ── Native Zero-Dependency MCP Server (2026-07-28 Spec) ─────────────────────
|
|
607
985
|
async function main() {
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
986
|
+
async function readResource(uri, ctx) {
|
|
987
|
+
const project = resolveProject(undefined, ctx);
|
|
988
|
+
const branch = resolveBranch(undefined, ctx);
|
|
989
|
+
if (uri === "backwrite://schema/current") {
|
|
990
|
+
const path = branch
|
|
991
|
+
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
|
|
992
|
+
: `/v1/projects/${encodeURIComponent(project)}/schema`;
|
|
993
|
+
const data = await apiRequest(path, "GET", undefined, ctx);
|
|
994
|
+
return {
|
|
995
|
+
contents: [{ uri, mimeType: "application/json", text: JSON.stringify(data, null, 2) }],
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
if (uri === "backwrite://architecture/topology") {
|
|
999
|
+
const [branches, overview] = await Promise.all([
|
|
1000
|
+
apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches`, "GET", undefined, ctx).catch(() => ({ branches: [] })),
|
|
1001
|
+
apiRequest(`/v1/projects/${encodeURIComponent(project)}/overview`, "GET", undefined, ctx).catch(() => ({})),
|
|
1002
|
+
]);
|
|
1003
|
+
return {
|
|
1004
|
+
contents: [
|
|
1005
|
+
{
|
|
1006
|
+
uri,
|
|
1007
|
+
mimeType: "application/json",
|
|
1008
|
+
text: JSON.stringify({
|
|
1009
|
+
project_id: project,
|
|
1010
|
+
active_branch_id: branch || null,
|
|
1011
|
+
endpoints: {
|
|
1012
|
+
direct_postgres: "db.backwrite.dev:5432?sslmode=require",
|
|
1013
|
+
pgbouncer_pooler: "pooler.backwrite.dev:6543?sslmode=require",
|
|
1014
|
+
api_gateway: BACKWRITE_URL,
|
|
1015
|
+
},
|
|
1016
|
+
branches,
|
|
1017
|
+
overview,
|
|
1018
|
+
}, null, 2),
|
|
1019
|
+
},
|
|
1020
|
+
],
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
if (uri === "backwrite://advisors/findings") {
|
|
1024
|
+
const data = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/advisors`, "GET", undefined, ctx);
|
|
1025
|
+
return {
|
|
1026
|
+
contents: [{ uri, mimeType: "application/json", text: JSON.stringify(data, null, 2) }],
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
throw new Error(`Unknown Backwrite MCP resource URI: ${uri}`);
|
|
1030
|
+
}
|
|
1031
|
+
async function executeTool(name, a, ctx) {
|
|
1032
|
+
const req = (path, method = "GET", body) => apiRequest(path, method, body, ctx);
|
|
620
1033
|
try {
|
|
621
1034
|
switch (name) {
|
|
622
1035
|
case "backwrite_execute_sql": {
|
|
623
|
-
const project = resolveProject(a.project_id);
|
|
624
|
-
const branch = resolveBranch(a.branch_id);
|
|
1036
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1037
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
625
1038
|
const path = branch
|
|
626
1039
|
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`
|
|
627
1040
|
: `/v1/projects/${encodeURIComponent(project)}/query`;
|
|
628
|
-
const res = await
|
|
1041
|
+
const res = await req(path, "POST", { sql: a.sql, view: "raw" });
|
|
629
1042
|
return {
|
|
630
1043
|
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
631
1044
|
};
|
|
632
1045
|
}
|
|
633
1046
|
case "backwrite_get_database_schema": {
|
|
634
|
-
const project = resolveProject(a.project_id);
|
|
635
|
-
const branch = resolveBranch(a.branch_id);
|
|
1047
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1048
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
636
1049
|
const path = branch
|
|
637
1050
|
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
|
|
638
1051
|
: `/v1/projects/${encodeURIComponent(project)}/schema`;
|
|
639
|
-
const res = await
|
|
1052
|
+
const res = await req(path, "GET");
|
|
640
1053
|
return {
|
|
641
1054
|
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
642
1055
|
};
|
|
643
1056
|
}
|
|
644
1057
|
case "backwrite_list_tables": {
|
|
645
|
-
const project = resolveProject(a.project_id);
|
|
646
|
-
const branch = resolveBranch(a.branch_id);
|
|
1058
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1059
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
647
1060
|
const path = branch
|
|
648
1061
|
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
|
|
649
1062
|
: `/v1/projects/${encodeURIComponent(project)}/schema`;
|
|
650
|
-
const res = await
|
|
1063
|
+
const res = await req(path, "GET");
|
|
651
1064
|
const tables = (res.tables || []).map((t) => ({
|
|
652
1065
|
schema: t.schema,
|
|
653
1066
|
name: t.name,
|
|
@@ -659,12 +1072,12 @@ async function main() {
|
|
|
659
1072
|
};
|
|
660
1073
|
}
|
|
661
1074
|
case "backwrite_describe_table": {
|
|
662
|
-
const project = resolveProject(a.project_id);
|
|
663
|
-
const branch = resolveBranch(a.branch_id);
|
|
1075
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1076
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
664
1077
|
const path = branch
|
|
665
1078
|
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
|
|
666
1079
|
: `/v1/projects/${encodeURIComponent(project)}/schema`;
|
|
667
|
-
const res = await
|
|
1080
|
+
const res = await req(path, "GET");
|
|
668
1081
|
const targetSchema = a.schema_name || "public";
|
|
669
1082
|
const table = (res.tables || []).find((t) => t.name === a.table_name &&
|
|
670
1083
|
(t.schema === targetSchema || (!a.schema_name && t.schema === "public")));
|
|
@@ -676,15 +1089,15 @@ async function main() {
|
|
|
676
1089
|
};
|
|
677
1090
|
}
|
|
678
1091
|
case "backwrite_list_branches": {
|
|
679
|
-
const project = resolveProject(a.project_id);
|
|
680
|
-
const res = await
|
|
1092
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1093
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/branches`, "GET");
|
|
681
1094
|
return {
|
|
682
1095
|
content: [{ type: "text", text: JSON.stringify(res.branches ?? res, null, 2) }],
|
|
683
1096
|
};
|
|
684
1097
|
}
|
|
685
1098
|
case "backwrite_create_branch": {
|
|
686
|
-
const project = resolveProject(a.project_id);
|
|
687
|
-
const res = await
|
|
1099
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1100
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/branches`, "POST", {
|
|
688
1101
|
name: a.name,
|
|
689
1102
|
branch_type: a.branch_type || "preview",
|
|
690
1103
|
source_branch_id: a.source_branch_id,
|
|
@@ -694,31 +1107,33 @@ async function main() {
|
|
|
694
1107
|
};
|
|
695
1108
|
}
|
|
696
1109
|
case "backwrite_delete_branch": {
|
|
697
|
-
const res = await
|
|
1110
|
+
const res = await req(`/v1/branches/${encodeURIComponent(a.branch_id)}`, "DELETE");
|
|
698
1111
|
return {
|
|
699
1112
|
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
700
1113
|
};
|
|
701
1114
|
}
|
|
702
1115
|
case "backwrite_vector_search": {
|
|
703
|
-
const project = resolveProject(a.project_id);
|
|
704
|
-
const branch = resolveBranch(a.branch_id);
|
|
705
|
-
const cols = a.select_columns
|
|
706
|
-
const limit = typeof a.limit === "number"
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
const
|
|
710
|
-
const
|
|
1116
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1117
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
1118
|
+
const cols = sanitizeSelectColumns(a.select_columns);
|
|
1119
|
+
const limit = typeof a.limit === "number" && Number.isFinite(a.limit)
|
|
1120
|
+
? Math.max(1, Math.min(Math.floor(a.limit), 100))
|
|
1121
|
+
: 10;
|
|
1122
|
+
const vectorStr = sanitizeVectorLiteral(a.query_vector);
|
|
1123
|
+
const safeTable = assertSqlIdentifier(a.table_name, "table_name");
|
|
1124
|
+
const safeCol = assertSqlIdentifier(a.embedding_column, "embedding_column");
|
|
1125
|
+
const sql = `SELECT ${cols}, (${safeCol} <=> '${vectorStr}') AS distance FROM ${safeTable} ORDER BY distance ASC LIMIT ${limit};`;
|
|
711
1126
|
const path = branch
|
|
712
1127
|
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`
|
|
713
1128
|
: `/v1/projects/${encodeURIComponent(project)}/query`;
|
|
714
|
-
const res = await
|
|
1129
|
+
const res = await req(path, "POST", { sql, view: "raw" });
|
|
715
1130
|
return {
|
|
716
1131
|
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
717
1132
|
};
|
|
718
1133
|
}
|
|
719
1134
|
case "backwrite_store_agent_memory": {
|
|
720
|
-
const project = resolveProject(a.project_id);
|
|
721
|
-
const branch = resolveBranch(a.branch_id);
|
|
1135
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1136
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
722
1137
|
const path = branch
|
|
723
1138
|
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`
|
|
724
1139
|
: `/v1/projects/${encodeURIComponent(project)}/query`;
|
|
@@ -735,39 +1150,39 @@ async function main() {
|
|
|
735
1150
|
);
|
|
736
1151
|
CREATE INDEX IF NOT EXISTS idx_agent_memories_key ON agent_memories(memory_key);
|
|
737
1152
|
`;
|
|
738
|
-
await
|
|
1153
|
+
await req(path, "POST", { sql: ensureSql, view: "raw" }).catch(() => { });
|
|
739
1154
|
const metaJson = JSON.stringify(a.metadata || {}).replace(/'/g, "''");
|
|
740
1155
|
const contentEsc = String(a.content).replace(/'/g, "''");
|
|
741
1156
|
const keyEsc = String(a.memory_key).replace(/'/g, "''");
|
|
742
|
-
const embeddingVal = a.embedding
|
|
1157
|
+
const embeddingVal = a.embedding ? `'${sanitizeVectorLiteral(a.embedding)}'` : "NULL";
|
|
743
1158
|
const insertSql = `
|
|
744
1159
|
INSERT INTO agent_memories (memory_key, content, metadata, embedding)
|
|
745
1160
|
VALUES ('${keyEsc}', '${contentEsc}', '${metaJson}'::jsonb, ${embeddingVal})
|
|
746
1161
|
RETURNING id, memory_key, created_at;
|
|
747
1162
|
`;
|
|
748
|
-
const res = await
|
|
1163
|
+
const res = await req(path, "POST", { sql: insertSql, view: "raw" });
|
|
749
1164
|
return {
|
|
750
1165
|
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
751
1166
|
};
|
|
752
1167
|
}
|
|
753
1168
|
case "backwrite_get_connection_string": {
|
|
754
|
-
const project = resolveProject(a.project_id);
|
|
755
|
-
const branch = resolveBranch(a.branch_id);
|
|
1169
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1170
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
756
1171
|
const path = branch
|
|
757
1172
|
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/connection`
|
|
758
1173
|
: `/v1/projects/${encodeURIComponent(project)}/connection`;
|
|
759
|
-
const res = await
|
|
1174
|
+
const res = await req(path, "GET");
|
|
760
1175
|
return {
|
|
761
1176
|
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
762
1177
|
};
|
|
763
1178
|
}
|
|
764
1179
|
case "backwrite_generate_types": {
|
|
765
|
-
const project = resolveProject(a.project_id);
|
|
766
|
-
const branch = resolveBranch(a.branch_id);
|
|
1180
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1181
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
767
1182
|
const path = branch
|
|
768
1183
|
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
|
|
769
1184
|
: `/v1/projects/${encodeURIComponent(project)}/schema`;
|
|
770
|
-
const res = await
|
|
1185
|
+
const res = await req(path, "GET");
|
|
771
1186
|
let code = "";
|
|
772
1187
|
if (a.format === "typescript") {
|
|
773
1188
|
code = generateTypescript(res);
|
|
@@ -786,23 +1201,23 @@ async function main() {
|
|
|
786
1201
|
};
|
|
787
1202
|
}
|
|
788
1203
|
case "backwrite_list_projects": {
|
|
789
|
-
const orgsRes = await
|
|
1204
|
+
const orgsRes = await req("/v1/organizations", "GET");
|
|
790
1205
|
const orgs = orgsRes.organizations ?? (Array.isArray(orgsRes) ? orgsRes : []);
|
|
791
1206
|
const results = [];
|
|
792
1207
|
for (const o of orgs) {
|
|
793
|
-
const pRes = await
|
|
1208
|
+
const pRes = await req(`/v1/organizations/${encodeURIComponent(o.id)}/projects`, "GET").catch(() => ({ projects: [] }));
|
|
794
1209
|
results.push({ organization: o, projects: pRes.projects ?? pRes });
|
|
795
1210
|
}
|
|
796
1211
|
return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] };
|
|
797
1212
|
}
|
|
798
1213
|
case "backwrite_overview_live": {
|
|
799
|
-
const project = resolveProject(a.project_id);
|
|
1214
|
+
const project = resolveProject(a.project_id, ctx);
|
|
800
1215
|
const minutes = typeof a.minutes === "number" ? a.minutes : 60;
|
|
801
|
-
const res = await
|
|
1216
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/overview/live?minutes=${minutes}`, "GET");
|
|
802
1217
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
803
1218
|
}
|
|
804
1219
|
case "backwrite_advisors_list": {
|
|
805
|
-
const project = resolveProject(a.project_id);
|
|
1220
|
+
const project = resolveProject(a.project_id, ctx);
|
|
806
1221
|
const qs = new URLSearchParams();
|
|
807
1222
|
if (a.branch_id)
|
|
808
1223
|
qs.set("branch_id", String(a.branch_id));
|
|
@@ -811,29 +1226,29 @@ async function main() {
|
|
|
811
1226
|
if (a.status)
|
|
812
1227
|
qs.set("status", String(a.status));
|
|
813
1228
|
const suffix = qs.toString() ? `?${qs.toString()}` : "";
|
|
814
|
-
const res = await
|
|
1229
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/advisors${suffix}`, "GET");
|
|
815
1230
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
816
1231
|
}
|
|
817
1232
|
case "backwrite_advisors_scan": {
|
|
818
|
-
const project = resolveProject(a.project_id);
|
|
819
|
-
const branch = resolveBranch(a.branch_id);
|
|
820
|
-
const res = await
|
|
1233
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1234
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
1235
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/advisors/scan`, "POST", branch ? { branch_id: branch } : {});
|
|
821
1236
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
822
1237
|
}
|
|
823
1238
|
case "backwrite_advisors_simulate": {
|
|
824
|
-
const project = resolveProject(a.project_id);
|
|
825
|
-
const branch = resolveBranch(a.branch_id);
|
|
826
|
-
const res = await
|
|
1239
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1240
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
1241
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/advisors/${encodeURIComponent(a.finding_id)}/simulate`, "POST", branch ? { branch_id: branch } : {});
|
|
827
1242
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
828
1243
|
}
|
|
829
1244
|
case "backwrite_test_connection": {
|
|
830
|
-
const project = resolveProject(a.project_id);
|
|
831
|
-
const res = await
|
|
1245
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1246
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(a.branch_id)}/studio/connection/test`, "POST", {});
|
|
832
1247
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
833
1248
|
}
|
|
834
1249
|
case "backwrite_simulate_rls_policy": {
|
|
835
|
-
const project = resolveProject(a.project_id);
|
|
836
|
-
const res = await
|
|
1250
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1251
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(a.branch_id)}/studio/policies/simulate`, "POST", {
|
|
837
1252
|
schema: a.schema || "public",
|
|
838
1253
|
table: a.table,
|
|
839
1254
|
role: a.role || "authenticated",
|
|
@@ -844,23 +1259,23 @@ async function main() {
|
|
|
844
1259
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
845
1260
|
}
|
|
846
1261
|
case "backwrite_list_users": {
|
|
847
|
-
const project = resolveProject(a.project_id);
|
|
1262
|
+
const project = resolveProject(a.project_id, ctx);
|
|
848
1263
|
const qs = new URLSearchParams();
|
|
849
1264
|
qs.set("source", String(a.source || "all"));
|
|
850
1265
|
if (a.search)
|
|
851
1266
|
qs.set("search", String(a.search));
|
|
852
1267
|
if (typeof a.limit === "number")
|
|
853
1268
|
qs.set("limit", String(a.limit));
|
|
854
|
-
const res = await
|
|
1269
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(a.branch_id)}/studio/users?${qs.toString()}`, "GET");
|
|
855
1270
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
856
1271
|
}
|
|
857
1272
|
case "backwrite_list_secrets": {
|
|
858
|
-
const project = resolveProject(a.project_id);
|
|
859
|
-
const res = await
|
|
1273
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1274
|
+
const res = await req(`/v1/projects/${encodeURIComponent(project)}/secrets`, "GET");
|
|
860
1275
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
861
1276
|
}
|
|
862
1277
|
case "backwrite_migration_dry_run": {
|
|
863
|
-
const res = await
|
|
1278
|
+
const res = await req(`/v1/migrations/apply`, "POST", {
|
|
864
1279
|
branch_id: a.branch_id,
|
|
865
1280
|
statements: a.statements,
|
|
866
1281
|
dry_run: true,
|
|
@@ -869,19 +1284,19 @@ async function main() {
|
|
|
869
1284
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
870
1285
|
}
|
|
871
1286
|
case "backwrite_queue_stats": {
|
|
872
|
-
const res = await
|
|
1287
|
+
const res = await req(`/v1/queues/${encodeURIComponent(a.branch_id)}/${encodeURIComponent(a.queue)}/stats`, "GET");
|
|
873
1288
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
874
1289
|
}
|
|
875
1290
|
case "backwrite_cache_get": {
|
|
876
|
-
const res = await
|
|
1291
|
+
const res = await req(`/v1/cache/${encodeURIComponent(a.branch_id)}/entries/${encodeURIComponent(a.key)}`, "GET");
|
|
877
1292
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
878
1293
|
}
|
|
879
1294
|
case "backwrite_org_usage_limits": {
|
|
880
|
-
const res = await
|
|
1295
|
+
const res = await req(`/v1/organizations/${encodeURIComponent(a.organization_id)}/usage-limits`, "GET");
|
|
881
1296
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
882
1297
|
}
|
|
883
1298
|
case "backwrite_create_organization": {
|
|
884
|
-
const res = await
|
|
1299
|
+
const res = await req(`/v1/organizations`, "POST", {
|
|
885
1300
|
name: a.name,
|
|
886
1301
|
plan_tier: a.plan_tier || "free",
|
|
887
1302
|
database_engine: a.database_engine || "postgresql",
|
|
@@ -889,7 +1304,7 @@ async function main() {
|
|
|
889
1304
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
890
1305
|
}
|
|
891
1306
|
case "backwrite_create_project": {
|
|
892
|
-
const res = await
|
|
1307
|
+
const res = await req(`/v1/projects`, "POST", {
|
|
893
1308
|
organization_id: a.organization_id,
|
|
894
1309
|
name: a.name,
|
|
895
1310
|
database_engine: a.database_engine || "postgresql",
|
|
@@ -897,6 +1312,196 @@ async function main() {
|
|
|
897
1312
|
});
|
|
898
1313
|
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
899
1314
|
}
|
|
1315
|
+
case "backwrite_spawn_worktree": {
|
|
1316
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1317
|
+
const slug = slugifyTask(a.task_name);
|
|
1318
|
+
const branchName = `agent-${slug}-${Date.now().toString(36).slice(-4)}`;
|
|
1319
|
+
const gitBranch = `agent/${slug}`;
|
|
1320
|
+
const worktreePath = `.backwrite/worktrees/${branchName}`;
|
|
1321
|
+
const baseBranch = a.base_branch || "main";
|
|
1322
|
+
const created = await req(`/v1/projects/${encodeURIComponent(project)}/branches`, "POST", {
|
|
1323
|
+
name: branchName,
|
|
1324
|
+
branch_type: "preview",
|
|
1325
|
+
mode: a.mode || "schema-only",
|
|
1326
|
+
});
|
|
1327
|
+
const branchId = created.branch_id || created.id || "";
|
|
1328
|
+
return {
|
|
1329
|
+
content: [
|
|
1330
|
+
{
|
|
1331
|
+
type: "text",
|
|
1332
|
+
text: JSON.stringify({
|
|
1333
|
+
workspace_id: branchName,
|
|
1334
|
+
project_id: project,
|
|
1335
|
+
branch_id: branchId,
|
|
1336
|
+
operation_id: created.operation_id || null,
|
|
1337
|
+
git_branch: gitBranch,
|
|
1338
|
+
worktree_path: worktreePath,
|
|
1339
|
+
git_worktree_command: `git worktree add -b ${gitBranch} ${worktreePath} ${baseBranch}`,
|
|
1340
|
+
cleanup_command: `git worktree remove ${worktreePath} && git branch -d ${gitBranch}`,
|
|
1341
|
+
env_template: {
|
|
1342
|
+
BACKWRITE_URL: BACKWRITE_URL,
|
|
1343
|
+
BACKWRITE_PROJECT_ID: project,
|
|
1344
|
+
BACKWRITE_BRANCH_ID: branchId,
|
|
1345
|
+
DATABASE_URL: "postgresql://<ROLE>:<PASSWORD>@pooler.backwrite.dev:6543/<DB>?sslmode=require",
|
|
1346
|
+
DIRECT_URL: "postgresql://<ROLE>:<PASSWORD>@db.backwrite.dev:5432/<DB>?sslmode=require",
|
|
1347
|
+
},
|
|
1348
|
+
}, null, 2),
|
|
1349
|
+
},
|
|
1350
|
+
],
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1353
|
+
case "backwrite_sync_schema": {
|
|
1354
|
+
const project = resolveProject(a.project_id, ctx);
|
|
1355
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
1356
|
+
if (!branch)
|
|
1357
|
+
throw new Error("branch_id is required to sync schema safely on an isolated branch.");
|
|
1358
|
+
const queryRes = await req(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`, "POST", { sql: a.sql, view: "raw" });
|
|
1359
|
+
let advisors = null;
|
|
1360
|
+
if (a.run_advisors !== false) {
|
|
1361
|
+
advisors = await req(`/v1/projects/${encodeURIComponent(project)}/advisors`, "GET").catch((err) => ({ warning: `Advisors check skipped: ${err.message}` }));
|
|
1362
|
+
}
|
|
1363
|
+
return {
|
|
1364
|
+
content: [
|
|
1365
|
+
{
|
|
1366
|
+
type: "text",
|
|
1367
|
+
text: JSON.stringify({ branch_id: branch, migration: queryRes, advisors }, null, 2),
|
|
1368
|
+
},
|
|
1369
|
+
],
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
case "backwrite_workspace_lock": {
|
|
1373
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
1374
|
+
if (!branch)
|
|
1375
|
+
throw new Error("branch_id is required for distributed lockfile operations.");
|
|
1376
|
+
const safePath = String(a.file_path || "").replace(/^\/+/, "");
|
|
1377
|
+
if (!safePath || safePath.includes(".."))
|
|
1378
|
+
throw new Error("Invalid file_path for lockfile.");
|
|
1379
|
+
const lockKey = `backwrite:lock:${encodeURIComponent(safePath)}`;
|
|
1380
|
+
const action = String(a.action || "check");
|
|
1381
|
+
if (action === "check") {
|
|
1382
|
+
const existing = await req(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "GET").catch(() => null);
|
|
1383
|
+
return {
|
|
1384
|
+
content: [{ type: "text", text: JSON.stringify({ file_path: safePath, locked: Boolean(existing?.value), holder: existing || null }, null, 2) }],
|
|
1385
|
+
};
|
|
1386
|
+
}
|
|
1387
|
+
if (action === "release") {
|
|
1388
|
+
await req(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "DELETE").catch(() => ({}));
|
|
1389
|
+
return {
|
|
1390
|
+
content: [{ type: "text", text: JSON.stringify({ file_path: safePath, released: true, agent_id: a.agent_id || null }, null, 2) }],
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
// acquire: check if another agent already owns the lock
|
|
1394
|
+
const current = await req(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "GET").catch(() => null);
|
|
1395
|
+
if (current?.value) {
|
|
1396
|
+
try {
|
|
1397
|
+
const parsed = typeof current.value === "string" ? JSON.parse(current.value) : current.value;
|
|
1398
|
+
if (parsed.agent_id && parsed.agent_id !== a.agent_id) {
|
|
1399
|
+
return {
|
|
1400
|
+
content: [
|
|
1401
|
+
{
|
|
1402
|
+
type: "text",
|
|
1403
|
+
text: JSON.stringify({
|
|
1404
|
+
acquired: false,
|
|
1405
|
+
contested: true,
|
|
1406
|
+
file_path: safePath,
|
|
1407
|
+
held_by: parsed.agent_id,
|
|
1408
|
+
since: parsed.acquired_at,
|
|
1409
|
+
guidance: "File is contested by another active worktree agent. Pause and coordinate or request elicitation before editing.",
|
|
1410
|
+
}, null, 2),
|
|
1411
|
+
},
|
|
1412
|
+
],
|
|
1413
|
+
};
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
catch { }
|
|
1417
|
+
}
|
|
1418
|
+
const lockPayload = {
|
|
1419
|
+
agent_id: a.agent_id || "unknown-agent",
|
|
1420
|
+
file_path: safePath,
|
|
1421
|
+
acquired_at: new Date().toISOString(),
|
|
1422
|
+
};
|
|
1423
|
+
await req(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}?ttl=${Number(a.ttl_seconds || 600)}`, "PUT", { value: JSON.stringify(lockPayload) });
|
|
1424
|
+
return {
|
|
1425
|
+
content: [{ type: "text", text: JSON.stringify({ acquired: true, contested: false, ...lockPayload }, null, 2) }],
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
case "backwrite_agent_emit_event": {
|
|
1429
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
1430
|
+
if (!branch)
|
|
1431
|
+
throw new Error("branch_id is required to stream agent events.");
|
|
1432
|
+
const res = await req(`/v1/realtime/${encodeURIComponent(branch)}/broadcast`, "POST", {
|
|
1433
|
+
channel: `agent:${a.agent_id}`,
|
|
1434
|
+
event: a.event,
|
|
1435
|
+
payload: {
|
|
1436
|
+
agent_id: a.agent_id,
|
|
1437
|
+
message: a.message,
|
|
1438
|
+
metadata: a.metadata || {},
|
|
1439
|
+
ts: new Date().toISOString(),
|
|
1440
|
+
},
|
|
1441
|
+
});
|
|
1442
|
+
return { content: [{ type: "text", text: JSON.stringify({ streamed: true, channel: `agent:${a.agent_id}`, res }, null, 2) }] };
|
|
1443
|
+
}
|
|
1444
|
+
case "backwrite_elicit_context": {
|
|
1445
|
+
const elicitationId = `elicit_${crypto.randomUUID()}`;
|
|
1446
|
+
const payload = {
|
|
1447
|
+
type: "mcp/elicitation",
|
|
1448
|
+
elicitation_id: elicitationId,
|
|
1449
|
+
status: "awaiting_operator_input",
|
|
1450
|
+
reason: a.reason,
|
|
1451
|
+
question: a.question,
|
|
1452
|
+
requested_fields: Array.isArray(a.requested_fields) ? a.requested_fields : [],
|
|
1453
|
+
agent_id: a.agent_id || null,
|
|
1454
|
+
created_at: new Date().toISOString(),
|
|
1455
|
+
};
|
|
1456
|
+
if (a.branch_id) {
|
|
1457
|
+
await req(`/v1/realtime/${encodeURIComponent(a.branch_id)}/broadcast`, "POST", {
|
|
1458
|
+
channel: a.agent_id ? `agent:${a.agent_id}` : "agent:elicitation",
|
|
1459
|
+
event: "elicitation_required",
|
|
1460
|
+
payload,
|
|
1461
|
+
}).catch(() => { });
|
|
1462
|
+
}
|
|
1463
|
+
return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
|
|
1464
|
+
}
|
|
1465
|
+
case "backwrite_export_agent_plugin": {
|
|
1466
|
+
const project = a.project_id || DEFAULT_PROJECT_ID || "";
|
|
1467
|
+
const branch = resolveBranch(a.branch_id, ctx);
|
|
1468
|
+
let schemaSnapshot = undefined;
|
|
1469
|
+
if (a.include_schema !== false && project) {
|
|
1470
|
+
const path = branch
|
|
1471
|
+
? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
|
|
1472
|
+
: `/v1/projects/${encodeURIComponent(project)}/schema`;
|
|
1473
|
+
schemaSnapshot = await req(path, "GET").catch(() => undefined);
|
|
1474
|
+
}
|
|
1475
|
+
const files = buildAgentPluginFiles(String(a.name || "backwrite-agent-plugin"), project, branch, Array.isArray(a.skills) ? a.skills : [], schemaSnapshot);
|
|
1476
|
+
return {
|
|
1477
|
+
content: [
|
|
1478
|
+
{
|
|
1479
|
+
type: "text",
|
|
1480
|
+
text: JSON.stringify({
|
|
1481
|
+
standard: "Agent Plugins 1.0.0",
|
|
1482
|
+
plugin_name: slugifyTask(a.name),
|
|
1483
|
+
files_count: Object.keys(files).length,
|
|
1484
|
+
files,
|
|
1485
|
+
}, null, 2),
|
|
1486
|
+
},
|
|
1487
|
+
],
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
case "backwrite_list_snapshots": {
|
|
1491
|
+
const res = await req(`/v1/branches/${encodeURIComponent(a.branch_id)}/snapshots`, "GET");
|
|
1492
|
+
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
1493
|
+
}
|
|
1494
|
+
case "backwrite_create_snapshot": {
|
|
1495
|
+
const res = await req(`/v1/branches/${encodeURIComponent(a.branch_id)}/snapshot`, "POST", {
|
|
1496
|
+
label: a.label || `mcp-snap-${Date.now()}`,
|
|
1497
|
+
});
|
|
1498
|
+
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
1499
|
+
}
|
|
1500
|
+
case "backwrite_cache_set": {
|
|
1501
|
+
const ttl = Number(a.ttl_seconds || 300);
|
|
1502
|
+
const res = await req(`/v1/cache/${encodeURIComponent(a.branch_id)}/entries/${encodeURIComponent(a.key)}?ttl=${ttl}`, "PUT", { value: a.value });
|
|
1503
|
+
return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
|
|
1504
|
+
}
|
|
900
1505
|
default:
|
|
901
1506
|
throw new Error(`Unknown tool: ${name}`);
|
|
902
1507
|
}
|
|
@@ -908,38 +1513,143 @@ async function main() {
|
|
|
908
1513
|
};
|
|
909
1514
|
}
|
|
910
1515
|
}
|
|
911
|
-
|
|
912
|
-
const
|
|
913
|
-
|
|
914
|
-
|
|
1516
|
+
async function handleJsonRpc(rpc, ctx) {
|
|
1517
|
+
const id = rpc?.id ?? null;
|
|
1518
|
+
const method = String(rpc?.method || "");
|
|
1519
|
+
const params = (rpc?.params && typeof rpc.params === "object" ? rpc.params : {});
|
|
1520
|
+
// JSON-RPC notifications have no id and require no response
|
|
1521
|
+
if (method === "notifications/initialized" || method === "notifications/cancelled") {
|
|
1522
|
+
return null;
|
|
1523
|
+
}
|
|
1524
|
+
try {
|
|
1525
|
+
if (method === "initialize") {
|
|
1526
|
+
return {
|
|
1527
|
+
jsonrpc: "2.0",
|
|
1528
|
+
id,
|
|
1529
|
+
result: {
|
|
1530
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
1531
|
+
serverInfo: { name: "backwrite-mcp", version: VERSION },
|
|
1532
|
+
capabilities: { tools: {}, resources: {}, prompts: {} },
|
|
1533
|
+
},
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
if (method === "ping") {
|
|
1537
|
+
return { jsonrpc: "2.0", id, result: {} };
|
|
1538
|
+
}
|
|
1539
|
+
if (method === "logging/setLevel") {
|
|
1540
|
+
return { jsonrpc: "2.0", id, result: {} };
|
|
1541
|
+
}
|
|
1542
|
+
if (method === "tools/list") {
|
|
1543
|
+
return { jsonrpc: "2.0", id, result: { tools: TOOLS } };
|
|
1544
|
+
}
|
|
1545
|
+
if (method === "tools/call") {
|
|
1546
|
+
const result = await executeTool(String(params.name || ""), params.arguments || {}, ctx);
|
|
1547
|
+
return { jsonrpc: "2.0", id, result };
|
|
1548
|
+
}
|
|
1549
|
+
if (method === "resources/list") {
|
|
1550
|
+
return { jsonrpc: "2.0", id, result: { resources: RESOURCES } };
|
|
1551
|
+
}
|
|
1552
|
+
if (method === "resources/read") {
|
|
1553
|
+
const result = await readResource(String(params.uri || ""), ctx);
|
|
1554
|
+
return { jsonrpc: "2.0", id, result };
|
|
1555
|
+
}
|
|
1556
|
+
if (method === "prompts/list") {
|
|
1557
|
+
return { jsonrpc: "2.0", id, result: { prompts: PROMPTS } };
|
|
1558
|
+
}
|
|
1559
|
+
if (method === "prompts/get") {
|
|
1560
|
+
const result = getPromptMessages(String(params.name || ""), params.arguments || {});
|
|
1561
|
+
return { jsonrpc: "2.0", id, result };
|
|
1562
|
+
}
|
|
1563
|
+
return {
|
|
1564
|
+
jsonrpc: "2.0",
|
|
1565
|
+
id,
|
|
1566
|
+
error: { code: -32601, message: `Method not found: ${method}` },
|
|
1567
|
+
};
|
|
1568
|
+
}
|
|
1569
|
+
catch (err) {
|
|
1570
|
+
return {
|
|
1571
|
+
jsonrpc: "2.0",
|
|
1572
|
+
id,
|
|
1573
|
+
error: { code: -32603, message: err?.message || String(err) },
|
|
1574
|
+
};
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
915
1577
|
if (process.argv.includes("--http") || process.env.MCP_HTTP_PORT || process.env.PORT) {
|
|
916
1578
|
const port = parseInt(process.env.MCP_HTTP_PORT || process.env.PORT || "8090", 10);
|
|
1579
|
+
const bindHost = process.env.MCP_HTTP_HOST || "127.0.0.1";
|
|
1580
|
+
const isLoopbackOnly = bindHost === "127.0.0.1" || bindHost === "localhost" || bindHost === "::1";
|
|
1581
|
+
const allowAmbientLocalKey = isLoopbackOnly && process.env.MCP_ALLOW_LOCAL_AMBIENT_KEY === "true";
|
|
1582
|
+
const corsOrigin = process.env.MCP_CORS_ORIGIN || "https://console.backwrite.dev";
|
|
1583
|
+
const MAX_BODY_BYTES = 1_048_576;
|
|
917
1584
|
const http = await import("node:http");
|
|
918
|
-
const
|
|
919
|
-
const
|
|
1585
|
+
const sseSessions = new Map();
|
|
1586
|
+
const extractHttpCtx = (req) => {
|
|
1587
|
+
const headerAuth = (typeof req.headers.authorization === "string" ? req.headers.authorization : "") ||
|
|
1588
|
+
(typeof req.headers.apikey === "string" ? req.headers.apikey : "");
|
|
1589
|
+
const apiKey = headerAuth.replace(/^Bearer\s+/i, "").trim() || undefined;
|
|
1590
|
+
const projectId = typeof req.headers["x-backwrite-project"] === "string"
|
|
1591
|
+
? req.headers["x-backwrite-project"].trim() || undefined
|
|
1592
|
+
: undefined;
|
|
1593
|
+
const branchId = typeof req.headers["x-backwrite-branch"] === "string"
|
|
1594
|
+
? req.headers["x-backwrite-branch"].trim() || undefined
|
|
1595
|
+
: undefined;
|
|
1596
|
+
return {
|
|
1597
|
+
apiKey,
|
|
1598
|
+
projectId,
|
|
1599
|
+
branchId,
|
|
1600
|
+
// Never allow unauthenticated HTTP callers to inherit the server process's ambient service key
|
|
1601
|
+
requireExplicitKey: !allowAmbientLocalKey,
|
|
1602
|
+
};
|
|
1603
|
+
};
|
|
1604
|
+
const readJsonBody = async (req, res) => {
|
|
1605
|
+
const chunks = [];
|
|
1606
|
+
let totalBytes = 0;
|
|
1607
|
+
for await (const chunk of req) {
|
|
1608
|
+
const buf = Buffer.from(chunk);
|
|
1609
|
+
totalBytes += buf.length;
|
|
1610
|
+
if (totalBytes > MAX_BODY_BYTES) {
|
|
1611
|
+
res.writeHead(413, { "Content-Type": "application/json" });
|
|
1612
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Request body too large" } }));
|
|
1613
|
+
return null;
|
|
1614
|
+
}
|
|
1615
|
+
chunks.push(buf);
|
|
1616
|
+
}
|
|
1617
|
+
const raw = Buffer.concat(chunks).toString("utf-8");
|
|
1618
|
+
try {
|
|
1619
|
+
return JSON.parse(raw || "{}");
|
|
1620
|
+
}
|
|
1621
|
+
catch {
|
|
1622
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1623
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }));
|
|
1624
|
+
return null;
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
920
1627
|
const httpServer = http.createServer(async (req, res) => {
|
|
921
|
-
res.setHeader("Access-Control-Allow-Origin",
|
|
1628
|
+
res.setHeader("Access-Control-Allow-Origin", corsOrigin);
|
|
922
1629
|
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
923
1630
|
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, apikey, X-Backwrite-Project, X-Backwrite-Branch");
|
|
1631
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
924
1632
|
if (req.method === "OPTIONS") {
|
|
925
1633
|
res.writeHead(204);
|
|
926
1634
|
res.end();
|
|
927
1635
|
return;
|
|
928
1636
|
}
|
|
929
|
-
const
|
|
930
|
-
const url = new URL(req.url || "/", `http://${host}`);
|
|
1637
|
+
const url = new URL(req.url || "/", `http://127.0.0.1:${port}`);
|
|
931
1638
|
if (url.pathname === "/health" || url.pathname === "/") {
|
|
932
1639
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
933
1640
|
res.end(JSON.stringify({
|
|
934
1641
|
status: "online",
|
|
935
1642
|
server: "backwrite-mcp",
|
|
936
|
-
version:
|
|
1643
|
+
version: VERSION,
|
|
1644
|
+
protocol_version: PROTOCOL_VERSION,
|
|
937
1645
|
transports: ["streamable-http", "sse"],
|
|
938
1646
|
mcp_endpoint: "/mcp",
|
|
939
1647
|
sse_endpoint: "/sse",
|
|
940
1648
|
messages: "/messages",
|
|
941
1649
|
tools_endpoint: "/tools",
|
|
942
1650
|
tools_count: TOOLS.length,
|
|
1651
|
+
resources_count: RESOURCES.length,
|
|
1652
|
+
prompts_count: PROMPTS.length,
|
|
943
1653
|
}));
|
|
944
1654
|
return;
|
|
945
1655
|
}
|
|
@@ -947,7 +1657,7 @@ async function main() {
|
|
|
947
1657
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
948
1658
|
res.end(JSON.stringify({
|
|
949
1659
|
server: "backwrite-mcp",
|
|
950
|
-
version:
|
|
1660
|
+
version: VERSION,
|
|
951
1661
|
count: TOOLS.length,
|
|
952
1662
|
tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
|
|
953
1663
|
}));
|
|
@@ -955,81 +1665,104 @@ async function main() {
|
|
|
955
1665
|
}
|
|
956
1666
|
// Stateless Streamable HTTP JSON-RPC 2.0 endpoint (/mcp)
|
|
957
1667
|
if (url.pathname === "/mcp" && req.method === "POST") {
|
|
958
|
-
const
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
const
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
1668
|
+
const rpc = await readJsonBody(req, res);
|
|
1669
|
+
if (!rpc)
|
|
1670
|
+
return;
|
|
1671
|
+
const ctx = extractHttpCtx(req);
|
|
1672
|
+
const method = String(rpc.method || "");
|
|
1673
|
+
if (ctx.requireExplicitKey && !ctx.apiKey && (method === "tools/call" || method === "resources/read")) {
|
|
1674
|
+
res.writeHead(401, { "Content-Type": "application/json" });
|
|
1675
|
+
res.end(JSON.stringify({
|
|
1676
|
+
jsonrpc: "2.0",
|
|
1677
|
+
id: rpc.id ?? null,
|
|
1678
|
+
error: { code: -32001, message: "Authentication required: supply Authorization: Bearer <token> or apikey header." },
|
|
1679
|
+
}));
|
|
969
1680
|
return;
|
|
970
1681
|
}
|
|
971
|
-
const
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
const method = rpc.method;
|
|
976
|
-
const params = rpc.params || {};
|
|
977
|
-
let result;
|
|
978
|
-
if (method === "initialize") {
|
|
979
|
-
result = {
|
|
980
|
-
protocolVersion: "2024-11-05",
|
|
981
|
-
serverInfo: { name: "backwrite-mcp", version: "0.2.3" },
|
|
982
|
-
capabilities: { tools: {} },
|
|
983
|
-
};
|
|
984
|
-
}
|
|
985
|
-
else if (method === "tools/list") {
|
|
986
|
-
result = { tools: TOOLS };
|
|
987
|
-
}
|
|
988
|
-
else if (method === "tools/call") {
|
|
989
|
-
result = await requestAuthStore.run({ apiKey }, () => executeTool(String(params.name || ""), params.arguments || {}));
|
|
990
|
-
}
|
|
991
|
-
else {
|
|
992
|
-
res.writeHead(200, { "Content-Type": "application/json" });
|
|
993
|
-
res.end(JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } }));
|
|
1682
|
+
const reply = await handleJsonRpc(rpc, ctx);
|
|
1683
|
+
if (reply === null) {
|
|
1684
|
+
res.writeHead(202);
|
|
1685
|
+
res.end();
|
|
994
1686
|
return;
|
|
995
1687
|
}
|
|
996
1688
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
997
|
-
res.end(JSON.stringify(
|
|
1689
|
+
res.end(JSON.stringify(reply));
|
|
998
1690
|
return;
|
|
999
1691
|
}
|
|
1692
|
+
// Authenticated SSE transport (/sse + /messages?sessionId=...)
|
|
1000
1693
|
if (url.pathname === "/sse" && req.method === "GET") {
|
|
1001
|
-
const
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1694
|
+
const ctx = extractHttpCtx(req);
|
|
1695
|
+
if (ctx.requireExplicitKey && !ctx.apiKey) {
|
|
1696
|
+
res.writeHead(401, { "Content-Type": "application/json" });
|
|
1697
|
+
res.end(JSON.stringify({ error: "Authentication required: supply Authorization: Bearer <token> or apikey header." }));
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
const sessionId = `sess_${crypto.randomUUID()}`;
|
|
1701
|
+
res.writeHead(200, {
|
|
1702
|
+
"Content-Type": "text/event-stream",
|
|
1703
|
+
"Cache-Control": "no-cache, no-transform",
|
|
1704
|
+
Connection: "keep-alive",
|
|
1705
|
+
});
|
|
1706
|
+
res.write(`event: endpoint\ndata: /messages?sessionId=${encodeURIComponent(sessionId)}\n\n`);
|
|
1707
|
+
sseSessions.set(sessionId, { res, ctx });
|
|
1708
|
+
req.on("close", () => {
|
|
1709
|
+
sseSessions.delete(sessionId);
|
|
1710
|
+
});
|
|
1008
1711
|
return;
|
|
1009
1712
|
}
|
|
1010
1713
|
if (url.pathname === "/messages" && req.method === "POST") {
|
|
1011
1714
|
const sessionId = url.searchParams.get("sessionId");
|
|
1012
|
-
const
|
|
1013
|
-
|
|
1014
|
-
: Array.from(transports.values())[0];
|
|
1015
|
-
if (!transport) {
|
|
1715
|
+
const session = sessionId ? sseSessions.get(sessionId) : undefined;
|
|
1716
|
+
if (!session) {
|
|
1016
1717
|
res.writeHead(404, { "Content-Type": "application/json" });
|
|
1017
1718
|
res.end(JSON.stringify({ error: "Session not found" }));
|
|
1018
1719
|
return;
|
|
1019
1720
|
}
|
|
1020
|
-
await
|
|
1721
|
+
const rpc = await readJsonBody(req, res);
|
|
1722
|
+
if (!rpc)
|
|
1723
|
+
return;
|
|
1724
|
+
const reqCtx = extractHttpCtx(req);
|
|
1725
|
+
const mergedCtx = {
|
|
1726
|
+
apiKey: reqCtx.apiKey || session.ctx.apiKey,
|
|
1727
|
+
projectId: reqCtx.projectId || session.ctx.projectId,
|
|
1728
|
+
branchId: reqCtx.branchId || session.ctx.branchId,
|
|
1729
|
+
requireExplicitKey: session.ctx.requireExplicitKey,
|
|
1730
|
+
};
|
|
1731
|
+
const reply = await handleJsonRpc(rpc, mergedCtx);
|
|
1732
|
+
if (reply !== null) {
|
|
1733
|
+
session.res.write(`event: message\ndata: ${JSON.stringify(reply)}\n\n`);
|
|
1734
|
+
}
|
|
1735
|
+
res.writeHead(202, { "Content-Type": "application/json" });
|
|
1736
|
+
res.end(JSON.stringify({ accepted: true }));
|
|
1021
1737
|
return;
|
|
1022
1738
|
}
|
|
1023
1739
|
res.writeHead(404, { "Content-Type": "application/json" });
|
|
1024
1740
|
res.end(JSON.stringify({ error: "Not Found" }));
|
|
1025
1741
|
});
|
|
1026
|
-
httpServer.listen(port,
|
|
1027
|
-
console.log(`Backwrite MCP Server listening on http
|
|
1742
|
+
httpServer.listen(port, bindHost, () => {
|
|
1743
|
+
console.log(`Backwrite MCP Server v${VERSION} listening on http://${bindHost}:${port} (/mcp, /sse, /messages)`);
|
|
1028
1744
|
});
|
|
1029
1745
|
}
|
|
1030
1746
|
else {
|
|
1031
|
-
|
|
1032
|
-
|
|
1747
|
+
// Native newline-delimited JSON-RPC 2.0 Stdio transport (zero external deps)
|
|
1748
|
+
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
1749
|
+
rl.on("line", async (line) => {
|
|
1750
|
+
const trimmed = line.trim();
|
|
1751
|
+
if (!trimmed)
|
|
1752
|
+
return;
|
|
1753
|
+
let rpc;
|
|
1754
|
+
try {
|
|
1755
|
+
rpc = JSON.parse(trimmed);
|
|
1756
|
+
}
|
|
1757
|
+
catch {
|
|
1758
|
+
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }) + "\n");
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
const reply = await handleJsonRpc(rpc, { requireExplicitKey: false });
|
|
1762
|
+
if (reply !== null) {
|
|
1763
|
+
process.stdout.write(JSON.stringify(reply) + "\n");
|
|
1764
|
+
}
|
|
1765
|
+
});
|
|
1033
1766
|
}
|
|
1034
1767
|
}
|
|
1035
1768
|
main().catch((error) => {
|