@constructorfleet/sketchforge3d 1.31.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,6 +38,11 @@ and only files already sitting in `SKETCHFORGE_MACRO_DIR`. There is deliberately
38
38
  no tool that accepts code to run. A Python macro needs `sketchforge3d` installed
39
39
  from PyPI, since only a checkout carries the Python source.
40
40
 
41
+ A SketchForge server also answers MCP itself, at `/mcp`, for clients that connect
42
+ to a URL rather than start a process. That endpoint is part of the server, not of
43
+ this package; see the
44
+ [MCP endpoint guide](https://github.com/constructorfleet/SketchForge-3D/blob/main/docs/guides/deployment.md#mcp-endpoint).
45
+
41
46
  ## Connecting
42
47
 
43
48
  ```ts
@@ -3,7 +3,7 @@ import { mkdir, realpath } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
 
5
5
  function configuredRoot() {
6
- return process.env.SKETCHFORGE_MCP_FILES_DIR || process.env.SKETCHFORGE_PROJECTS_DIR;
6
+ return process.env.SKETCHFORGE_MCP_FILES_DIR?.trim() || process.env.SKETCHFORGE_PROJECTS_DIR?.trim();
7
7
  }
8
8
 
9
9
  function isWithin(root, target) {
@@ -42,7 +42,14 @@ function requireWithin(root, target) {
42
42
  export async function resolveMcpReadPath(value) {
43
43
  const requested = path.resolve(String(value ?? ""));
44
44
  const root = await getRoot();
45
- const resolved = await realpath(requested);
45
+ let resolved;
46
+ try {
47
+ resolved = await realpath(requested);
48
+ } catch (error) {
49
+ // Hides whether a path outside the root exists.
50
+ if (root && ["ENOENT", "ENOTDIR"].includes(error?.code)) requireWithin(root, await resolveThroughExistingAncestor(requested));
51
+ throw error;
52
+ }
46
53
  return root ? requireWithin(root, resolved) : resolved;
47
54
  }
48
55
 
@@ -0,0 +1,9 @@
1
+ export interface McpTool {
2
+ name: string;
3
+ description: string;
4
+ inputSchema: { type: string; properties?: Record<string, unknown>; required?: string[] };
5
+ }
6
+
7
+ export declare const hostedTools: readonly McpTool[];
8
+ export declare function callHostedTool(name: string, args?: Record<string, unknown>): Promise<unknown>;
9
+ export declare function createHostedMcpHandler(options?: { version?: string }): (request: Request) => Promise<Response>;
package/mcp/hosted.mjs ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Exposes stored-project tools over HTTP. Withholds editor tools, the
3
+ * process-wide selection, macros, and `url` (server-side request forgery).
4
+ */
5
+
6
+ import { realpathSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { callLocalEngineTool } from "./localEngine.mjs";
9
+ import { createDispatcher } from "./protocol.mjs";
10
+ import { engineTools } from "./toolCatalog.mjs";
11
+ import { createStreamableHttpHandler } from "./streamableHttp.mjs";
12
+
13
+ const WITHHELD_TOOLS = new Set(["sketchforge_list_editors", "sketchforge_inspect_errors", "sketchforge_select_objects"]);
14
+ const WITHHELD_PROPERTIES = ["url", "editorNumber", "editorId", "timeoutMs"];
15
+
16
+ function withoutTargeting(tool) {
17
+ const properties = { ...tool.inputSchema.properties };
18
+ for (const property of WITHHELD_PROPERTIES) delete properties[property];
19
+ return { ...tool, inputSchema: { ...tool.inputSchema, properties } };
20
+ }
21
+
22
+ export const hostedTools = engineTools.filter(({ name }) => !WITHHELD_TOOLS.has(name)).map(withoutTargeting);
23
+
24
+ const hostedToolNames = new Set(hostedTools.map(({ name }) => name));
25
+
26
+ // Same rule as `/api/v1`: the id becomes a file name in the project directory.
27
+ const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,119}$/;
28
+ const PATH_ARGUMENTS = ["filePath", "outputPath"];
29
+
30
+ /** Resolves symlinks in the deepest ancestor that exists; the rest may not exist yet. */
31
+ function physicalPath(value) {
32
+ let candidate = path.resolve(value);
33
+ const missing = [];
34
+ for (;;) {
35
+ try {
36
+ return path.join(realpathSync(candidate), ...missing);
37
+ } catch {
38
+ const parent = path.dirname(candidate);
39
+ if (parent === candidate) return path.resolve(value);
40
+ missing.unshift(path.basename(candidate));
41
+ candidate = parent;
42
+ }
43
+ }
44
+ }
45
+
46
+ function contains(parent, child) {
47
+ const relative = path.relative(parent, child);
48
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
49
+ }
50
+
51
+ /** Rejects host paths that could reach stored projects or their lock files. */
52
+ function requireSeparateFilesRoot() {
53
+ const files = process.env.SKETCHFORGE_MCP_FILES_DIR?.trim();
54
+ const projects = process.env.SKETCHFORGE_PROJECTS_DIR?.trim();
55
+ if (files && projects) {
56
+ const [filesRoot, projectsRoot] = [physicalPath(files), physicalPath(projects)];
57
+ if (!contains(filesRoot, projectsRoot) && !contains(projectsRoot, filesRoot)) return;
58
+ }
59
+ throw new Error("filePath and outputPath need SKETCHFORGE_MCP_FILES_DIR set on the server to a directory apart from SKETCHFORGE_PROJECTS_DIR. Omit outputPath to receive an export in the result.");
60
+ }
61
+
62
+ export async function callHostedTool(name, args = {}) {
63
+ if (!hostedToolNames.has(name)) throw new Error(`Unknown tool: ${name}`);
64
+ const input = args ?? {};
65
+ if (input.url !== undefined) throw new Error("url is not accepted here: this endpoint works on its own server's projects.");
66
+ if (input.projectId !== undefined && !(typeof input.projectId === "string" && PROJECT_ID.test(input.projectId))) {
67
+ throw new Error("projectId must be a project id from sketchforge_list_projects: letters, digits, hyphens and underscores.");
68
+ }
69
+ if (PATH_ARGUMENTS.some((key) => input[key] !== undefined)) requireSeparateFilesRoot();
70
+ return callLocalEngineTool(name, input);
71
+ }
72
+
73
+ /** Builds the Streamable HTTP handler. Authorize each request before calling it. */
74
+ export function createHostedMcpHandler({ version } = {}) {
75
+ return createStreamableHttpHandler({
76
+ dispatch: createDispatcher({ tools: hostedTools, callTool: callHostedTool, version }),
77
+ });
78
+ }
@@ -6,19 +6,20 @@ import { resolveMcpReadPath, resolveMcpWritePath } from "./filesystemPaths.mjs";
6
6
 
7
7
  // SKETCHFORGE_MCP_FILES_DIR is resolved by the shared MCP filesystem path policy.
8
8
 
9
- const projectsDir = process.env.SKETCHFORGE_PROJECTS_DIR;
10
9
  let backend;
11
10
  let enginePackagePromise;
12
11
  let selectedObjectIds = [];
13
12
 
14
13
  async function getBackend() {
14
+ // Read per call: a long-lived host process may configure storage after import.
15
+ const projectsDir = process.env.SKETCHFORGE_PROJECTS_DIR?.trim();
15
16
  if (!projectsDir) throw new Error("Set SKETCHFORGE_PROJECTS_DIR to a directory containing SketchForge project files.");
16
- if (!backend) {
17
+ if (backend?.projectsDir !== projectsDir) {
17
18
  enginePackagePromise ??= import("@constructorfleet/sketchforge-engine");
18
19
  await mkdir(projectsDir, { recursive: true });
19
20
  const { createEngine, directoryProjectStore } = await enginePackagePromise;
20
21
  const store = directoryProjectStore(projectsDir);
21
- backend = { store, engine: createEngine(store), package: await enginePackagePromise };
22
+ backend = { projectsDir, store, engine: createEngine(store), package: await enginePackagePromise };
22
23
  }
23
24
  return backend;
24
25
  }
@@ -310,7 +311,7 @@ async function callLocalEngineToolRaw(name, args = {}) {
310
311
  if (["sketchforge_list_editors", "sketchforge_inspect_errors"].includes(name)) {
311
312
  throw new Error(`${name} needs an open SketchForge editor and is unavailable in local mode.`);
312
313
  }
313
- const { engine, package: enginePackage } = await getBackend();
314
+ const { engine, package: enginePackage, projectsDir } = await getBackend();
314
315
  if (name === "sketchforge_list_projects") {
315
316
  const projects = await Promise.all((await backend.store.list()).map(async (record) => {
316
317
  const project = await unwrap(await engine.project(record.projectId));
@@ -0,0 +1,87 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ /**
5
+ * The version this bridge reports is the package's, read at startup rather than
6
+ * written here: it ships inside `@constructorfleet/sketchforge3d`, whose version
7
+ * tracks the app's, and a client that logs a hand-written number would say
8
+ * something untrue after the first release.
9
+ */
10
+ const packageVersion = (() => {
11
+ try {
12
+ const manifest = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
13
+ const parsed = JSON.parse(readFileSync(manifest, "utf8"));
14
+ return typeof parsed.version === "string" ? parsed.version : "0.0.0";
15
+ } catch {
16
+ return "0.0.0";
17
+ }
18
+ })();
19
+
20
+ function textContent(value) {
21
+ return {
22
+ type: "text",
23
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2),
24
+ };
25
+ }
26
+
27
+ export function toolResult(value) {
28
+ if (value?.dataUrl?.startsWith?.("data:image/png;base64,")) {
29
+ return {
30
+ content: [
31
+ textContent({ face: value.face, ...(value.view === undefined ? {} : { view: value.view }), bytesApprox: value.bytesApprox }),
32
+ {
33
+ type: "image",
34
+ data: value.dataUrl.slice("data:image/png;base64,".length),
35
+ mimeType: "image/png",
36
+ },
37
+ ],
38
+ };
39
+ }
40
+ return { content: [textContent(value)] };
41
+ }
42
+
43
+ /** Lists newest first; initialize falls back to the first entry. */
44
+ export const SUPPORTED_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
45
+
46
+ function rpcResult(id, result) {
47
+ return { jsonrpc: "2.0", id, result };
48
+ }
49
+
50
+ export function rpcError(id, code, message) {
51
+ return { jsonrpc: "2.0", id, error: { code, message } };
52
+ }
53
+
54
+ /**
55
+ * Builds the JSON-RPC handler shared by every transport; resolves undefined for notifications.
56
+ * Pass `version` when the package manifest is not on disk.
57
+ */
58
+ export function createDispatcher({ tools, callTool, version = packageVersion }) {
59
+ return async function dispatch(message) {
60
+ if (!message || typeof message !== "object") return undefined;
61
+ const { id, method, params } = message;
62
+ if (id === undefined || id === null) return undefined;
63
+ try {
64
+ if (method === "initialize") {
65
+ const requested = params?.protocolVersion;
66
+ return rpcResult(id, {
67
+ protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : SUPPORTED_PROTOCOL_VERSIONS[0],
68
+ capabilities: { tools: {} },
69
+ serverInfo: { name: "sketchforge-mcp", version },
70
+ });
71
+ }
72
+ if (method === "ping") return rpcResult(id, {});
73
+ if (method === "tools/list") return rpcResult(id, { tools });
74
+ if (method === "tools/call") {
75
+ const name = params?.name;
76
+ if (typeof name !== "string") return rpcError(id, -32602, "Expected tool name");
77
+ return rpcResult(id, toolResult(await callTool(name, params?.arguments || {})));
78
+ }
79
+ if (method === "resources/list") return rpcResult(id, { resources: [] });
80
+ return rpcError(id, -32601, `Unknown method: ${method}`);
81
+ } catch (error) {
82
+ const text = error instanceof Error ? error.message : String(error);
83
+ if (method === "tools/call") return rpcResult(id, { isError: true, content: [textContent(text)] });
84
+ return rpcError(id, -32000, text);
85
+ }
86
+ };
87
+ }