@backwrite/mcp 0.3.0 → 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/dist/index.js CHANGED
@@ -3,12 +3,38 @@
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 { AsyncLocalStorage } from "node:async_hooks";
7
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
8
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
- import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
10
- const VERSION = "0.3.0";
11
- const requestAuthStore = new AsyncLocalStorage();
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(",")}]`;
37
+ }
12
38
  function assertSafeBaseUrl(raw) {
13
39
  let u;
14
40
  try {
@@ -32,17 +58,18 @@ const BACKWRITE_URL = assertSafeBaseUrl(process.env.BACKWRITE_URL ||
32
58
  const BACKWRITE_API_KEY = process.env.BACKWRITE_SERVICE_KEY ||
33
59
  process.env.BACKWRITE_SECRET_KEY ||
34
60
  process.env.BACKWRITE_API_KEY ||
35
- process.env.BW_KEY ||
36
61
  "";
37
62
  const DEFAULT_PROJECT_ID = process.env.BACKWRITE_PROJECT_ID || "";
38
63
  const DEFAULT_BRANCH_ID = process.env.BACKWRITE_BRANCH_ID || "";
39
- async function apiRequest(path, method = "GET", body) {
64
+ async function apiRequest(path, method = "GET", body, ctx) {
40
65
  if (!path.startsWith("/") || path.startsWith("//") || path.includes("..") || /[\r\n\0]/.test(path)) {
41
66
  throw new Error(`Security block: invalid API path '${path}'.`);
42
67
  }
43
68
  const url = `${BACKWRITE_URL}${path}`;
44
- const ctx = requestAuthStore.getStore();
45
- const activeKey = ctx?.apiKey || BACKWRITE_API_KEY;
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
+ }
46
73
  if (activeKey && /[\r\n\0]/.test(activeKey)) {
47
74
  throw new Error("Security block: malformed authorization token.");
48
75
  }
@@ -51,7 +78,7 @@ async function apiRequest(path, method = "GET", body) {
51
78
  "Content-Type": "application/json",
52
79
  };
53
80
  if (method.toUpperCase() !== "GET" && method.toUpperCase() !== "HEAD") {
54
- headers["Idempotency-Key"] = `bwmcp_${crypto.randomUUID()}`;
81
+ headers["Idempotency-Key"] = `backwrite_mcp_${crypto.randomUUID()}`;
55
82
  }
56
83
  if (activeKey) {
57
84
  if (activeKey.startsWith("bwk_") || activeKey.startsWith("bw_")) {
@@ -72,15 +99,15 @@ async function apiRequest(path, method = "GET", body) {
72
99
  }
73
100
  return json.data ?? json;
74
101
  }
75
- function resolveProject(projectId) {
76
- const p = projectId || DEFAULT_PROJECT_ID;
102
+ function resolveProject(projectId, ctx) {
103
+ const p = projectId || ctx?.projectId || DEFAULT_PROJECT_ID;
77
104
  if (!p) {
78
105
  throw new Error("No project_id specified and BACKWRITE_PROJECT_ID environment variable is not set.");
79
106
  }
80
107
  return p;
81
108
  }
82
- function resolveBranch(branchId) {
83
- return branchId || DEFAULT_BRANCH_ID || undefined;
109
+ function resolveBranch(branchId, ctx) {
110
+ return branchId || ctx?.branchId || DEFAULT_BRANCH_ID || undefined;
84
111
  }
85
112
  // ── Codegen Utilities ────────────────────────────────────────────────────────
86
113
  function pgToTs(ty, nullable) {
@@ -666,7 +693,7 @@ const TOOLS = [
666
693
  },
667
694
  {
668
695
  name: "backwrite_agent_emit_event",
669
- description: "Stream structured agent telemetry (thoughts, tool calls, test results, status transitions) over Backwrite Realtime / NATS JetStream so terminal dashboards (`bw top`) and UI consoles can observe parallel agents live.",
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.",
670
697
  inputSchema: {
671
698
  type: "object",
672
699
  properties: {
@@ -711,7 +738,7 @@ const TOOLS = [
711
738
  skills: {
712
739
  type: "array",
713
740
  items: { type: "string" },
714
- description: "Skills to generate (e.g. ['bw-migrations', 'bw-deploy', 'database-troubleshooting', 'api-generation']).",
741
+ description: "Skills to generate (e.g. ['backwrite-migrations', 'backwrite-deploy', 'database-troubleshooting', 'api-generation']).",
715
742
  },
716
743
  },
717
744
  required: ["name"],
@@ -740,17 +767,6 @@ const TOOLS = [
740
767
  required: ["branch_id"],
741
768
  },
742
769
  },
743
- {
744
- name: "backwrite_delete_branch",
745
- description: "Tear down a disposable preview or agent worktree PostgreSQL 18 branch after review/merge.",
746
- inputSchema: {
747
- type: "object",
748
- properties: {
749
- branch_id: { type: "string", description: "Non-production branch ID to delete." },
750
- },
751
- required: ["branch_id"],
752
- },
753
- },
754
770
  {
755
771
  name: "backwrite_cache_set",
756
772
  description: "Store a key/value entry with optional TTL in a branch's Valkey 8 in-memory cache.",
@@ -795,7 +811,7 @@ function slugifyTask(task) {
795
811
  }
796
812
  function buildAgentPluginFiles(name, projectId, branchId, skills, schemaSnapshot) {
797
813
  const safeName = slugifyTask(name);
798
- const selectedSkills = skills.length > 0 ? skills : ["bw-migrations", "bw-deploy", "database-troubleshooting", "api-generation"];
814
+ const selectedSkills = skills.length > 0 ? skills : ["backwrite-migrations", "backwrite-deploy", "database-troubleshooting", "api-generation"];
799
815
  const files = {
800
816
  "plugin.json": JSON.stringify({
801
817
  schemaVersion: "1.0.0",
@@ -828,8 +844,8 @@ function buildAgentPluginFiles(name, projectId, branchId, skills, schemaSnapshot
828
844
  files["schema.json"] = JSON.stringify(schemaSnapshot, null, 2);
829
845
  }
830
846
  const skillBodies = {
831
- "bw-migrations": `---
832
- name: bw-migrations
847
+ "backwrite-migrations": `---
848
+ name: backwrite-migrations
833
849
  description: Safe PostgreSQL 18 schema migration SOP using isolated Backwrite CoW branches and Advisors.
834
850
  ---
835
851
 
@@ -839,10 +855,10 @@ description: Safe PostgreSQL 18 schema migration SOP using isolated Backwrite Co
839
855
  2. Read the live schema via MCP Resource \`backwrite://schema/current\` or \`backwrite_get_database_schema\`.
840
856
  3. Acquire a lock on migration/schema files via \`backwrite_workspace_lock(action="acquire")\` before editing.
841
857
  4. Apply DDL to the disposable branch with \`backwrite_sync_schema(run_advisors=true)\` and resolve any missing-index or RLS findings.
842
- 5. Take a snapshot (\`backwrite_create_snapshot\`) before promoting, then hand off for human review via \`bw review <agent-id>\`.
858
+ 5. Take a snapshot (\`backwrite_create_snapshot\`) before promoting, then hand off for human review via \`backwrite review <agent-id>\`.
843
859
  `,
844
- "bw-deploy": `---
845
- name: bw-deploy
860
+ "backwrite-deploy": `---
861
+ name: backwrite-deploy
846
862
  description: Pre-deploy verification checklist for Backwrite projects, PgBouncer :6543 pooling, and PITR snapshots.
847
863
  ---
848
864
 
@@ -884,39 +900,105 @@ description: Generate strictly typed TypeScript, Drizzle, or Prisma models from
884
900
  }
885
901
  return files;
886
902
  }
887
- // ── MCP Server Startup ──────────────────────────────────────────────────────
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
+ },
924
+ ];
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) ─────────────────────
888
985
  async function main() {
889
- const server = new Server({
890
- name: "backwrite-mcp",
891
- version: VERSION,
892
- }, {
893
- capabilities: {
894
- tools: {},
895
- resources: {},
896
- },
897
- });
898
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
899
- tools: TOOLS,
900
- }));
901
- server.setRequestHandler(ListResourcesRequestSchema, async () => ({
902
- resources: RESOURCES,
903
- }));
904
- async function readResource(uri) {
905
- const project = resolveProject();
906
- const branch = resolveBranch();
986
+ async function readResource(uri, ctx) {
987
+ const project = resolveProject(undefined, ctx);
988
+ const branch = resolveBranch(undefined, ctx);
907
989
  if (uri === "backwrite://schema/current") {
908
990
  const path = branch
909
991
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
910
992
  : `/v1/projects/${encodeURIComponent(project)}/schema`;
911
- const data = await apiRequest(path, "GET");
993
+ const data = await apiRequest(path, "GET", undefined, ctx);
912
994
  return {
913
995
  contents: [{ uri, mimeType: "application/json", text: JSON.stringify(data, null, 2) }],
914
996
  };
915
997
  }
916
998
  if (uri === "backwrite://architecture/topology") {
917
999
  const [branches, overview] = await Promise.all([
918
- apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches`, "GET").catch(() => ({ branches: [] })),
919
- apiRequest(`/v1/projects/${encodeURIComponent(project)}/overview`, "GET").catch(() => ({})),
1000
+ apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches`, "GET", undefined, ctx).catch(() => ({ branches: [] })),
1001
+ apiRequest(`/v1/projects/${encodeURIComponent(project)}/overview`, "GET", undefined, ctx).catch(() => ({})),
920
1002
  ]);
921
1003
  return {
922
1004
  contents: [
@@ -939,48 +1021,46 @@ async function main() {
939
1021
  };
940
1022
  }
941
1023
  if (uri === "backwrite://advisors/findings") {
942
- const data = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/advisors`, "GET");
1024
+ const data = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/advisors`, "GET", undefined, ctx);
943
1025
  return {
944
1026
  contents: [{ uri, mimeType: "application/json", text: JSON.stringify(data, null, 2) }],
945
1027
  };
946
1028
  }
947
1029
  throw new Error(`Unknown Backwrite MCP resource URI: ${uri}`);
948
1030
  }
949
- server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
950
- return readResource(request.params.uri);
951
- });
952
- async function executeTool(name, a) {
1031
+ async function executeTool(name, a, ctx) {
1032
+ const req = (path, method = "GET", body) => apiRequest(path, method, body, ctx);
953
1033
  try {
954
1034
  switch (name) {
955
1035
  case "backwrite_execute_sql": {
956
- const project = resolveProject(a.project_id);
957
- const branch = resolveBranch(a.branch_id);
1036
+ const project = resolveProject(a.project_id, ctx);
1037
+ const branch = resolveBranch(a.branch_id, ctx);
958
1038
  const path = branch
959
1039
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`
960
1040
  : `/v1/projects/${encodeURIComponent(project)}/query`;
961
- const res = await apiRequest(path, "POST", { sql: a.sql, view: "raw" });
1041
+ const res = await req(path, "POST", { sql: a.sql, view: "raw" });
962
1042
  return {
963
1043
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
964
1044
  };
965
1045
  }
966
1046
  case "backwrite_get_database_schema": {
967
- const project = resolveProject(a.project_id);
968
- const branch = resolveBranch(a.branch_id);
1047
+ const project = resolveProject(a.project_id, ctx);
1048
+ const branch = resolveBranch(a.branch_id, ctx);
969
1049
  const path = branch
970
1050
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
971
1051
  : `/v1/projects/${encodeURIComponent(project)}/schema`;
972
- const res = await apiRequest(path, "GET");
1052
+ const res = await req(path, "GET");
973
1053
  return {
974
1054
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
975
1055
  };
976
1056
  }
977
1057
  case "backwrite_list_tables": {
978
- const project = resolveProject(a.project_id);
979
- const branch = resolveBranch(a.branch_id);
1058
+ const project = resolveProject(a.project_id, ctx);
1059
+ const branch = resolveBranch(a.branch_id, ctx);
980
1060
  const path = branch
981
1061
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
982
1062
  : `/v1/projects/${encodeURIComponent(project)}/schema`;
983
- const res = await apiRequest(path, "GET");
1063
+ const res = await req(path, "GET");
984
1064
  const tables = (res.tables || []).map((t) => ({
985
1065
  schema: t.schema,
986
1066
  name: t.name,
@@ -992,12 +1072,12 @@ async function main() {
992
1072
  };
993
1073
  }
994
1074
  case "backwrite_describe_table": {
995
- const project = resolveProject(a.project_id);
996
- const branch = resolveBranch(a.branch_id);
1075
+ const project = resolveProject(a.project_id, ctx);
1076
+ const branch = resolveBranch(a.branch_id, ctx);
997
1077
  const path = branch
998
1078
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
999
1079
  : `/v1/projects/${encodeURIComponent(project)}/schema`;
1000
- const res = await apiRequest(path, "GET");
1080
+ const res = await req(path, "GET");
1001
1081
  const targetSchema = a.schema_name || "public";
1002
1082
  const table = (res.tables || []).find((t) => t.name === a.table_name &&
1003
1083
  (t.schema === targetSchema || (!a.schema_name && t.schema === "public")));
@@ -1009,15 +1089,15 @@ async function main() {
1009
1089
  };
1010
1090
  }
1011
1091
  case "backwrite_list_branches": {
1012
- const project = resolveProject(a.project_id);
1013
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches`, "GET");
1092
+ const project = resolveProject(a.project_id, ctx);
1093
+ const res = await req(`/v1/projects/${encodeURIComponent(project)}/branches`, "GET");
1014
1094
  return {
1015
1095
  content: [{ type: "text", text: JSON.stringify(res.branches ?? res, null, 2) }],
1016
1096
  };
1017
1097
  }
1018
1098
  case "backwrite_create_branch": {
1019
- const project = resolveProject(a.project_id);
1020
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches`, "POST", {
1099
+ const project = resolveProject(a.project_id, ctx);
1100
+ const res = await req(`/v1/projects/${encodeURIComponent(project)}/branches`, "POST", {
1021
1101
  name: a.name,
1022
1102
  branch_type: a.branch_type || "preview",
1023
1103
  source_branch_id: a.source_branch_id,
@@ -1027,31 +1107,33 @@ async function main() {
1027
1107
  };
1028
1108
  }
1029
1109
  case "backwrite_delete_branch": {
1030
- const res = await apiRequest(`/v1/branches/${encodeURIComponent(a.branch_id)}`, "DELETE");
1110
+ const res = await req(`/v1/branches/${encodeURIComponent(a.branch_id)}`, "DELETE");
1031
1111
  return {
1032
1112
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
1033
1113
  };
1034
1114
  }
1035
1115
  case "backwrite_vector_search": {
1036
- const project = resolveProject(a.project_id);
1037
- const branch = resolveBranch(a.branch_id);
1038
- const cols = a.select_columns || "*";
1039
- const limit = typeof a.limit === "number" ? Math.min(a.limit, 100) : 10;
1040
- const vectorStr = `[${a.query_vector.join(",")}]`;
1041
- const sanitizedTable = String(a.table_name).replace(/"/g, '""');
1042
- const sanitizedCol = String(a.embedding_column).replace(/"/g, '""');
1043
- const sql = `SELECT ${cols}, ("${sanitizedCol}" <=> '${vectorStr}') AS distance FROM "${sanitizedTable}" ORDER BY distance ASC LIMIT ${limit};`;
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};`;
1044
1126
  const path = branch
1045
1127
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`
1046
1128
  : `/v1/projects/${encodeURIComponent(project)}/query`;
1047
- const res = await apiRequest(path, "POST", { sql, view: "raw" });
1129
+ const res = await req(path, "POST", { sql, view: "raw" });
1048
1130
  return {
1049
1131
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
1050
1132
  };
1051
1133
  }
1052
1134
  case "backwrite_store_agent_memory": {
1053
- const project = resolveProject(a.project_id);
1054
- const branch = resolveBranch(a.branch_id);
1135
+ const project = resolveProject(a.project_id, ctx);
1136
+ const branch = resolveBranch(a.branch_id, ctx);
1055
1137
  const path = branch
1056
1138
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`
1057
1139
  : `/v1/projects/${encodeURIComponent(project)}/query`;
@@ -1068,39 +1150,39 @@ async function main() {
1068
1150
  );
1069
1151
  CREATE INDEX IF NOT EXISTS idx_agent_memories_key ON agent_memories(memory_key);
1070
1152
  `;
1071
- await apiRequest(path, "POST", { sql: ensureSql, view: "raw" }).catch(() => { });
1153
+ await req(path, "POST", { sql: ensureSql, view: "raw" }).catch(() => { });
1072
1154
  const metaJson = JSON.stringify(a.metadata || {}).replace(/'/g, "''");
1073
1155
  const contentEsc = String(a.content).replace(/'/g, "''");
1074
1156
  const keyEsc = String(a.memory_key).replace(/'/g, "''");
1075
- const embeddingVal = a.embedding && Array.isArray(a.embedding) ? `'[${a.embedding.join(",")}]'` : "NULL";
1157
+ const embeddingVal = a.embedding ? `'${sanitizeVectorLiteral(a.embedding)}'` : "NULL";
1076
1158
  const insertSql = `
1077
1159
  INSERT INTO agent_memories (memory_key, content, metadata, embedding)
1078
1160
  VALUES ('${keyEsc}', '${contentEsc}', '${metaJson}'::jsonb, ${embeddingVal})
1079
1161
  RETURNING id, memory_key, created_at;
1080
1162
  `;
1081
- const res = await apiRequest(path, "POST", { sql: insertSql, view: "raw" });
1163
+ const res = await req(path, "POST", { sql: insertSql, view: "raw" });
1082
1164
  return {
1083
1165
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
1084
1166
  };
1085
1167
  }
1086
1168
  case "backwrite_get_connection_string": {
1087
- const project = resolveProject(a.project_id);
1088
- const branch = resolveBranch(a.branch_id);
1169
+ const project = resolveProject(a.project_id, ctx);
1170
+ const branch = resolveBranch(a.branch_id, ctx);
1089
1171
  const path = branch
1090
1172
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/connection`
1091
1173
  : `/v1/projects/${encodeURIComponent(project)}/connection`;
1092
- const res = await apiRequest(path, "GET");
1174
+ const res = await req(path, "GET");
1093
1175
  return {
1094
1176
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
1095
1177
  };
1096
1178
  }
1097
1179
  case "backwrite_generate_types": {
1098
- const project = resolveProject(a.project_id);
1099
- const branch = resolveBranch(a.branch_id);
1180
+ const project = resolveProject(a.project_id, ctx);
1181
+ const branch = resolveBranch(a.branch_id, ctx);
1100
1182
  const path = branch
1101
1183
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
1102
1184
  : `/v1/projects/${encodeURIComponent(project)}/schema`;
1103
- const res = await apiRequest(path, "GET");
1185
+ const res = await req(path, "GET");
1104
1186
  let code = "";
1105
1187
  if (a.format === "typescript") {
1106
1188
  code = generateTypescript(res);
@@ -1119,23 +1201,23 @@ async function main() {
1119
1201
  };
1120
1202
  }
1121
1203
  case "backwrite_list_projects": {
1122
- const orgsRes = await apiRequest("/v1/organizations", "GET");
1204
+ const orgsRes = await req("/v1/organizations", "GET");
1123
1205
  const orgs = orgsRes.organizations ?? (Array.isArray(orgsRes) ? orgsRes : []);
1124
1206
  const results = [];
1125
1207
  for (const o of orgs) {
1126
- const pRes = await apiRequest(`/v1/organizations/${encodeURIComponent(o.id)}/projects`, "GET").catch(() => ({ projects: [] }));
1208
+ const pRes = await req(`/v1/organizations/${encodeURIComponent(o.id)}/projects`, "GET").catch(() => ({ projects: [] }));
1127
1209
  results.push({ organization: o, projects: pRes.projects ?? pRes });
1128
1210
  }
1129
1211
  return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] };
1130
1212
  }
1131
1213
  case "backwrite_overview_live": {
1132
- const project = resolveProject(a.project_id);
1214
+ const project = resolveProject(a.project_id, ctx);
1133
1215
  const minutes = typeof a.minutes === "number" ? a.minutes : 60;
1134
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/overview/live?minutes=${minutes}`, "GET");
1216
+ const res = await req(`/v1/projects/${encodeURIComponent(project)}/overview/live?minutes=${minutes}`, "GET");
1135
1217
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1136
1218
  }
1137
1219
  case "backwrite_advisors_list": {
1138
- const project = resolveProject(a.project_id);
1220
+ const project = resolveProject(a.project_id, ctx);
1139
1221
  const qs = new URLSearchParams();
1140
1222
  if (a.branch_id)
1141
1223
  qs.set("branch_id", String(a.branch_id));
@@ -1144,29 +1226,29 @@ async function main() {
1144
1226
  if (a.status)
1145
1227
  qs.set("status", String(a.status));
1146
1228
  const suffix = qs.toString() ? `?${qs.toString()}` : "";
1147
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/advisors${suffix}`, "GET");
1229
+ const res = await req(`/v1/projects/${encodeURIComponent(project)}/advisors${suffix}`, "GET");
1148
1230
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1149
1231
  }
1150
1232
  case "backwrite_advisors_scan": {
1151
- const project = resolveProject(a.project_id);
1152
- const branch = resolveBranch(a.branch_id);
1153
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/advisors/scan`, "POST", branch ? { branch_id: branch } : {});
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 } : {});
1154
1236
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1155
1237
  }
1156
1238
  case "backwrite_advisors_simulate": {
1157
- const project = resolveProject(a.project_id);
1158
- const branch = resolveBranch(a.branch_id);
1159
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/advisors/${encodeURIComponent(a.finding_id)}/simulate`, "POST", branch ? { branch_id: branch } : {});
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 } : {});
1160
1242
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1161
1243
  }
1162
1244
  case "backwrite_test_connection": {
1163
- const project = resolveProject(a.project_id);
1164
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(a.branch_id)}/studio/connection/test`, "POST", {});
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", {});
1165
1247
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1166
1248
  }
1167
1249
  case "backwrite_simulate_rls_policy": {
1168
- const project = resolveProject(a.project_id);
1169
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(a.branch_id)}/studio/policies/simulate`, "POST", {
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", {
1170
1252
  schema: a.schema || "public",
1171
1253
  table: a.table,
1172
1254
  role: a.role || "authenticated",
@@ -1177,23 +1259,23 @@ async function main() {
1177
1259
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1178
1260
  }
1179
1261
  case "backwrite_list_users": {
1180
- const project = resolveProject(a.project_id);
1262
+ const project = resolveProject(a.project_id, ctx);
1181
1263
  const qs = new URLSearchParams();
1182
1264
  qs.set("source", String(a.source || "all"));
1183
1265
  if (a.search)
1184
1266
  qs.set("search", String(a.search));
1185
1267
  if (typeof a.limit === "number")
1186
1268
  qs.set("limit", String(a.limit));
1187
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(a.branch_id)}/studio/users?${qs.toString()}`, "GET");
1269
+ const res = await req(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(a.branch_id)}/studio/users?${qs.toString()}`, "GET");
1188
1270
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1189
1271
  }
1190
1272
  case "backwrite_list_secrets": {
1191
- const project = resolveProject(a.project_id);
1192
- const res = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/secrets`, "GET");
1273
+ const project = resolveProject(a.project_id, ctx);
1274
+ const res = await req(`/v1/projects/${encodeURIComponent(project)}/secrets`, "GET");
1193
1275
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1194
1276
  }
1195
1277
  case "backwrite_migration_dry_run": {
1196
- const res = await apiRequest(`/v1/migrations/apply`, "POST", {
1278
+ const res = await req(`/v1/migrations/apply`, "POST", {
1197
1279
  branch_id: a.branch_id,
1198
1280
  statements: a.statements,
1199
1281
  dry_run: true,
@@ -1202,19 +1284,19 @@ async function main() {
1202
1284
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1203
1285
  }
1204
1286
  case "backwrite_queue_stats": {
1205
- const res = await apiRequest(`/v1/queues/${encodeURIComponent(a.branch_id)}/${encodeURIComponent(a.queue)}/stats`, "GET");
1287
+ const res = await req(`/v1/queues/${encodeURIComponent(a.branch_id)}/${encodeURIComponent(a.queue)}/stats`, "GET");
1206
1288
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1207
1289
  }
1208
1290
  case "backwrite_cache_get": {
1209
- const res = await apiRequest(`/v1/cache/${encodeURIComponent(a.branch_id)}/entries/${encodeURIComponent(a.key)}`, "GET");
1291
+ const res = await req(`/v1/cache/${encodeURIComponent(a.branch_id)}/entries/${encodeURIComponent(a.key)}`, "GET");
1210
1292
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1211
1293
  }
1212
1294
  case "backwrite_org_usage_limits": {
1213
- const res = await apiRequest(`/v1/organizations/${encodeURIComponent(a.organization_id)}/usage-limits`, "GET");
1295
+ const res = await req(`/v1/organizations/${encodeURIComponent(a.organization_id)}/usage-limits`, "GET");
1214
1296
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1215
1297
  }
1216
1298
  case "backwrite_create_organization": {
1217
- const res = await apiRequest(`/v1/organizations`, "POST", {
1299
+ const res = await req(`/v1/organizations`, "POST", {
1218
1300
  name: a.name,
1219
1301
  plan_tier: a.plan_tier || "free",
1220
1302
  database_engine: a.database_engine || "postgresql",
@@ -1222,7 +1304,7 @@ async function main() {
1222
1304
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1223
1305
  }
1224
1306
  case "backwrite_create_project": {
1225
- const res = await apiRequest(`/v1/projects`, "POST", {
1307
+ const res = await req(`/v1/projects`, "POST", {
1226
1308
  organization_id: a.organization_id,
1227
1309
  name: a.name,
1228
1310
  database_engine: a.database_engine || "postgresql",
@@ -1231,13 +1313,13 @@ async function main() {
1231
1313
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1232
1314
  }
1233
1315
  case "backwrite_spawn_worktree": {
1234
- const project = resolveProject(a.project_id);
1316
+ const project = resolveProject(a.project_id, ctx);
1235
1317
  const slug = slugifyTask(a.task_name);
1236
1318
  const branchName = `agent-${slug}-${Date.now().toString(36).slice(-4)}`;
1237
1319
  const gitBranch = `agent/${slug}`;
1238
1320
  const worktreePath = `.backwrite/worktrees/${branchName}`;
1239
1321
  const baseBranch = a.base_branch || "main";
1240
- const created = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches`, "POST", {
1322
+ const created = await req(`/v1/projects/${encodeURIComponent(project)}/branches`, "POST", {
1241
1323
  name: branchName,
1242
1324
  branch_type: "preview",
1243
1325
  mode: a.mode || "schema-only",
@@ -1269,14 +1351,14 @@ async function main() {
1269
1351
  };
1270
1352
  }
1271
1353
  case "backwrite_sync_schema": {
1272
- const project = resolveProject(a.project_id);
1273
- const branch = resolveBranch(a.branch_id);
1354
+ const project = resolveProject(a.project_id, ctx);
1355
+ const branch = resolveBranch(a.branch_id, ctx);
1274
1356
  if (!branch)
1275
1357
  throw new Error("branch_id is required to sync schema safely on an isolated branch.");
1276
- const queryRes = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`, "POST", { sql: a.sql, view: "raw" });
1358
+ const queryRes = await req(`/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/query`, "POST", { sql: a.sql, view: "raw" });
1277
1359
  let advisors = null;
1278
1360
  if (a.run_advisors !== false) {
1279
- advisors = await apiRequest(`/v1/projects/${encodeURIComponent(project)}/advisors`, "GET").catch((err) => ({ warning: `Advisors check skipped: ${err.message}` }));
1361
+ advisors = await req(`/v1/projects/${encodeURIComponent(project)}/advisors`, "GET").catch((err) => ({ warning: `Advisors check skipped: ${err.message}` }));
1280
1362
  }
1281
1363
  return {
1282
1364
  content: [
@@ -1288,28 +1370,28 @@ async function main() {
1288
1370
  };
1289
1371
  }
1290
1372
  case "backwrite_workspace_lock": {
1291
- const branch = resolveBranch(a.branch_id);
1373
+ const branch = resolveBranch(a.branch_id, ctx);
1292
1374
  if (!branch)
1293
1375
  throw new Error("branch_id is required for distributed lockfile operations.");
1294
1376
  const safePath = String(a.file_path || "").replace(/^\/+/, "");
1295
1377
  if (!safePath || safePath.includes(".."))
1296
1378
  throw new Error("Invalid file_path for lockfile.");
1297
- const lockKey = `bw:lock:${encodeURIComponent(safePath)}`;
1379
+ const lockKey = `backwrite:lock:${encodeURIComponent(safePath)}`;
1298
1380
  const action = String(a.action || "check");
1299
1381
  if (action === "check") {
1300
- const existing = await apiRequest(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "GET").catch(() => null);
1382
+ const existing = await req(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "GET").catch(() => null);
1301
1383
  return {
1302
1384
  content: [{ type: "text", text: JSON.stringify({ file_path: safePath, locked: Boolean(existing?.value), holder: existing || null }, null, 2) }],
1303
1385
  };
1304
1386
  }
1305
1387
  if (action === "release") {
1306
- await apiRequest(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "DELETE").catch(() => ({}));
1388
+ await req(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "DELETE").catch(() => ({}));
1307
1389
  return {
1308
1390
  content: [{ type: "text", text: JSON.stringify({ file_path: safePath, released: true, agent_id: a.agent_id || null }, null, 2) }],
1309
1391
  };
1310
1392
  }
1311
1393
  // acquire: check if another agent already owns the lock
1312
- const current = await apiRequest(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "GET").catch(() => null);
1394
+ const current = await req(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}`, "GET").catch(() => null);
1313
1395
  if (current?.value) {
1314
1396
  try {
1315
1397
  const parsed = typeof current.value === "string" ? JSON.parse(current.value) : current.value;
@@ -1338,16 +1420,16 @@ async function main() {
1338
1420
  file_path: safePath,
1339
1421
  acquired_at: new Date().toISOString(),
1340
1422
  };
1341
- await apiRequest(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}?ttl=${Number(a.ttl_seconds || 600)}`, "PUT", { value: JSON.stringify(lockPayload) });
1423
+ await req(`/v1/cache/${encodeURIComponent(branch)}/entries/${encodeURIComponent(lockKey)}?ttl=${Number(a.ttl_seconds || 600)}`, "PUT", { value: JSON.stringify(lockPayload) });
1342
1424
  return {
1343
1425
  content: [{ type: "text", text: JSON.stringify({ acquired: true, contested: false, ...lockPayload }, null, 2) }],
1344
1426
  };
1345
1427
  }
1346
1428
  case "backwrite_agent_emit_event": {
1347
- const branch = resolveBranch(a.branch_id);
1429
+ const branch = resolveBranch(a.branch_id, ctx);
1348
1430
  if (!branch)
1349
1431
  throw new Error("branch_id is required to stream agent events.");
1350
- const res = await apiRequest(`/v1/realtime/${encodeURIComponent(branch)}/broadcast`, "POST", {
1432
+ const res = await req(`/v1/realtime/${encodeURIComponent(branch)}/broadcast`, "POST", {
1351
1433
  channel: `agent:${a.agent_id}`,
1352
1434
  event: a.event,
1353
1435
  payload: {
@@ -1372,7 +1454,7 @@ async function main() {
1372
1454
  created_at: new Date().toISOString(),
1373
1455
  };
1374
1456
  if (a.branch_id) {
1375
- await apiRequest(`/v1/realtime/${encodeURIComponent(a.branch_id)}/broadcast`, "POST", {
1457
+ await req(`/v1/realtime/${encodeURIComponent(a.branch_id)}/broadcast`, "POST", {
1376
1458
  channel: a.agent_id ? `agent:${a.agent_id}` : "agent:elicitation",
1377
1459
  event: "elicitation_required",
1378
1460
  payload,
@@ -1382,13 +1464,13 @@ async function main() {
1382
1464
  }
1383
1465
  case "backwrite_export_agent_plugin": {
1384
1466
  const project = a.project_id || DEFAULT_PROJECT_ID || "";
1385
- const branch = resolveBranch(a.branch_id);
1467
+ const branch = resolveBranch(a.branch_id, ctx);
1386
1468
  let schemaSnapshot = undefined;
1387
1469
  if (a.include_schema !== false && project) {
1388
1470
  const path = branch
1389
1471
  ? `/v1/projects/${encodeURIComponent(project)}/branches/${encodeURIComponent(branch)}/schema`
1390
1472
  : `/v1/projects/${encodeURIComponent(project)}/schema`;
1391
- schemaSnapshot = await apiRequest(path, "GET").catch(() => undefined);
1473
+ schemaSnapshot = await req(path, "GET").catch(() => undefined);
1392
1474
  }
1393
1475
  const files = buildAgentPluginFiles(String(a.name || "backwrite-agent-plugin"), project, branch, Array.isArray(a.skills) ? a.skills : [], schemaSnapshot);
1394
1476
  return {
@@ -1406,24 +1488,18 @@ async function main() {
1406
1488
  };
1407
1489
  }
1408
1490
  case "backwrite_list_snapshots": {
1409
- const res = await apiRequest(`/v1/branches/${encodeURIComponent(a.branch_id)}/snapshots`, "GET");
1491
+ const res = await req(`/v1/branches/${encodeURIComponent(a.branch_id)}/snapshots`, "GET");
1410
1492
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1411
1493
  }
1412
1494
  case "backwrite_create_snapshot": {
1413
- const res = await apiRequest(`/v1/branches/${encodeURIComponent(a.branch_id)}/snapshot`, "POST", {
1495
+ const res = await req(`/v1/branches/${encodeURIComponent(a.branch_id)}/snapshot`, "POST", {
1414
1496
  label: a.label || `mcp-snap-${Date.now()}`,
1415
1497
  });
1416
1498
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1417
1499
  }
1418
- case "backwrite_delete_branch": {
1419
- const res = await apiRequest(`/v1/branches/${encodeURIComponent(a.branch_id)}`, "DELETE", {
1420
- elevated_approval: false,
1421
- });
1422
- return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1423
- }
1424
1500
  case "backwrite_cache_set": {
1425
1501
  const ttl = Number(a.ttl_seconds || 300);
1426
- const res = await apiRequest(`/v1/cache/${encodeURIComponent(a.branch_id)}/entries/${encodeURIComponent(a.key)}?ttl=${ttl}`, "PUT", { value: a.value });
1502
+ const res = await req(`/v1/cache/${encodeURIComponent(a.branch_id)}/entries/${encodeURIComponent(a.key)}?ttl=${ttl}`, "PUT", { value: a.value });
1427
1503
  return { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] };
1428
1504
  }
1429
1505
  default:
@@ -1437,18 +1513,117 @@ async function main() {
1437
1513
  };
1438
1514
  }
1439
1515
  }
1440
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
1441
- const { name, arguments: args } = request.params;
1442
- return executeTool(name, args || {});
1443
- });
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
+ }
1444
1577
  if (process.argv.includes("--http") || process.env.MCP_HTTP_PORT || process.env.PORT) {
1445
1578
  const port = parseInt(process.env.MCP_HTTP_PORT || process.env.PORT || "8090", 10);
1446
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";
1447
1582
  const corsOrigin = process.env.MCP_CORS_ORIGIN || "https://console.backwrite.dev";
1448
1583
  const MAX_BODY_BYTES = 1_048_576;
1449
1584
  const http = await import("node:http");
1450
- const { SSEServerTransport } = await import("@modelcontextprotocol/sdk/server/sse.js");
1451
- const transports = new Map();
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
+ };
1452
1627
  const httpServer = http.createServer(async (req, res) => {
1453
1628
  res.setHeader("Access-Control-Allow-Origin", corsOrigin);
1454
1629
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
@@ -1466,12 +1641,15 @@ async function main() {
1466
1641
  status: "online",
1467
1642
  server: "backwrite-mcp",
1468
1643
  version: VERSION,
1644
+ protocol_version: PROTOCOL_VERSION,
1469
1645
  transports: ["streamable-http", "sse"],
1470
1646
  mcp_endpoint: "/mcp",
1471
1647
  sse_endpoint: "/sse",
1472
1648
  messages: "/messages",
1473
1649
  tools_endpoint: "/tools",
1474
1650
  tools_count: TOOLS.length,
1651
+ resources_count: RESOURCES.length,
1652
+ prompts_count: PROMPTS.length,
1475
1653
  }));
1476
1654
  return;
1477
1655
  }
@@ -1487,94 +1665,104 @@ async function main() {
1487
1665
  }
1488
1666
  // Stateless Streamable HTTP JSON-RPC 2.0 endpoint (/mcp)
1489
1667
  if (url.pathname === "/mcp" && req.method === "POST") {
1490
- const chunks = [];
1491
- let totalBytes = 0;
1492
- for await (const chunk of req) {
1493
- const buf = Buffer.from(chunk);
1494
- totalBytes += buf.length;
1495
- if (totalBytes > MAX_BODY_BYTES) {
1496
- res.writeHead(413, { "Content-Type": "application/json" });
1497
- res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Request body too large" } }));
1498
- return;
1499
- }
1500
- chunks.push(buf);
1501
- }
1502
- const raw = Buffer.concat(chunks).toString("utf-8");
1503
- let rpc;
1504
- try {
1505
- rpc = JSON.parse(raw || "{}");
1506
- }
1507
- catch {
1508
- res.writeHead(400, { "Content-Type": "application/json" });
1509
- res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }));
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
+ }));
1510
1680
  return;
1511
1681
  }
1512
- const headerAuth = (typeof req.headers.authorization === "string" ? req.headers.authorization : "") ||
1513
- (typeof req.headers.apikey === "string" ? req.headers.apikey : "");
1514
- const apiKey = headerAuth.replace(/^Bearer\s+/i, "").trim() || undefined;
1515
- const id = rpc.id ?? null;
1516
- const method = rpc.method;
1517
- const params = rpc.params || {};
1518
- let result;
1519
- if (method === "initialize") {
1520
- result = {
1521
- protocolVersion: "2026-07-28",
1522
- serverInfo: { name: "backwrite-mcp", version: VERSION },
1523
- capabilities: { tools: {}, resources: {} },
1524
- };
1525
- }
1526
- else if (method === "tools/list") {
1527
- result = { tools: TOOLS };
1528
- }
1529
- else if (method === "tools/call") {
1530
- result = await requestAuthStore.run({ apiKey }, () => executeTool(String(params.name || ""), params.arguments || {}));
1531
- }
1532
- else if (method === "resources/list") {
1533
- result = { resources: RESOURCES };
1534
- }
1535
- else if (method === "resources/read") {
1536
- result = await requestAuthStore.run({ apiKey }, () => readResource(String(params.uri || "")));
1537
- }
1538
- else {
1539
- res.writeHead(200, { "Content-Type": "application/json" });
1540
- 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();
1541
1686
  return;
1542
1687
  }
1543
1688
  res.writeHead(200, { "Content-Type": "application/json" });
1544
- res.end(JSON.stringify({ jsonrpc: "2.0", id, result }));
1689
+ res.end(JSON.stringify(reply));
1545
1690
  return;
1546
1691
  }
1692
+ // Authenticated SSE transport (/sse + /messages?sessionId=...)
1547
1693
  if (url.pathname === "/sse" && req.method === "GET") {
1548
- const transport = new SSEServerTransport("/messages", res);
1549
- const sessionId = transport._sessionId || `sess_${crypto.randomUUID()}`;
1550
- transports.set(sessionId, transport);
1551
- transport.onclose = () => {
1552
- transports.delete(sessionId);
1553
- };
1554
- await server.connect(transport);
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
+ });
1555
1711
  return;
1556
1712
  }
1557
1713
  if (url.pathname === "/messages" && req.method === "POST") {
1558
1714
  const sessionId = url.searchParams.get("sessionId");
1559
- const transport = sessionId ? transports.get(sessionId) : undefined;
1560
- if (!transport) {
1715
+ const session = sessionId ? sseSessions.get(sessionId) : undefined;
1716
+ if (!session) {
1561
1717
  res.writeHead(404, { "Content-Type": "application/json" });
1562
1718
  res.end(JSON.stringify({ error: "Session not found" }));
1563
1719
  return;
1564
1720
  }
1565
- await transport.handlePostMessage(req, res);
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 }));
1566
1737
  return;
1567
1738
  }
1568
1739
  res.writeHead(404, { "Content-Type": "application/json" });
1569
1740
  res.end(JSON.stringify({ error: "Not Found" }));
1570
1741
  });
1571
1742
  httpServer.listen(port, bindHost, () => {
1572
- console.log(`Backwrite MCP Server listening on http://${bindHost}:${port} (SSE /sse, Messages /messages)`);
1743
+ console.log(`Backwrite MCP Server v${VERSION} listening on http://${bindHost}:${port} (/mcp, /sse, /messages)`);
1573
1744
  });
1574
1745
  }
1575
1746
  else {
1576
- const transport = new StdioServerTransport();
1577
- await server.connect(transport);
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
+ });
1578
1766
  }
1579
1767
  }
1580
1768
  main().catch((error) => {