@powerhousedao/reactor-mcp 6.2.3-dev.24 → 6.2.3-dev.26

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/cli.d.mts CHANGED
@@ -1 +1,2 @@
1
- export { };
1
+ export {}
2
+ export {};
package/dist/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as logger, t as createServer$1 } from "./server-Dtbb-8Dy.mjs";
1
+ import { n as logger, t as createServer$1 } from "./server-CT8k24iS.mjs";
2
2
  import { childLogger, documentModelDocumentModelModule } from "document-model";
3
3
  import { ReactorBuilder, ReactorClientBuilder } from "@powerhousedao/reactor";
4
4
  import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":["createServer"],"sources":["../src/feature-flags.ts","../src/stdio/loader.ts","../src/stdio/index.ts","../src/cli.ts"],"sourcesContent":["import { EnvVarProvider } from \"@openfeature/env-var-provider\";\nimport { OpenFeature } from \"@openfeature/server-sdk\";\n\nexport async function initFeatureFlags() {\n // for now, we're only using env vars for feature flags\n const provider = new EnvVarProvider();\n\n await OpenFeature.setProviderAndWait(provider);\n\n return OpenFeature.getClient();\n}\n","import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { childLogger } from \"document-model\";\nimport { access } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\nimport { createServer } from \"vite\";\n\ninterface IPackageLoader {\n load(): Promise<DocumentModelModule[]>;\n onDocumentModelsChange(\n callback: (models: DocumentModelModule[]) => void,\n ): Promise<() => void>;\n}\n\nfunction debounce<T extends (...args: any[]) => void>(\n func: T,\n delay = 100,\n): (...args: Parameters<T>) => void {\n let timeoutId: ReturnType<typeof setTimeout>;\n return (...args: Parameters<T>): void => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => func(...args), delay);\n };\n}\n\nfunction isSubpath(parent: string, dir: string) {\n const relative = path.relative(parent, dir);\n return relative && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n\nexport class VitePackageLoader implements IPackageLoader {\n private readonly logger = childLogger([\"reactor-mcp\", \"vite-loader\"]);\n\n private readonly root: string;\n private readonly documentModelsDir: string;\n\n private vite: ViteDevServer | undefined;\n\n readonly name = \"VitePackageLoader\";\n\n constructor(root: string, documentModelsDir: string) {\n this.root = root;\n this.documentModelsDir = documentModelsDir;\n }\n\n private get fullPath(): string {\n return path.join(this.root, this.documentModelsDir);\n }\n\n private async initVite() {\n if (this.vite) {\n return this.vite;\n }\n\n this.vite = await createServer({\n root: this.root,\n logLevel: \"info\",\n server: {\n hmr: false,\n middlewareMode: true,\n warmup: {\n ssrFiles: [this.fullPath],\n },\n fs: {\n allow: [this.fullPath],\n },\n },\n optimizeDeps: {\n // It's recommended to disable deps optimization\n noDiscovery: true,\n include: [],\n },\n });\n\n return this.vite;\n }\n\n async load(): Promise<DocumentModelModule[]> {\n const vite = await this.initVite();\n\n await access(this.fullPath);\n this.logger.verbose(\"Loading document models from @path\", this.fullPath);\n\n try {\n const localDMs = (await vite.ssrLoadModule(this.fullPath)) as Record<\n string,\n DocumentModelModule\n >;\n\n const exports = Object.values(localDMs);\n\n // duck type\n const documentModels: DocumentModelModule[] = [];\n for (const dm of exports) {\n if (dm.documentModel) {\n documentModels.push(dm);\n }\n }\n\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${this.fullPath}`,\n );\n\n return documentModels;\n } catch (e) {\n this.logger.verbose(\n ` ➜ No Document Models found for: ${this.fullPath}${e ? `\\n${JSON.stringify(e)}` : \"\"}`,\n );\n }\n\n return [];\n }\n\n async onDocumentModelsChange(\n callback: (models: DocumentModelModule[]) => void,\n ) {\n const vite = await this.initVite();\n const listener = debounce(async (changedPath: string) => {\n if (isSubpath(this.fullPath, changedPath)) {\n const documentModels = await this.load();\n callback(documentModels);\n }\n }, 100);\n vite.watcher.on(\"change\", listener);\n\n return () => {\n vite.watcher.off(\"change\", listener);\n };\n }\n}\n","import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { ReactorBuilder, ReactorClientBuilder } from \"@powerhousedao/reactor\";\nimport { reactorDriveDocumentModelModule } from \"@powerhousedao/reactor-drive\";\nimport { ReactorGroupV1 } from \"@powerhousedao/reactor-group\";\nimport { driveDocumentModelModule } from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"document-model\";\nimport { initFeatureFlags } from \"../feature-flags.js\";\nimport { logger } from \"../logger.js\";\nimport { createServer } from \"../server.js\";\nimport { VitePackageLoader } from \"./loader.js\";\n\nexport interface IMcpOptions {\n remoteDrive?: string;\n root?: string;\n documentModelsDir?: string;\n}\n\nconst baseDocumentModels: DocumentModelModule<any>[] = [\n documentModelDocumentModelModule,\n driveDocumentModelModule,\n reactorDriveDocumentModelModule,\n ReactorGroupV1 as unknown as DocumentModelModule<any>,\n];\n\nasync function createReactorClient(documentModels: DocumentModelModule[]) {\n const reactorBuilder = new ReactorBuilder().withDocumentModelSources(\n baseDocumentModels.concat(documentModels),\n );\n\n const module = await new ReactorClientBuilder()\n .withReactorBuilder(reactorBuilder)\n .buildModule();\n\n return module;\n}\n\nexport async function initStdioMcpServer(options?: IMcpOptions) {\n const {\n remoteDrive,\n root,\n documentModelsDir = \"./document-models\",\n } = options ?? {};\n\n // initialize feature flags\n await initFeatureFlags();\n\n // if root of project is passed then loads local document models\n let documentModelsLoader: VitePackageLoader | undefined;\n const documentModels: DocumentModelModule[] = [];\n\n if (root) {\n documentModelsLoader = new VitePackageLoader(root, documentModelsDir);\n try {\n const loadedModels = await documentModelsLoader.load();\n documentModels.push(...loadedModels);\n logger.info(\n \"Loaded document models: @models\",\n loadedModels.map((m) => m.documentModel.global.name).join(\", \"),\n );\n } catch (e) {\n logger.error(\"@error\", e);\n }\n }\n\n // initializes reactor client with loaded document models\n const reactorModule = await createReactorClient(documentModels);\n const { client, reactor, reactorModule: rModule } = reactorModule;\n\n // listens for changes in the local document models to update the reactor\n if (documentModelsLoader && rModule?.documentModelRegistry) {\n const unsubscribe = await documentModelsLoader.onDocumentModelsChange(\n (models) => {\n const results = rModule.documentModelRegistry.registerModules(\n ...baseDocumentModels.concat(models),\n );\n for (const result of results) {\n if (result.status === \"error\") {\n logger.error(\n \"Failed to register document model: @error\",\n result.error,\n );\n }\n }\n },\n );\n\n process.on(\"exit\", () => {\n unsubscribe();\n reactor.kill();\n });\n }\n\n // if a remote drive is passed, log a warning since remote drives\n // are now handled at a different level (SyncManager)\n if (remoteDrive) {\n logger.warn(\n \"Remote drive configuration via MCP is not supported in the new reactor. \" +\n \"Remote drives should be configured at the server level.\",\n );\n }\n\n // starts the server\n // Note: syncManager is not available in stdio mode currently\n const server = await createServer({ client });\n\n // starts Stdio transport\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","import { logger } from \"./logger.js\";\nimport { initStdioMcpServer } from \"./stdio/index.js\";\n\ninitStdioMcpServer({\n remoteDrive: process.argv.at(2),\n root: process.cwd(),\n}).catch((error: unknown) => {\n logger.error(\"@error\", error);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;AAGA,eAAsB,mBAAmB;CAEvC,MAAM,WAAW,IAAI,gBAAgB;AAErC,OAAM,YAAY,mBAAmB,SAAS;AAE9C,QAAO,YAAY,WAAW;;;;ACKhC,SAAS,SACP,MACA,QAAQ,KAC0B;CAClC,IAAI;AACJ,SAAQ,GAAG,SAA8B;AACvC,eAAa,UAAU;AACvB,cAAY,iBAAiB,KAAK,GAAG,KAAK,EAAE,MAAM;;;AAItD,SAAS,UAAU,QAAgB,KAAa;CAC9C,MAAM,WAAW,KAAK,SAAS,QAAQ,IAAI;AAC3C,QAAO,YAAY,CAAC,SAAS,WAAW,KAAK,IAAI,CAAC,KAAK,WAAW,SAAS;;AAG7E,IAAa,oBAAb,MAAyD;CACvD,SAA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AAO,QAAQ,UAAU;;;;ACzGjC,mBAAmB;CACjB,aAAa,QAAQ,KAAK,GAAG,EAAE;CAC/B,MAAM,QAAQ,KAAK;CACpB,CAAC,CAAC,OAAO,UAAmB;AAC3B,QAAO,MAAM,UAAU,MAAM;AAC7B,SAAQ,KAAK,EAAE;EACf"}
1
+ {"version":3,"file":"cli.mjs","names":["createServer"],"sources":["../src/feature-flags.ts","../src/stdio/loader.ts","../src/stdio/index.ts","../src/cli.ts"],"sourcesContent":["import { EnvVarProvider } from \"@openfeature/env-var-provider\";\nimport { OpenFeature } from \"@openfeature/server-sdk\";\n\nexport async function initFeatureFlags() {\n // for now, we're only using env vars for feature flags\n const provider = new EnvVarProvider();\n\n await OpenFeature.setProviderAndWait(provider);\n\n return OpenFeature.getClient();\n}\n","import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { childLogger } from \"document-model\";\nimport { access } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\nimport { createServer } from \"vite\";\n\ninterface IPackageLoader {\n load(): Promise<DocumentModelModule[]>;\n onDocumentModelsChange(\n callback: (models: DocumentModelModule[]) => void,\n ): Promise<() => void>;\n}\n\nfunction debounce<T extends (...args: any[]) => void>(\n func: T,\n delay = 100,\n): (...args: Parameters<T>) => void {\n let timeoutId: ReturnType<typeof setTimeout>;\n return (...args: Parameters<T>): void => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => func(...args), delay);\n };\n}\n\nfunction isSubpath(parent: string, dir: string) {\n const relative = path.relative(parent, dir);\n return relative && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n\nexport class VitePackageLoader implements IPackageLoader {\n private readonly logger = childLogger([\"reactor-mcp\", \"vite-loader\"]);\n\n private readonly root: string;\n private readonly documentModelsDir: string;\n\n private vite: ViteDevServer | undefined;\n\n readonly name = \"VitePackageLoader\";\n\n constructor(root: string, documentModelsDir: string) {\n this.root = root;\n this.documentModelsDir = documentModelsDir;\n }\n\n private get fullPath(): string {\n return path.join(this.root, this.documentModelsDir);\n }\n\n private async initVite() {\n if (this.vite) {\n return this.vite;\n }\n\n this.vite = await createServer({\n root: this.root,\n logLevel: \"info\",\n server: {\n hmr: false,\n middlewareMode: true,\n warmup: {\n ssrFiles: [this.fullPath],\n },\n fs: {\n allow: [this.fullPath],\n },\n },\n optimizeDeps: {\n // It's recommended to disable deps optimization\n noDiscovery: true,\n include: [],\n },\n });\n\n return this.vite;\n }\n\n async load(): Promise<DocumentModelModule[]> {\n const vite = await this.initVite();\n\n await access(this.fullPath);\n this.logger.verbose(\"Loading document models from @path\", this.fullPath);\n\n try {\n const localDMs = (await vite.ssrLoadModule(this.fullPath)) as Record<\n string,\n DocumentModelModule\n >;\n\n const exports = Object.values(localDMs);\n\n // duck type\n const documentModels: DocumentModelModule[] = [];\n for (const dm of exports) {\n if (dm.documentModel) {\n documentModels.push(dm);\n }\n }\n\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${this.fullPath}`,\n );\n\n return documentModels;\n } catch (e) {\n this.logger.verbose(\n ` ➜ No Document Models found for: ${this.fullPath}${e ? `\\n${JSON.stringify(e)}` : \"\"}`,\n );\n }\n\n return [];\n }\n\n async onDocumentModelsChange(\n callback: (models: DocumentModelModule[]) => void,\n ) {\n const vite = await this.initVite();\n const listener = debounce(async (changedPath: string) => {\n if (isSubpath(this.fullPath, changedPath)) {\n const documentModels = await this.load();\n callback(documentModels);\n }\n }, 100);\n vite.watcher.on(\"change\", listener);\n\n return () => {\n vite.watcher.off(\"change\", listener);\n };\n }\n}\n","import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { ReactorBuilder, ReactorClientBuilder } from \"@powerhousedao/reactor\";\nimport { reactorDriveDocumentModelModule } from \"@powerhousedao/reactor-drive\";\nimport { ReactorGroupV1 } from \"@powerhousedao/reactor-group\";\nimport { driveDocumentModelModule } from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"document-model\";\nimport { initFeatureFlags } from \"../feature-flags.js\";\nimport { logger } from \"../logger.js\";\nimport { createServer } from \"../server.js\";\nimport { VitePackageLoader } from \"./loader.js\";\n\nexport interface IMcpOptions {\n remoteDrive?: string;\n root?: string;\n documentModelsDir?: string;\n}\n\nconst baseDocumentModels: DocumentModelModule<any>[] = [\n documentModelDocumentModelModule,\n driveDocumentModelModule,\n reactorDriveDocumentModelModule,\n ReactorGroupV1 as unknown as DocumentModelModule<any>,\n];\n\nasync function createReactorClient(documentModels: DocumentModelModule[]) {\n const reactorBuilder = new ReactorBuilder().withDocumentModelSources(\n baseDocumentModels.concat(documentModels),\n );\n\n const module = await new ReactorClientBuilder()\n .withReactorBuilder(reactorBuilder)\n .buildModule();\n\n return module;\n}\n\nexport async function initStdioMcpServer(options?: IMcpOptions) {\n const {\n remoteDrive,\n root,\n documentModelsDir = \"./document-models\",\n } = options ?? {};\n\n // initialize feature flags\n await initFeatureFlags();\n\n // if root of project is passed then loads local document models\n let documentModelsLoader: VitePackageLoader | undefined;\n const documentModels: DocumentModelModule[] = [];\n\n if (root) {\n documentModelsLoader = new VitePackageLoader(root, documentModelsDir);\n try {\n const loadedModels = await documentModelsLoader.load();\n documentModels.push(...loadedModels);\n logger.info(\n \"Loaded document models: @models\",\n loadedModels.map((m) => m.documentModel.global.name).join(\", \"),\n );\n } catch (e) {\n logger.error(\"@error\", e);\n }\n }\n\n // initializes reactor client with loaded document models\n const reactorModule = await createReactorClient(documentModels);\n const { client, reactor, reactorModule: rModule } = reactorModule;\n\n // listens for changes in the local document models to update the reactor\n if (documentModelsLoader && rModule?.documentModelRegistry) {\n const unsubscribe = await documentModelsLoader.onDocumentModelsChange(\n (models) => {\n const results = rModule.documentModelRegistry.registerModules(\n ...baseDocumentModels.concat(models),\n );\n for (const result of results) {\n if (result.status === \"error\") {\n logger.error(\n \"Failed to register document model: @error\",\n result.error,\n );\n }\n }\n },\n );\n\n process.on(\"exit\", () => {\n unsubscribe();\n reactor.kill();\n });\n }\n\n // if a remote drive is passed, log a warning since remote drives\n // are now handled at a different level (SyncManager)\n if (remoteDrive) {\n logger.warn(\n \"Remote drive configuration via MCP is not supported in the new reactor. \" +\n \"Remote drives should be configured at the server level.\",\n );\n }\n\n // starts the server\n // Note: syncManager is not available in stdio mode currently\n const server = await createServer({ client });\n\n // starts Stdio transport\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","import { logger } from \"./logger.js\";\nimport { initStdioMcpServer } from \"./stdio/index.js\";\n\ninitStdioMcpServer({\n remoteDrive: process.argv.at(2),\n root: process.cwd(),\n}).catch((error: unknown) => {\n logger.error(\"@error\", error);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;AAGA,eAAsB,mBAAmB;CAEvC,MAAM,WAAW,IAAI,eAAe;CAEpC,MAAM,YAAY,mBAAmB,QAAQ;CAE7C,OAAO,YAAY,UAAU;AAC/B;;;ACIA,SAAS,SACP,MACA,QAAQ,KAC0B;CAClC,IAAI;CACJ,QAAQ,GAAG,SAA8B;EACvC,aAAa,SAAS;EACtB,YAAY,iBAAiB,KAAK,GAAG,IAAI,GAAG,KAAK;CACnD;AACF;AAEA,SAAS,UAAU,QAAgB,KAAa;CAC9C,MAAM,WAAW,KAAK,SAAS,QAAQ,GAAG;CAC1C,OAAO,YAAY,CAAC,SAAS,WAAW,IAAI,KAAK,CAAC,KAAK,WAAW,QAAQ;AAC5E;AAEA,IAAa,oBAAb,MAAyD;CACvD,SAA0B,YAAY,CAAC,eAAe,aAAa,CAAC;CAEpE;CACA;CAEA;CAEA,OAAgB;CAEhB,YAAY,MAAc,mBAA2B;EACnD,KAAK,OAAO;EACZ,KAAK,oBAAoB;CAC3B;CAEA,IAAY,WAAmB;EAC7B,OAAO,KAAK,KAAK,KAAK,MAAM,KAAK,iBAAiB;CACpD;CAEA,MAAc,WAAW;EACvB,IAAI,KAAK,MACP,OAAO,KAAK;EAGd,KAAK,OA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;CAC5B,QAAQ,KAAK,CAAC;AAChB,CAAC"}
@@ -1,10 +1,8 @@
1
1
  import { ToolCallback } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { IReactorClient, ISyncManager } from "@powerhousedao/reactor";
3
- import { Action, DocumentModelModule } from "@powerhousedao/shared/document-model";
3
+ import { Action, AuthSubject, DocumentModelModule } from "@powerhousedao/shared/document-model";
4
4
  import { ZodRawShape, z } from "zod";
5
- import * as _modelcontextprotocol_sdk_types0 from "@modelcontextprotocol/sdk/types";
6
5
  import { CallToolResult, Prompt, Resource, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
7
-
8
6
  //#region src/tools/types.d.ts
9
7
  type ExtractCallbackFromTool<T extends ToolSchema> = T extends {
10
8
  inputSchema: infer S;
@@ -31,10 +29,18 @@ interface IMcpProvider<T extends ToolWithCallback = ToolWithCallback, R extends
31
29
  type ReactorMcpProviderOptions = {
32
30
  client: IReactorClient;
33
31
  syncManager?: ISyncManager;
32
+ /**
33
+ * Who the tools read as. A server shared by many callers must set it, an
34
+ * anonymous one to an empty subject. Omitted, reads fall back to the
35
+ * client's signer, which only a single-user local reactor should rely on.
36
+ */
37
+ subject?: AuthSubject;
34
38
  };
35
39
  declare const createDocumentTool: {
36
40
  readonly name: "createDocument";
37
- readonly description: "Create a new document.\n Unless the user specifies otherwise, and a drive named \"vetra\" is available, add the document to that drive by providing the drive's ID in the \"driveId\" parameter.\n When \"driveId\" is provided, the document is created and added to the drive atomically — no separate \"addActions\" call with \"ADD_FILE\" is needed.";
41
+ readonly description: `Create a new document.
42
+ Unless the user specifies otherwise, and a drive named "vetra" is available, add the document to that drive by providing the drive's ID in the "driveId" parameter.
43
+ When "driveId" is provided, the document is created and added to the drive atomically — no separate "addActions" call with "ADD_FILE" is needed.`;
38
44
  readonly inputSchema: {
39
45
  readonly documentType: z.ZodString;
40
46
  readonly name: z.ZodOptional<z.ZodString>;
@@ -191,7 +197,7 @@ declare const getDocumentModelsTool: {
191
197
  };
192
198
  type ToolRecord<T extends readonly ToolSchema[]> = { [K in T[number]["name"]]: ToolWithCallback<Extract<T[number], {
193
199
  name: K;
194
- }>> };
200
+ }>>; };
195
201
  declare const _allTools: readonly [{
196
202
  readonly name: "getDocument";
197
203
  readonly description: "Retrieve a document by its ID";
@@ -203,7 +209,9 @@ declare const _allTools: readonly [{
203
209
  };
204
210
  }, {
205
211
  readonly name: "createDocument";
206
- readonly description: "Create a new document.\n Unless the user specifies otherwise, and a drive named \"vetra\" is available, add the document to that drive by providing the drive's ID in the \"driveId\" parameter.\n When \"driveId\" is provided, the document is created and added to the drive atomically — no separate \"addActions\" call with \"ADD_FILE\" is needed.";
212
+ readonly description: `Create a new document.
213
+ Unless the user specifies otherwise, and a drive named "vetra" is available, add the document to that drive by providing the drive's ID in the "driveId" parameter.
214
+ When "driveId" is provided, the document is created and added to the drive atomically — no separate "addActions" call with "ADD_FILE" is needed.`;
207
215
  readonly inputSchema: {
208
216
  readonly documentType: z.ZodString;
209
217
  readonly name: z.ZodOptional<z.ZodString>;
@@ -353,11 +361,13 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
353
361
  } & {
354
362
  callback: (args: {
355
363
  id: string;
356
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
364
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
357
365
  };
358
366
  readonly createDocument: {
359
367
  readonly name: "createDocument";
360
- readonly description: "Create a new document.\n Unless the user specifies otherwise, and a drive named \"vetra\" is available, add the document to that drive by providing the drive's ID in the \"driveId\" parameter.\n When \"driveId\" is provided, the document is created and added to the drive atomically — no separate \"addActions\" call with \"ADD_FILE\" is needed.";
368
+ readonly description: `Create a new document.
369
+ Unless the user specifies otherwise, and a drive named "vetra" is available, add the document to that drive by providing the drive's ID in the "driveId" parameter.
370
+ When "driveId" is provided, the document is created and added to the drive atomically — no separate "addActions" call with "ADD_FILE" is needed.`;
361
371
  readonly inputSchema: {
362
372
  readonly documentType: z.ZodString;
363
373
  readonly name: z.ZodOptional<z.ZodString>;
@@ -373,7 +383,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
373
383
  name?: string | undefined;
374
384
  driveId?: string | undefined;
375
385
  parentFolder?: string | undefined;
376
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
386
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
377
387
  };
378
388
  readonly getDocuments: {
379
389
  readonly name: "getDocuments";
@@ -387,7 +397,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
387
397
  } & {
388
398
  callback: (args: {
389
399
  parentId: string;
390
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
400
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
391
401
  };
392
402
  readonly deleteDocument: {
393
403
  readonly name: "deleteDocument";
@@ -401,7 +411,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
401
411
  } & {
402
412
  callback: (args: {
403
413
  documentId: string;
404
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
414
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
405
415
  };
406
416
  readonly addActions: {
407
417
  readonly name: "addActions";
@@ -427,7 +437,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
427
437
  scope: string;
428
438
  context?: Record<string, unknown> | undefined;
429
439
  }[];
430
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
440
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
431
441
  };
432
442
  readonly getDrives: {
433
443
  readonly name: "getDrives";
@@ -437,7 +447,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
437
447
  readonly driveIds: z.ZodArray<z.ZodString>;
438
448
  };
439
449
  } & {
440
- callback: (args: Record<string, never>) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
450
+ callback: (args: Record<string, never>) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
441
451
  };
442
452
  readonly addDrive: {
443
453
  readonly name: "addDrive";
@@ -471,7 +481,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
471
481
  sharingType?: string | null | undefined;
472
482
  } | undefined;
473
483
  };
474
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
484
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
475
485
  };
476
486
  readonly getDrive: {
477
487
  readonly name: "getDrive";
@@ -493,7 +503,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
493
503
  revisions?: Record<string, number> | undefined;
494
504
  checkHashes?: boolean | undefined;
495
505
  } | undefined;
496
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
506
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
497
507
  };
498
508
  readonly deleteDrive: {
499
509
  readonly name: "deleteDrive";
@@ -507,7 +517,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
507
517
  } & {
508
518
  callback: (args: {
509
519
  driveId: string;
510
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
520
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
511
521
  };
512
522
  readonly addRemoteDrive: {
513
523
  readonly name: "addRemoteDrive";
@@ -543,7 +553,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
543
553
  } | undefined;
544
554
  pullInterval?: number | undefined;
545
555
  };
546
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
556
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
547
557
  };
548
558
  readonly getDocumentModels: {
549
559
  readonly name: "getDocumentModels";
@@ -560,7 +570,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
560
570
  }, z.core.$strip>>;
561
571
  };
562
572
  } & {
563
- callback: (args: Record<string, never>) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
573
+ callback: (args: Record<string, never>) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
564
574
  };
565
575
  readonly getDocumentModelSchema: {
566
576
  readonly name: "getDocumentModelSchema";
@@ -574,7 +584,7 @@ declare function createReactorMcpProvider(options: ReactorMcpProviderOptions): P
574
584
  } & {
575
585
  callback: (args: {
576
586
  type: string;
577
- }) => Promise<_modelcontextprotocol_sdk_types0.CallToolResult>;
587
+ }) => Promise<import("@modelcontextprotocol/sdk/types").CallToolResult>;
578
588
  };
579
589
  };
580
590
  readonly resources: {};
@@ -602,4 +612,5 @@ declare function validateDocumentModelAction(documentModelModule: DocumentModelM
602
612
  };
603
613
  //#endregion
604
614
  export { ToolWithCallback as C, ToolSchema as S, getDriveTool as _, ReactorMcpTools as a, IMcpProvider as b, addRemoteDriveTool as c, deleteDocumentTool as d, deleteDriveTool as f, getDocumentsTool as g, getDocumentTool as h, ReactorMcpProviderOptions as i, createDocumentTool as l, getDocumentModelsTool as m, toolWithCallback as n, addActionsTool as o, getDocumentModelSchemaTool as p, validateDocumentModelAction as r, addDriveTool as s, InvalidToolOutputError as t, createReactorMcpProvider as u, getDrivesTool as v, ResolveZodSchema as x, ExtractCallbackFromTool as y };
605
- //# sourceMappingURL=index-DXl2_PJH.d.mts.map
615
+ export {};
616
+ //# sourceMappingURL=index-CWO1xShX.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-CWO1xShX.d.mts","names":[],"sources":["../src/tools/types.ts","../src/tools/reactor.ts","../src/tools/utils.ts"],"mappings":";;;;;;KAQY,wBAAwB,UAAU,cAAc;EAC1D,mBAAmB;IAEjB,aAAa,UAAU,cAAc,iBACrC;KAEQ,iBAAiB,UAAU,aAAa,cAAc;EAChE,UAAU,wBAAwB;;KAGxB,WACV,kBAAkB,cAAc,aAChC,mBAAmB,cAAc;EAEjC;EACA;EACA;EACA,cAAc;EACd,eAAe;EACf,cAAc;;KAGJ,iBAAiB,KAAK,UAAU,EAAE,cAC1C,E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AEX,YAAU,EAAA;;;iBAGV,SAAO,EAAA;;;;;;;;eAKH;eAEJ;;iBAEA,YAAU,EAAA;iBACV,SAAO,EAAA,SAAA,EAAA;;;;;;;;iBAiBP,SAAO,EAAA;;;;;;;;;;;;;;eAqDH;eACO;;;iBAGX,UAAQ,EAAA,SAAA,EAAA;;;;;;eAKJ;eACO;;iBAEX,YAAU,EAAA;;;;;;;;;;;;;iBAoCV,SAAO,EAAA;;;;;;;;;;;;;;;;;;eAKH;eACO;;iBAEX,SAAO,EAAA;iBACP,SAAO,EAAA,YAAA,EAAA;;;;;;iBAaP,OAAK,EAAA;;;;;;;;;;;;eAKD;eACO;;iBAEX,SAAO,EAAA;;;iBAGP,SAAO,EAAA;;;;;;;;eAKH;eACO;;iBAEX,KAAG,EAAA;iBACH,SAAO,EAAA;;;;;;;;;;;;;iBAuCP,SAAO,EAAA;;;;;;;;;;;;;;;;;;;eAgBH;eACO;;;iBAGX,gBAAc,EAAA,SAAA,EAAA;;;;;;;;;;;;;eAfV;eACO;;iBAEX,MAAI,EAAA;;;iBAGJ,QAAM,EAAA;;;;;;;;;;;;;cCjTG,+BAA+B;EAC1C,YAAY,UAAU,EAAE;;;;;;;;;;iBAeV,iBAAiB,UAAU,YACzC,MAAM,GACN,eACE,MAAM,iBAAiB,sBAErB,iBAAiB,qBACjB,QAAQ,iBAAiB,sBAAmB;EAGxC,WAAA,MAAA,iBAAiB,sBACtB,QAAQ;;iBAgCG,4BACd,qBAAqB,qBACrB,QAAQ;EACL;EAAkB"}
package/dist/index.d.mts CHANGED
@@ -1,16 +1,21 @@
1
- import { C as ToolWithCallback, S as ToolSchema, _ as getDriveTool, a as ReactorMcpTools, b as IMcpProvider, c as addRemoteDriveTool, d as deleteDocumentTool, f as deleteDriveTool, g as getDocumentsTool, h as getDocumentTool, i as ReactorMcpProviderOptions, l as createDocumentTool, m as getDocumentModelsTool, n as toolWithCallback, o as addActionsTool, p as getDocumentModelSchemaTool, r as validateDocumentModelAction, s as addDriveTool, t as InvalidToolOutputError, u as createReactorMcpProvider, v as getDrivesTool, x as ResolveZodSchema, y as ExtractCallbackFromTool } from "./index-DXl2_PJH.mjs";
1
+ import { C as ToolWithCallback, S as ToolSchema, _ as getDriveTool, a as ReactorMcpTools, b as IMcpProvider, c as addRemoteDriveTool, d as deleteDocumentTool, f as deleteDriveTool, g as getDocumentsTool, h as getDocumentTool, i as ReactorMcpProviderOptions, l as createDocumentTool, m as getDocumentModelsTool, n as toolWithCallback, o as addActionsTool, p as getDocumentModelSchemaTool, r as validateDocumentModelAction, s as addDriveTool, t as InvalidToolOutputError, u as createReactorMcpProvider, v as getDrivesTool, x as ResolveZodSchema, y as ExtractCallbackFromTool } from "./index-CWO1xShX.mjs";
2
2
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { IReactorClient, ISyncManager } from "@powerhousedao/reactor";
5
+ import { AuthSubject } from "@powerhousedao/shared/document-model";
5
6
  import { IncomingMessage, ServerResponse } from "node:http";
6
-
7
7
  //#region src/mcp-routes.d.ts
8
8
  /** Minimal interface for an HTTP adapter that supports Node.js-style route handlers. */
9
9
  interface NodeRouteAdapter {
10
10
  mountNodeRoute(method: "DELETE" | "GET" | "POST", path: string, handler: (req: IncomingMessage, res: ServerResponse, body?: unknown) => void | Promise<void>): void;
11
11
  }
12
+ /**
13
+ * An authorized request names the subject its tools read as. Anonymous is an
14
+ * empty subject, never the host's signer.
15
+ */
12
16
  type McpAuthorizationResult = {
13
17
  authorized: true;
18
+ subject: AuthSubject;
14
19
  } | {
15
20
  authorized: false;
16
21
  status: number;
@@ -31,14 +36,17 @@ interface SetupMcpServerOptions {
31
36
  type TransportFactory = (opts: {
32
37
  sessionIdGenerator: undefined;
33
38
  }) => InstanceType<typeof StreamableHTTPServerTransport>;
34
- declare function setupMcpServer(options: SetupMcpServerOptions, httpAdapter: NodeRouteAdapter, createTransport?: TransportFactory): Promise<void>;
39
+ export declare function setupMcpServer(options: SetupMcpServerOptions, httpAdapter: NodeRouteAdapter, createTransport?: TransportFactory): Promise<void>;
35
40
  //#endregion
36
41
  //#region src/server.d.ts
37
42
  interface CreateServerOptions {
38
43
  client: IReactorClient;
39
44
  syncManager?: ISyncManager;
45
+ /** Who the tools read as; omitted, the client's signer. */
46
+ subject?: AuthSubject;
40
47
  }
41
- declare function createServer(options: CreateServerOptions): Promise<McpServer>;
48
+ export declare function createServer(options: CreateServerOptions): Promise<McpServer>;
42
49
  //#endregion
43
- export { type CreateServerOptions, ExtractCallbackFromTool, IMcpProvider, InvalidToolOutputError, type McpAuthorizationResult, type McpRequestAuthorizer, ReactorMcpProviderOptions, ReactorMcpTools, ResolveZodSchema, type SetupMcpServerOptions, ToolSchema, ToolWithCallback, addActionsTool, addDriveTool, addRemoteDriveTool, createDocumentTool, createReactorMcpProvider, createServer, deleteDocumentTool, deleteDriveTool, getDocumentModelSchemaTool, getDocumentModelsTool, getDocumentTool, getDocumentsTool, getDriveTool, getDrivesTool, setupMcpServer, toolWithCallback, validateDocumentModelAction };
50
+ export { type CreateServerOptions, ExtractCallbackFromTool, IMcpProvider, InvalidToolOutputError, type McpAuthorizationResult, type McpRequestAuthorizer, ReactorMcpProviderOptions, ReactorMcpTools, ResolveZodSchema, type SetupMcpServerOptions, ToolSchema, ToolWithCallback, addActionsTool, addDriveTool, addRemoteDriveTool, createDocumentTool, createReactorMcpProvider, deleteDocumentTool, deleteDriveTool, getDocumentModelSchemaTool, getDocumentModelsTool, getDocumentTool, getDocumentsTool, getDriveTool, getDrivesTool, toolWithCallback, validateDocumentModelAction };
51
+ export {};
44
52
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/mcp-routes.ts","../src/server.ts"],"mappings":";;;;;;;;UAKU,gBAAA;EACR,cAAA,CACE,MAAA,6BACA,IAAA,UACA,OAAA,GACE,GAAA,EAAK,eAAA,EACL,GAAA,EAAK,cAAA,EACL,IAAA,sBACU,OAAA;AAAA;AAAA,KAMJ,sBAAA;EACN,UAAA;AAAA;EACA,UAAA;EAAmB,MAAA;EAAgB,OAAA;AAAA;;;;;;KAO7B,oBAAA,IACV,GAAA,EAAK,eAAA,KACF,OAAA,CAAQ,sBAAA;AAAA,UAEI,qBAAA;EACf,MAAA,EAAQ,cAAA;EACR,WAAA,GAAc,YAAA;EACd,gBAAA,EAAkB,oBAAA;AAAA;;KAgBf,gBAAA,IAAoB,IAAA;EACvB,kBAAA;AAAA,MACI,YAAA,QAAoB,6BAAA;AAAA,iBAwCV,cAAA,CACd,OAAA,EAAS,qBAAA,EACT,WAAA,EAAa,gBAAA,EAGb,eAAA,GAAiB,gBAAA,GAEhB,OAAA;;;UChGc,mBAAA;EACf,MAAA,EAAQ,cAAA;EACR,WAAA,GAAc,YAAA;AAAA;AAAA,iBAmBM,YAAA,CACpB,OAAA,EAAS,mBAAA,GACR,OAAA,CAAQ,SAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/mcp-routes.ts","../src/server.ts"],"mappings":";;;;;;;;UAMU;EACR,eACE,mCACA,cACA,UACE,KAAK,iBACL,KAAK,gBACL,0BACU;;;;;;KAUJ;EACN;EAAkB,SAAS;;EAC3B;EAAmB;EAAgB;;;;;;;KAO7B,wBACV,KAAK,oBACF,QAAQ;UAEI;EACf,QAAQ;EACR,cAAc;EACd,kBAAkB;;;KAgBf,oBAAoB;EACvB;MACI,oBAAoB;wBA+CV,eACd,SAAS,uBACT,aAAa,kBAGb,kBAAiB,mBAEhB;;;UC3Gc;EACf,QAAQ;EACR,cAAc;;EAEd,UAAU;;wBAmBU,aACpB,SAAS,sBACR,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { n as logger, t as createServer } from "./server-Dtbb-8Dy.mjs";
2
- import { a as createReactorMcpProvider, c as getDocumentModelSchemaTool, d as getDocumentsTool, f as getDriveTool, g as validateDocumentModelAction, h as toolWithCallback, i as createDocumentTool, l as getDocumentModelsTool, m as InvalidToolOutputError, n as addDriveTool, o as deleteDocumentTool, p as getDrivesTool, r as addRemoteDriveTool, s as deleteDriveTool, t as addActionsTool, u as getDocumentTool } from "./reactor-BswnJgTi.mjs";
1
+ import { n as logger, t as createServer } from "./server-CT8k24iS.mjs";
2
+ import { a as createReactorMcpProvider, c as getDocumentModelSchemaTool, d as getDocumentsTool, f as getDriveTool, g as validateDocumentModelAction, h as toolWithCallback, i as createDocumentTool, l as getDocumentModelsTool, m as InvalidToolOutputError, n as addDriveTool, o as deleteDocumentTool, p as getDrivesTool, r as addRemoteDriveTool, s as deleteDriveTool, t as addActionsTool, u as getDocumentTool } from "./reactor-CYKTrGtF.mjs";
3
3
  import "./tools/index.mjs";
4
4
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
5
  //#region src/mcp-routes.ts
@@ -34,14 +34,18 @@ function withAuthorization(authorize, handler) {
34
34
  res.writeHead(result.status, { "Content-Type": "application/json" }).end(jsonRpcError(result.message));
35
35
  return;
36
36
  }
37
- await handler(req, res, body);
37
+ await handler(req, res, body, result.subject);
38
38
  };
39
39
  }
40
40
  function setupMcpServer(options, httpAdapter, createTransport = (opts) => new StreamableHTTPServerTransport(opts)) {
41
41
  const { authorizeRequest } = options;
42
- httpAdapter.mountNodeRoute("POST", "/mcp", withAuthorization(authorizeRequest, async (req, res, body) => {
42
+ httpAdapter.mountNodeRoute("POST", "/mcp", withAuthorization(authorizeRequest, async (req, res, body, subject) => {
43
43
  try {
44
- const server = await createServer(options);
44
+ const server = await createServer({
45
+ client: options.client,
46
+ syncManager: options.syncManager,
47
+ subject
48
+ });
45
49
  const transport = createTransport({ sessionIdGenerator: void 0 });
46
50
  res.on("close", () => {
47
51
  transport.close();
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/mcp-routes.ts"],"sourcesContent":["import { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport type { IReactorClient, ISyncManager } from \"@powerhousedao/reactor\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n/** Minimal interface for an HTTP adapter that supports Node.js-style route handlers. */\ninterface NodeRouteAdapter {\n mountNodeRoute(\n method: \"DELETE\" | \"GET\" | \"POST\",\n path: string,\n handler: (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n ) => void | Promise<void>,\n ): void;\n}\nimport { logger } from \"./logger.js\";\nimport { createServer } from \"./server.js\";\n\nexport type McpAuthorizationResult =\n | { authorized: true }\n | { authorized: false; status: number; message: string };\n\n/**\n * Authorizes an incoming /mcp request before it reaches the MCP transport.\n * MCP tools run with unrestricted reactor access, so this is the only gate;\n * an open endpoint must opt in by returning `authorized: true`.\n */\nexport type McpRequestAuthorizer = (\n req: IncomingMessage,\n) => Promise<McpAuthorizationResult>;\n\nexport interface SetupMcpServerOptions {\n client: IReactorClient;\n syncManager?: ISyncManager;\n authorizeRequest: McpRequestAuthorizer;\n}\n\nfunction jsonRpcError(message: string, code = -32000): string {\n return JSON.stringify({\n jsonrpc: \"2.0\",\n error: { code, message },\n id: null,\n });\n}\n\nconst METHOD_NOT_ALLOWED = jsonRpcError(\"Method not allowed.\");\n\nconst INTERNAL_SERVER_ERROR = jsonRpcError(\"Internal server error\", -32603);\n\n/** @internal Injected in tests to avoid relying on constructor mock semantics. */\ntype TransportFactory = (opts: {\n sessionIdGenerator: undefined;\n}) => InstanceType<typeof StreamableHTTPServerTransport>;\n\ntype NodeRouteHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n) => void | Promise<void>;\n\n/**\n * Authorizes the request before running the handler. Failures respond with\n * the authorizer's status and a JSON-RPC error; an authorizer fault fails\n * closed with a 500.\n */\nfunction withAuthorization(\n authorize: McpRequestAuthorizer,\n handler: NodeRouteHandler,\n): NodeRouteHandler {\n return async (req: IncomingMessage, res: ServerResponse, body?: unknown) => {\n let result: McpAuthorizationResult;\n try {\n result = await authorize(req);\n } catch (error) {\n logger.error(\"Error authorizing MCP request: @error\", error);\n if (!res.headersSent) {\n res\n .writeHead(500, { \"Content-Type\": \"application/json\" })\n .end(INTERNAL_SERVER_ERROR);\n }\n return;\n }\n if (!result.authorized) {\n res\n .writeHead(result.status, { \"Content-Type\": \"application/json\" })\n .end(jsonRpcError(result.message));\n return;\n }\n await handler(req, res, body);\n };\n}\n\nexport function setupMcpServer(\n options: SetupMcpServerOptions,\n httpAdapter: NodeRouteAdapter,\n // Allow tests to inject a factory function instead of relying on `new vi.fn()`\n // constructor semantics, which differ between macOS and Linux environments.\n createTransport: TransportFactory = (opts) =>\n new StreamableHTTPServerTransport(opts),\n): Promise<void> {\n const { authorizeRequest } = options;\n\n httpAdapter.mountNodeRoute(\n \"POST\",\n \"/mcp\",\n withAuthorization(\n authorizeRequest,\n async (req: IncomingMessage, res: ServerResponse, body?: unknown) => {\n // Stateless mode: every request owns its McpServer + transport so\n // concurrent or slow handlers cannot collide on a shared Protocol\n // instance (which throws \"Already connected to a transport\").\n try {\n const server = await createServer(options);\n const transport = createTransport({ sessionIdGenerator: undefined });\n res.on(\"close\", () => {\n void transport.close();\n void server.close();\n });\n await server.connect(transport);\n await transport.handleRequest(req, res, body);\n } catch (error) {\n logger.error(\"Error handling MCP request: @error\", error);\n if (!res.headersSent) {\n res\n .writeHead(500, { \"Content-Type\": \"application/json\" })\n .end(INTERNAL_SERVER_ERROR);\n }\n }\n },\n ),\n );\n\n // GET/DELETE always answer 405 in stateless mode and reach no MCP tool, so\n // they are intentionally left unauthorized.\n httpAdapter.mountNodeRoute(\n \"GET\",\n \"/mcp\",\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(405).end(METHOD_NOT_ALLOWED);\n },\n );\n\n httpAdapter.mountNodeRoute(\n \"DELETE\",\n \"/mcp\",\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(405).end(METHOD_NOT_ALLOWED);\n },\n );\n return Promise.resolve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;GAIpC,CACF;AAID,aAAY,eACV,OACA,SACC,MAAuB,QAAwB;AAC9C,MAAI,UAAU,IAAI,CAAC,IAAI,mBAAmB;GAE7C;AAED,aAAY,eACV,UACA,SACC,MAAuB,QAAwB;AAC9C,MAAI,UAAU,IAAI,CAAC,IAAI,mBAAmB;GAE7C;AACD,QAAO,QAAQ,SAAS"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/mcp-routes.ts"],"sourcesContent":["import { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport type { IReactorClient, ISyncManager } from \"@powerhousedao/reactor\";\nimport type { AuthSubject } from \"@powerhousedao/shared/document-model\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n/** Minimal interface for an HTTP adapter that supports Node.js-style route handlers. */\ninterface NodeRouteAdapter {\n mountNodeRoute(\n method: \"DELETE\" | \"GET\" | \"POST\",\n path: string,\n handler: (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n ) => void | Promise<void>,\n ): void;\n}\nimport { logger } from \"./logger.js\";\nimport { createServer } from \"./server.js\";\n\n/**\n * An authorized request names the subject its tools read as. Anonymous is an\n * empty subject, never the host's signer.\n */\nexport type McpAuthorizationResult =\n | { authorized: true; subject: AuthSubject }\n | { authorized: false; status: number; message: string };\n\n/**\n * Authorizes an incoming /mcp request before it reaches the MCP transport.\n * MCP tools run with unrestricted reactor access, so this is the only gate;\n * an open endpoint must opt in by returning `authorized: true`.\n */\nexport type McpRequestAuthorizer = (\n req: IncomingMessage,\n) => Promise<McpAuthorizationResult>;\n\nexport interface SetupMcpServerOptions {\n client: IReactorClient;\n syncManager?: ISyncManager;\n authorizeRequest: McpRequestAuthorizer;\n}\n\nfunction jsonRpcError(message: string, code = -32000): string {\n return JSON.stringify({\n jsonrpc: \"2.0\",\n error: { code, message },\n id: null,\n });\n}\n\nconst METHOD_NOT_ALLOWED = jsonRpcError(\"Method not allowed.\");\n\nconst INTERNAL_SERVER_ERROR = jsonRpcError(\"Internal server error\", -32603);\n\n/** @internal Injected in tests to avoid relying on constructor mock semantics. */\ntype TransportFactory = (opts: {\n sessionIdGenerator: undefined;\n}) => InstanceType<typeof StreamableHTTPServerTransport>;\n\ntype NodeRouteHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n body?: unknown,\n) => void | Promise<void>;\n\ntype AuthorizedRouteHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n body: unknown,\n subject: AuthSubject,\n) => void | Promise<void>;\n\n/**\n * Authorizes the request before running the handler. Failures respond with\n * the authorizer's status and a JSON-RPC error; an authorizer fault fails\n * closed with a 500.\n */\nfunction withAuthorization(\n authorize: McpRequestAuthorizer,\n handler: AuthorizedRouteHandler,\n): NodeRouteHandler {\n return async (req: IncomingMessage, res: ServerResponse, body?: unknown) => {\n let result: McpAuthorizationResult;\n try {\n result = await authorize(req);\n } catch (error) {\n logger.error(\"Error authorizing MCP request: @error\", error);\n if (!res.headersSent) {\n res\n .writeHead(500, { \"Content-Type\": \"application/json\" })\n .end(INTERNAL_SERVER_ERROR);\n }\n return;\n }\n if (!result.authorized) {\n res\n .writeHead(result.status, { \"Content-Type\": \"application/json\" })\n .end(jsonRpcError(result.message));\n return;\n }\n await handler(req, res, body, result.subject);\n };\n}\n\nexport function setupMcpServer(\n options: SetupMcpServerOptions,\n httpAdapter: NodeRouteAdapter,\n // Allow tests to inject a factory function instead of relying on `new vi.fn()`\n // constructor semantics, which differ between macOS and Linux environments.\n createTransport: TransportFactory = (opts) =>\n new StreamableHTTPServerTransport(opts),\n): Promise<void> {\n const { authorizeRequest } = options;\n\n httpAdapter.mountNodeRoute(\n \"POST\",\n \"/mcp\",\n withAuthorization(authorizeRequest, async (req, res, body, subject) => {\n // Stateless mode: every request owns its McpServer + transport so\n // concurrent or slow handlers cannot collide on a shared Protocol\n // instance (which throws \"Already connected to a transport\").\n try {\n const server = await createServer({\n client: options.client,\n syncManager: options.syncManager,\n subject,\n });\n const transport = createTransport({ sessionIdGenerator: undefined });\n res.on(\"close\", () => {\n void transport.close();\n void server.close();\n });\n await server.connect(transport);\n await transport.handleRequest(req, res, body);\n } catch (error) {\n logger.error(\"Error handling MCP request: @error\", error);\n if (!res.headersSent) {\n res\n .writeHead(500, { \"Content-Type\": \"application/json\" })\n .end(INTERNAL_SERVER_ERROR);\n }\n }\n }),\n );\n\n // GET/DELETE always answer 405 in stateless mode and reach no MCP tool, so\n // they are intentionally left unauthorized.\n httpAdapter.mountNodeRoute(\n \"GET\",\n \"/mcp\",\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(405).end(METHOD_NOT_ALLOWED);\n },\n );\n\n httpAdapter.mountNodeRoute(\n \"DELETE\",\n \"/mcp\",\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(405).end(METHOD_NOT_ALLOWED);\n },\n );\n return Promise.resolve();\n}\n"],"mappings":";;;;;AA2CA,SAAS,aAAa,SAAiB,OAAO,OAAgB;CAC5D,OAAO,KAAK,UAAU;EACpB,SAAS;EACT,OAAO;GAAE;GAAM;EAAQ;EACvB,IAAI;CACN,CAAC;AACH;AAEA,MAAM,qBAAqB,aAAa,qBAAqB;AAE7D,MAAM,wBAAwB,aAAa,yBAAyB,MAAM;;;;;;AAyB1E,SAAS,kBACP,WACA,SACkB;CAClB,OAAO,OAAO,KAAsB,KAAqB,SAAmB;EAC1E,IAAI;EACJ,IAAI;GACF,SAAS,MAAM,UAAU,GAAG;EAC9B,SAAS,OAAO;GACd,OAAO,MAAM,yCAAyC,KAAK;GAC3D,IAAI,CAAC,IAAI,aACP,IACG,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC,CAAC,CACtD,IAAI,qBAAqB;GAE9B;EACF;EACA,IAAI,CAAC,OAAO,YAAY;GACtB,IACG,UAAU,OAAO,QAAQ,EAAE,gBAAgB,mBAAmB,CAAC,CAAC,CAChE,IAAI,aAAa,OAAO,OAAO,CAAC;GACnC;EACF;EACA,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,OAAO;CAC9C;AACF;AAEA,SAAgB,eACd,SACA,aAGA,mBAAqC,SACnC,IAAI,8BAA8B,IAAI,GACzB;CACf,MAAM,EAAE,qBAAqB;CAE7B,YAAY,eACV,QACA,QACA,kBAAkB,kBAAkB,OAAO,KAAK,KAAK,MAAM,YAAY;EAIrE,IAAI;GACF,MAAM,SAAS,MAAM,aAAa;IAChC,QAAQ,QAAQ;IAChB,aAAa,QAAQ;IACrB;GACF,CAAC;GACD,MAAM,YAAY,gBAAgB,EAAE,oBAAoB,KAAA,EAAU,CAAC;GACnE,IAAI,GAAG,eAAe;IACpB,UAAe,MAAM;IACrB,OAAY,MAAM;GACpB,CAAC;GACD,MAAM,OAAO,QAAQ,SAAS;GAC9B,MAAM,UAAU,cAAc,KAAK,KAAK,IAAI;EAC9C,SAAS,OAAO;GACd,OAAO,MAAM,sCAAsC,KAAK;GACxD,IAAI,CAAC,IAAI,aACP,IACG,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC,CAAC,CACtD,IAAI,qBAAqB;EAEhC;CACF,CAAC,CACH;CAIA,YAAY,eACV,OACA,SACC,MAAuB,QAAwB;EAC9C,IAAI,UAAU,GAAG,CAAC,CAAC,IAAI,kBAAkB;CAC3C,CACF;CAEA,YAAY,eACV,UACA,SACC,MAAuB,QAAwB;EAC9C,IAAI,UAAU,GAAG,CAAC,CAAC,IAAI,kBAAkB;CAC3C,CACF;CACA,OAAO,QAAQ,QAAQ;AACzB"}
@@ -220,13 +220,14 @@ const getDocumentModelsTool = {
220
220
  })).describe("List of available document models") }
221
221
  };
222
222
  function createReactorMcpProvider(options) {
223
- const { client, syncManager } = options;
223
+ const { client, syncManager, subject } = options;
224
+ const view = subject ? { subject } : void 0;
224
225
  function getDocumentModelModule(documentType) {
225
226
  return client.getDocumentModelModule(documentType);
226
227
  }
227
228
  const tools = {
228
229
  getDocument: toolWithCallback(getDocumentTool, async (params) => {
229
- const document = await client.get(params.id);
230
+ const document = await client.get(params.id, view);
230
231
  return { document: {
231
232
  header: document.header,
232
233
  state: document.state
@@ -243,7 +244,7 @@ function createReactorMcpProvider(options) {
243
244
  return { documentId: (await client.createEmpty(params.documentType, {})).header.id };
244
245
  }),
245
246
  getDocuments: toolWithCallback(getDocumentsTool, async (params) => {
246
- return { documentIds: (await client.getOutgoingRelationships(params.parentId, "child")).results.map((doc) => doc.header.id) };
247
+ return { documentIds: (await client.getOutgoingRelationships(params.parentId, "child", view)).results.map((doc) => doc.header.id) };
247
248
  }),
248
249
  deleteDocument: toolWithCallback(deleteDocumentTool, async (params) => {
249
250
  try {
@@ -256,7 +257,7 @@ function createReactorMcpProvider(options) {
256
257
  }
257
258
  }),
258
259
  addActions: toolWithCallback(addActionsTool, async (params) => {
259
- const document = await client.get(params.documentId);
260
+ const document = await client.get(params.documentId, view);
260
261
  const documentModel = await getDocumentModelModule(document.header.documentType);
261
262
  if (!documentModel) throw new Error(`Document model for document type '${document.header.documentType}' not found`);
262
263
  const actions = params.actions.map((paramAction) => {
@@ -265,11 +266,11 @@ function createReactorMcpProvider(options) {
265
266
  if (!actionValidation.isValid) throw new Error(`Invalid action ${JSON.stringify(action)}: ${actionValidation.errors.join(", ")}`);
266
267
  return action;
267
268
  });
268
- await client.execute(params.documentId, "main", actions);
269
+ await client.execute(params.documentId, "main", actions, void 0, subject);
269
270
  return { success: true };
270
271
  }),
271
272
  getDrives: toolWithCallback(getDrivesTool, async () => {
272
- return { driveIds: (await client.find({ type: DRIVE_DOCUMENT_TYPE })).results.map((doc) => doc.header.id) };
273
+ return { driveIds: (await client.find({ type: DRIVE_DOCUMENT_TYPE }, view)).results.map((doc) => doc.header.id) };
273
274
  }),
274
275
  addDrive: toolWithCallback(addDriveTool, async (params) => {
275
276
  const { driveInput } = params;
@@ -280,11 +281,11 @@ function createReactorMcpProvider(options) {
280
281
  if (driveInput.global.icon) actions.push(setDriveIcon({ icon: driveInput.global.icon }));
281
282
  if (driveInput.local?.sharingType) actions.push(setSharingType({ type: driveInput.local.sharingType }));
282
283
  if (driveInput.local?.availableOffline !== void 0) actions.push(setAvailableOffline({ availableOffline: driveInput.local.availableOffline }));
283
- if (actions.length > 0) await client.execute(driveId, "main", actions);
284
+ if (actions.length > 0) await client.execute(driveId, "main", actions, void 0, subject);
284
285
  return { driveId };
285
286
  }),
286
287
  getDrive: toolWithCallback(getDriveTool, async (params) => {
287
- const drive = await client.get(params.driveId);
288
+ const drive = await client.get(params.driveId, view);
288
289
  return { drive: {
289
290
  header: drive.header,
290
291
  state: drive.state
@@ -341,4 +342,4 @@ function createReactorMcpProvider(options) {
341
342
  //#endregion
342
343
  export { createReactorMcpProvider as a, getDocumentModelSchemaTool as c, getDocumentsTool as d, getDriveTool as f, validateDocumentModelAction as g, toolWithCallback as h, createDocumentTool as i, getDocumentModelsTool as l, InvalidToolOutputError as m, addDriveTool as n, deleteDocumentTool as o, getDrivesTool as p, addRemoteDriveTool as r, deleteDriveTool as s, addActionsTool as t, getDocumentTool as u };
343
344
 
344
- //# sourceMappingURL=reactor-BswnJgTi.mjs.map
345
+ //# sourceMappingURL=reactor-CYKTrGtF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reactor-CYKTrGtF.mjs","names":[],"sources":["../src/tools/utils.ts","../src/tools/reactor.ts"],"sourcesContent":["import type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { camelCase } from \"change-case\";\nimport type {\n Action,\n DocumentModelModule,\n Operation,\n} from \"@powerhousedao/shared/document-model\";\nimport type { z } from \"zod\";\nimport type { ResolveZodSchema, ToolSchema } from \"./types.js\";\n\nexport class InvalidToolOutputError extends Error {\n constructor(zodError: z.ZodError) {\n super(\"Invalid tool output\\n\" + zodError.message);\n this.name = \"InvalidToolOutputError\";\n this.cause = zodError;\n }\n}\n\n/**\n * Creates a tool with a callback function that handles the tool execution,\n * ensuring the output is valid and errors are handled and returned correctly.\n * @param tool The tool schema to wrap.\n * @param toolCallback The callback function to execute when the tool is called.\n * @returns A CallToolResult with structuredContent if OutputSchema is defined or content if undefined. If the\n * callback throws an error, the result will have isError set to true and the error message in the content.\n */\nexport function toolWithCallback<T extends ToolSchema>(\n tool: T,\n toolCallback: (\n args: ResolveZodSchema<T[\"inputSchema\"]>,\n ) =>\n | ResolveZodSchema<T[\"outputSchema\"]>\n | Promise<ResolveZodSchema<T[\"outputSchema\"]>>,\n) {\n const wrappedCallback = async (\n args: ResolveZodSchema<T[\"inputSchema\"]>,\n ): Promise<CallToolResult> => {\n try {\n const result = await toolCallback(args);\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(result),\n },\n ],\n structuredContent: result,\n } as const satisfies CallToolResult;\n } catch (error) {\n const errorString =\n error instanceof Error ? error.message : String(error);\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Error: ${errorString}`,\n },\n ],\n } as const satisfies CallToolResult;\n }\n };\n return {\n ...tool,\n callback: wrappedCallback,\n };\n}\n\nexport function validateDocumentModelAction(\n documentModelModule: DocumentModelModule,\n action: Action,\n): { isValid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n const globalState = documentModelModule.documentModel.global;\n\n // Get the latest specification\n if (!globalState.specifications || globalState.specifications.length === 0) {\n errors.push(\"Document model has no specifications\");\n return { isValid: false, errors };\n }\n\n const latestSpec =\n globalState.specifications[globalState.specifications.length - 1];\n\n // Search through modules to find the operation that matches the action type (in SCREAMING_SNAKE_CASE)\n let operation: (Operation & { scope: string }) | null = null;\n\n for (const module of latestSpec.modules) {\n const unsafeOperationOrActionOrSomething = module.operations.find(\n (op) => op.name === action.type,\n ) as unknown as Operation & { scope: string };\n if (unsafeOperationOrActionOrSomething) {\n operation = unsafeOperationOrActionOrSomething;\n break;\n }\n }\n\n if (!operation) {\n errors.push(\n `Operation \"${action.type}\" is not defined in any module of the document model`,\n );\n return { isValid: false, errors };\n }\n\n // Convert action type from SCREAMING_SNAKE_CASE to camelCase to match action creators\n const camelCaseActionType = camelCase(action.type);\n\n // Check if action creator exists in documentModelModule.actions\n const actionCreator = documentModelModule.actions[camelCaseActionType];\n\n if (!actionCreator) {\n errors.push(\n `Action creator \"${camelCaseActionType}\" for action type \"${action.type}\" is not defined in documentModelDocumentModelModule.actions`,\n );\n return { isValid: false, errors };\n }\n\n // Validate the operation using the action creator. TODO: Use document model exported validators directly\n let inputError: Error | null = null;\n try {\n actionCreator(action.input);\n } catch (e) {\n inputError = e instanceof Error ? e : new Error(JSON.stringify(e));\n }\n\n if (inputError) {\n errors.push(`Input validation error: ${inputError.message}`);\n }\n\n // Validate scope if operation defines one\n if (operation.scope && action.scope !== operation.scope) {\n errors.push(\n `Action scope \"${action.scope}\" does not match operation scope \"${operation.scope}\"`,\n );\n }\n\n return {\n isValid: errors.length === 0,\n errors,\n };\n}\n","import type { IReactorClient, ISyncManager } from \"@powerhousedao/reactor\";\nimport { DriveCollectionId } from \"@powerhousedao/reactor\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport {\n setAvailableOffline,\n setDriveIcon,\n setSharingType,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n Action,\n AuthSubject,\n DocumentModelModule,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n createAction,\n withSignaturePolicy,\n} from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport type { ToolSchema, ToolWithCallback } from \"./types.js\";\nimport { toolWithCallback, validateDocumentModelAction } from \"./utils.js\";\n\nconst DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\";\n\nexport type ReactorMcpProviderOptions = {\n client: IReactorClient;\n syncManager?: ISyncManager;\n /**\n * Who the tools read as. A server shared by many callers must set it, an\n * anonymous one to an empty subject. Omitted, reads fall back to the\n * client's signer, which only a single-user local reactor should rely on.\n */\n subject?: AuthSubject;\n};\n\nexport const createDocumentTool = {\n name: \"createDocument\",\n description: `Create a new document.\n Unless the user specifies otherwise, and a drive named \"vetra\" is available, add the document to that drive by providing the drive's ID in the \"driveId\" parameter.\n When \"driveId\" is provided, the document is created and added to the drive atomically — no separate \"addActions\" call with \"ADD_FILE\" is needed.`,\n inputSchema: {\n documentType: z.string().describe(\"Type of the document to create\"),\n name: z\n .string()\n .optional()\n .describe(\n \"Optional name for the document. Used as both the document name and the drive node name when driveId is provided.\",\n ),\n driveId: z\n .string()\n .optional()\n .describe(\n \"Optional drive ID or slug. When provided, the document is created and added to the drive atomically.\",\n ),\n parentFolder: z\n .string()\n .optional()\n .describe(\n \"Optional folder ID within the drive to place the document in. Only used when driveId is provided.\",\n ),\n },\n outputSchema: {\n documentId: z.string().describe(\"ID of the created document\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDocumentTool = {\n name: \"getDocument\",\n description: \"Retrieve a document by its ID\",\n inputSchema: {\n id: z.string().describe(\"ID of the document to retrieve\"),\n },\n outputSchema: {\n document: z.unknown().describe(\"The retrieved Document\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDocumentsTool = {\n name: \"getDocuments\",\n description: \"List documents in a drive\",\n inputSchema: {\n parentId: z.string().describe(\"ID of the drive\"),\n },\n outputSchema: {\n documentIds: z.array(z.string()).describe(\"Array of document IDs\"),\n },\n} as const satisfies ToolSchema;\n\nexport const deleteDocumentTool = {\n name: \"deleteDocument\",\n description: \"Delete a document\",\n inputSchema: {\n documentId: z.string().describe(\"ID of the document to delete\"),\n },\n outputSchema: {\n success: z.boolean().describe(\"Whether the deletion was successful\"),\n },\n} as const satisfies ToolSchema;\n\nexport const addActionsTool = {\n name: \"addActions\",\n description:\n \"Adds actions to a document. Prefer adding multiples actions at once to reduce the number of steps.\",\n inputSchema: {\n documentId: z.string().describe(\"ID of the document\"),\n actions: z\n .array(\n z\n .object({\n type: z.string().describe(\"The name of the action\"),\n input: z.unknown().describe(\"The payload of the action\"),\n scope: z.string().describe(\"The scope of the action\"),\n context: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Optional action context\"), // TODO: Define context schema\n })\n .strict(),\n )\n .describe(\"Action to add to the document\"),\n },\n outputSchema: {\n success: z.boolean().describe(\"Whether the actions were added\"),\n },\n} as const satisfies ToolSchema;\n\n// export const addOperationTool = {\n// name: \"addOperation\",\n// description: \"Add an operation to a document\",\n// inputSchema: {\n// documentId: z.string().describe(\"ID of the document\"),\n// operation: z\n// .object({\n// type: z.string().describe(\"The name of the action\"),\n// input: z.unknown().describe(\"The payload of the action\"),\n// scope: z.string().describe(\"The scope of the action\"),\n// index: z.number().describe(\"Position of the operation in the history\"),\n// timestampUtcMs: z\n// .string()\n// .describe(\"Timestamp of when the operation was added\"),\n// hash: z.string().describe(\"Hash of the resulting document data\"),\n// skip: z.number().describe(\"The number of operations skipped\"),\n// error: z\n// .string()\n// .optional()\n// .describe(\"Error message for a failed action\"),\n// id: z.string().optional().describe(\"Unique operation id\"),\n// context: z.object({}).optional().describe(\"Optional action context\"), // TODO: Define context schema\n// })\n// .strict()\n// .describe(\"Operation to add to the document\"),\n// },\n// outputSchema: {\n// result: z\n// .object({\n// status: z\n// .enum([\"SUCCESS\", \"CONFLICT\", \"MISSING\", \"ERROR\"])\n// .describe(\"Operation status\"),\n// error: z\n// .string()\n// .optional()\n// .describe(\"Error details if operation failed\"), // TODO: Define error schema\n// operations: z\n// .array(z.object({}))\n// .describe(\"Array of operations created\"), // TODO: Define operation schema\n// document: z.object({}).optional().describe(\"Updated document\"), // TODO: Define document schema\n// signals: z.array(z.object({})).describe(\"Array of signals generated\"), // TODO: Define signal schema\n// })\n// .describe(\"Operation result\"),\n// },\n// } as const satisfies ToolSchema;\n\n// Drive Operation Tools\n\nexport const getDrivesTool = {\n name: \"getDrives\",\n description: \"List all drives\",\n inputSchema: {},\n outputSchema: {\n driveIds: z.array(z.string()).describe(\"Array of drive IDs\"),\n },\n} as const satisfies ToolSchema;\n\nexport const addDriveTool = {\n name: \"addDrive\",\n description: \"Create a new drive\",\n inputSchema: {\n driveInput: z\n .object({\n global: z\n .object({\n name: z.string().describe(\"Name of the drive\"),\n icon: z\n .string()\n .nullable()\n .optional()\n .describe(\"Optional icon for the drive\"),\n })\n .describe(\"Global drive properties\"),\n preferredEditor: z\n .string()\n .optional()\n .describe(\n \"Optional app/editor module id recorded as the drive's preferred editor\",\n ),\n local: z\n .object({\n availableOffline: z\n .boolean()\n .optional()\n .describe(\"Whether drive is available offline\"),\n sharingType: z\n .string()\n .nullable()\n .optional()\n .describe(\"Sharing type\"),\n })\n .optional()\n .describe(\"Optional local state properties\"),\n })\n .describe(\"Drive configuration\"),\n },\n outputSchema: {\n driveId: z.string().describe(\"ID of the created drive\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDriveTool = {\n name: \"getDrive\",\n description: \"Get a specific drive\",\n inputSchema: {\n driveId: z.string().describe(\"ID of the drive to retrieve\"),\n options: z\n .object({\n revisions: z\n .record(z.string(), z.number())\n .optional()\n .describe(\"Optional revision filter\"),\n checkHashes: z.boolean().optional().describe(\"Whether to check hashes\"),\n // TODO: Add other ReducerOptions if needed\n })\n .optional()\n .describe(\"Optional get document options\"),\n },\n outputSchema: {\n drive: z.unknown().describe(\"Drive document\"), // TODO: Define DocumentDriveDocument schema\n },\n} as const satisfies ToolSchema;\n\nexport const deleteDriveTool = {\n name: \"deleteDrive\",\n description: \"Delete a drive\",\n inputSchema: {\n driveId: z.string().describe(\"ID of the drive to delete\"),\n },\n outputSchema: {\n success: z.boolean().describe(\"Whether the deletion was successful\"),\n },\n} as const satisfies ToolSchema;\n\nexport const addRemoteDriveTool = {\n name: \"addRemoteDrive\",\n description: \"Connect to a remote drive\",\n inputSchema: {\n url: z.string().describe(\"URL of the remote drive\"),\n options: z\n .object({\n availableOffline: z\n .boolean()\n .describe(\"Whether drive is available offline\"),\n sharingType: z.string().nullable().optional().describe(\"Sharing type\"),\n pullFilter: z\n .object({\n branch: z\n .array(z.string())\n .nullable()\n .optional()\n .describe(\"Branch filter\"),\n documentId: z\n .array(z.string())\n .nullable()\n .optional()\n .describe(\"Document ID filter\"),\n documentType: z\n .array(z.string())\n .nullable()\n .optional()\n .describe(\"Document type filter\"),\n scope: z\n .array(z.string())\n .nullable()\n .optional()\n .describe(\"Scope filter\"),\n })\n .optional()\n .describe(\"Optional pull filter\"),\n pullInterval: z\n .number()\n .optional()\n .describe(\"Pull interval in milliseconds\"),\n })\n .describe(\"Remote drive options\"),\n },\n outputSchema: {\n driveId: z.string().describe(\"ID of the added remote drive\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDocumentModelSchemaTool = {\n name: \"getDocumentModelSchema\",\n description: \"Get the schema of a document model\",\n inputSchema: {\n type: z.string().describe(\"Type of the document model\"),\n },\n outputSchema: {\n schema: z.unknown().describe(\"Schema of the document model\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDocumentModelsTool = {\n name: \"getDocumentModels\",\n description: \"Get the list of document models\",\n inputSchema: {},\n outputSchema: {\n documentModels: z\n .array(\n z.object({\n name: z.string().describe(\"Name of the document model\"),\n type: z.string().describe(\"Type of the document model\"),\n description: z.string().describe(\"Description of the document model\"),\n extension: z.string().describe(\"Extension of the document model\"),\n authorName: z.string().describe(\"Author name of the document model\"),\n authorWebsite: z\n .string()\n .describe(\"Author website of the document model\"),\n }),\n )\n .describe(\"List of available document models\"),\n },\n} as const satisfies ToolSchema;\n\ntype ToolRecord<T extends readonly ToolSchema[]> = {\n [K in T[number][\"name\"]]: ToolWithCallback<Extract<T[number], { name: K }>>;\n};\n\n// All tools array for type inference\nconst _allTools = [\n getDocumentTool,\n createDocumentTool,\n getDocumentsTool,\n deleteDocumentTool,\n addActionsTool,\n // addOperationTool,\n getDrivesTool,\n addDriveTool,\n getDriveTool,\n deleteDriveTool,\n addRemoteDriveTool,\n getDocumentModelSchemaTool,\n getDocumentModelsTool,\n] as const;\n\n// Inferred interface from tools\nexport type ReactorMcpTools = ToolRecord<typeof _allTools>;\n\nexport function createReactorMcpProvider(options: ReactorMcpProviderOptions) {\n const { client, syncManager, subject } = options;\n const view = subject ? { subject } : undefined;\n\n function getDocumentModelModule(documentType: string) {\n return client.getDocumentModelModule(documentType);\n }\n\n const tools = {\n getDocument: toolWithCallback(getDocumentTool, async (params) => {\n const document = await client.get<PHDocument>(params.id, view);\n return { document: { header: document.header, state: document.state } };\n }),\n\n createDocument: toolWithCallback(createDocumentTool, async (params) => {\n if (params.driveId) {\n const module = await getDocumentModelModule(params.documentType);\n if (!module) {\n throw new Error(\n `Document model for type '${params.documentType}' not found`,\n );\n }\n const document = withSignaturePolicy(\n module.utils.createDocument(),\n await client.getCreateSignaturePolicy(),\n );\n if (params.name) {\n document.header.name = params.name;\n }\n const created = await client.drives.addFile(\n params.driveId,\n document,\n params.parentFolder,\n );\n return { documentId: created.header.id };\n }\n\n const created = await client.createEmpty(params.documentType, {});\n return { documentId: created.header.id };\n }),\n\n getDocuments: toolWithCallback(getDocumentsTool, async (params) => {\n const result = await client.getOutgoingRelationships(\n params.parentId,\n \"child\",\n view,\n );\n const documentIds = result.results.map((doc) => doc.header.id);\n return { documentIds };\n }),\n\n deleteDocument: toolWithCallback(deleteDocumentTool, async (params) => {\n try {\n // Routes the delete through the drive; nothing read here is returned.\n const incoming = await client.getIncomingRelationships(\n params.documentId,\n \"child\",\n );\n const driveParent = incoming.results.find(\n (p) => p.header.documentType === DRIVE_DOCUMENT_TYPE,\n );\n if (driveParent) {\n await client.drives.removeNode(\n driveParent.header.id,\n params.documentId,\n );\n } else {\n await client.deleteDocument(params.documentId);\n }\n return { success: true };\n } catch {\n return { success: false };\n }\n }),\n\n addActions: toolWithCallback(addActionsTool, async (params) => {\n const document = await client.get<PHDocument>(params.documentId, view);\n const documentModel = await getDocumentModelModule(\n document.header.documentType,\n );\n if (!documentModel) {\n throw new Error(\n `Document model for document type '${document.header.documentType}' not found`,\n );\n }\n const actions: Action[] = params.actions.map((paramAction) => {\n const action: Action = createAction(\n paramAction.type,\n paramAction.input ?? {},\n undefined,\n undefined,\n paramAction.scope,\n );\n const actionValidation = validateDocumentModelAction(\n documentModel,\n action,\n );\n if (!actionValidation.isValid) {\n throw new Error(\n `Invalid action ${JSON.stringify(action)}: ${actionValidation.errors.join(\", \")}`,\n );\n }\n return action;\n });\n\n // Execute actions on the document using the \"main\" branch\n await client.execute(\n params.documentId,\n \"main\",\n actions,\n undefined,\n subject,\n );\n\n return {\n success: true,\n };\n }),\n\n // Drive operation implementations\n getDrives: toolWithCallback(getDrivesTool, async () => {\n // Find all documents of type \"powerhouse/document-drive\"\n const result = await client.find({ type: DRIVE_DOCUMENT_TYPE }, view);\n const driveIds = result.results.map((doc: PHDocument) => doc.header.id);\n return { driveIds };\n }),\n\n addDrive: toolWithCallback(addDriveTool, async (params) => {\n const { driveInput } = params;\n const drive = await client.createEmpty<DocumentDriveDocument>(\n DRIVE_DOCUMENT_TYPE,\n {},\n );\n const driveId = drive.header.id;\n\n if (driveInput.global.name) {\n await client.rename(driveId, driveInput.global.name);\n }\n if (driveInput.preferredEditor) {\n await client.setPreferredEditor(driveId, driveInput.preferredEditor);\n }\n\n const actions: Action[] = [];\n if (driveInput.global.icon) {\n actions.push(setDriveIcon({ icon: driveInput.global.icon }));\n }\n if (driveInput.local?.sharingType) {\n actions.push(setSharingType({ type: driveInput.local.sharingType }));\n }\n if (driveInput.local?.availableOffline !== undefined) {\n actions.push(\n setAvailableOffline({\n availableOffline: driveInput.local.availableOffline,\n }),\n );\n }\n if (actions.length > 0) {\n await client.execute(driveId, \"main\", actions, undefined, subject);\n }\n\n return { driveId };\n }),\n\n getDrive: toolWithCallback(getDriveTool, async (params) => {\n const drive = await client.get<DocumentDriveDocument>(\n params.driveId,\n view,\n );\n return { drive: { header: drive.header, state: drive.state } };\n }),\n\n deleteDrive: toolWithCallback(deleteDriveTool, async (params) => {\n try {\n // Use CASCADE to delete the drive and all its contents\n await client.deleteDocument(params.driveId);\n return { success: true };\n } catch {\n return { success: false };\n }\n }),\n\n addRemoteDrive: toolWithCallback(addRemoteDriveTool, async (params) => {\n if (!syncManager) {\n throw new Error(\n \"Remote drive management is not available. \" +\n \"SyncManager was not configured for this MCP server.\",\n );\n }\n\n // Fetch drive info from the REST endpoint to get both id and graphqlEndpoint\n const response = await fetch(params.url);\n if (!response.ok) {\n throw new Error(`Failed to resolve drive info from ${params.url}`);\n }\n const driveInfo = (await response.json()) as {\n id: string;\n graphqlEndpoint: string;\n };\n\n const resolvedDriveId = driveInfo.id;\n const collectionId = DriveCollectionId.forDrive(resolvedDriveId);\n\n // Check if remote already exists\n const existingRemote = syncManager\n .list()\n .find((remote) => remote.meta.collectionId.equals(collectionId));\n if (existingRemote) {\n return { driveId: resolvedDriveId };\n }\n\n // Add the remote via SyncManager\n const remoteName = `mcp-remote-${crypto.randomUUID()}`;\n await syncManager.add(remoteName, collectionId, {\n type: \"gql\",\n parameters: {\n url: driveInfo.graphqlEndpoint,\n },\n });\n\n return { driveId: resolvedDriveId };\n }),\n\n getDocumentModels: toolWithCallback(getDocumentModelsTool, async () => {\n const result = await client.getDocumentModelModules();\n return {\n documentModels: result.results.map((model: DocumentModelModule) => {\n const schemaGlobal = model.documentModel.global;\n return {\n name: schemaGlobal.name,\n type: schemaGlobal.id,\n description: schemaGlobal.description,\n extension: schemaGlobal.extension,\n authorName: schemaGlobal.author.name,\n authorWebsite: schemaGlobal.author.website ?? \"\",\n };\n }),\n };\n }),\n\n getDocumentModelSchema: toolWithCallback(\n getDocumentModelSchemaTool,\n async (params) => {\n const documentModel = await getDocumentModelModule(params.type);\n const schema = documentModel?.documentModel.global;\n if (!schema) {\n throw new Error(`Document model '${params.type}' not found`);\n }\n return { schema };\n },\n ),\n } as const;\n\n const resources = {};\n\n const prompts = {};\n\n return Promise.resolve({\n tools,\n resources,\n prompts,\n } as const);\n}\n"],"mappings":";;;;;;AAUA,IAAa,yBAAb,cAA4C,MAAM;CAChD,YAAY,UAAsB;EAChC,MAAM,0BAA0B,SAAS,OAAO;EAChD,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;;;;;;;;;AAUA,SAAgB,iBACd,MACA,cAKA;CACA,MAAM,kBAAkB,OACtB,SAC4B;EAC5B,IAAI;GACF,MAAM,SAAS,MAAM,aAA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,uBAAuB,YAAY;GAErE,OAAO,EACL,iBAAgB,MAFG,OAAO,wBAAwB,EAAA,CAE3B,QAAQ,KAAK,UAA+B;IACjE,MAAM,eAAe,MAAM,cAAc;IACzC,OAAO;KACL,MAAM,aAAa;KACnB,MAAM,aAAa;KACnB,aAAa,aAAa;KAC1B,WAAW,aAAa;KACxB,YAAY,aAAa,OAAO;KAChC,eAAe,aAAa,OAAO,WAAW;IAChD;GACF,CAAC,EACH;EACF,CAAC;EAED,wBAAwB,iBACtB,4BACA,OAAO,WAAW;GAEhB,MAAM,UAAS,MADa,uBAAuB,OAAO,IAAI,EAAA,EAChC,cAAc;GAC5C,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,mBAAmB,OAAO,KAAK,YAAY;GAE7D,OAAO,EAAE,OAAO;EAClB,CACF;CACF;CAMA,OAAO,QAAQ,QAAQ;EACrB;EACA,WAAA,CAAQ;EACR,SAAA,CAAM;CACR,CAAU;AACZ"}
@@ -1,4 +1,4 @@
1
- import { a as createReactorMcpProvider } from "./reactor-BswnJgTi.mjs";
1
+ import { a as createReactorMcpProvider } from "./reactor-CYKTrGtF.mjs";
2
2
  import { childLogger } from "document-model";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  //#region src/logger.ts
@@ -21,7 +21,7 @@ Examples:
21
21
  <example>Context: User needs to create a new document instance of a given document model. user: 'I need to create a demo user profile document' assistant: 'I'll use the reactor-mcp-server to help you create this document with example values.' <commentary>Since the user is requesting document model creation, use the reactor-mcp-document-expert agent to ensure proper reactor-mcp tool usage.</commentary></example> <example>Context: User is building a content management system and needs create documents for certain types of document models. user: 'Can you help me create example documents for blog posts and categories document models?' assistant: 'Let me use the reactor-mcp-server to create these documents using the appropriate reactor-mcp tool calls.' <commentary>Document creation requires the reactor-mcp-server tool calls to ensure compliance.</commentary></example>
22
22
  `;
23
23
  async function createServer(options) {
24
- const { client, syncManager } = options;
24
+ const { client, syncManager, subject } = options;
25
25
  const server = new McpServer({
26
26
  name: "reactor-mcp-server",
27
27
  version: "1.0.0",
@@ -44,7 +44,8 @@ async function createServer(options) {
44
44
  }] }));
45
45
  const reactorProvider = await createReactorMcpProvider({
46
46
  client,
47
- syncManager
47
+ syncManager,
48
+ subject
48
49
  });
49
50
  Object.entries(reactorProvider.tools).forEach(([toolName, { callback, ...schema }]) => {
50
51
  server.registerTool(toolName, schema, callback);
@@ -54,4 +55,4 @@ async function createServer(options) {
54
55
  //#endregion
55
56
  export { logger as n, createServer as t };
56
57
 
57
- //# sourceMappingURL=server-Dtbb-8Dy.mjs.map
58
+ //# sourceMappingURL=server-CT8k24iS.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-CT8k24iS.mjs","names":[],"sources":["../src/logger.ts","../src/server.ts"],"sourcesContent":["import { childLogger, type ILogger } from \"document-model\";\n\nexport const logger: ILogger = childLogger([\"reactor-mcp\"]);\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { IReactorClient, ISyncManager } from \"@powerhousedao/reactor\";\nimport type { AuthSubject } from \"@powerhousedao/shared/document-model\";\nimport { createReactorMcpProvider } from \"./tools/reactor.js\";\n\nexport interface CreateServerOptions {\n client: IReactorClient;\n syncManager?: ISyncManager;\n /** Who the tools read as; omitted, the client's signer. */\n subject?: AuthSubject;\n}\n\nexport const ReactorMcpInstructions = `MUST BE USED when handling documents or document-models for the Powerhouse/Vetra ecosystem.\nThere are 5 main concepts to know of: \n- Document Model: A template for creating documents. It defines the schema and allowed operations for a type of document.\n- Document: An instance of a document model. It contains actual data following the structure defined by the document model and can be changed using operations.\n- Drive: A document of type \"powerhouse/document-drive\" which represents a collection of documents and folders. To create a document inside a drive, use the \"createDocument\" tool with the \"driveId\" parameter — this handles everything atomically. Use \"addActions\" with \"ADD_FILE\" only when adding an existing document to a drive.\n- Action: A proposed change to a document. It is a JSON object with the action name and input that defines the action to be taken on the document. Should be dispatched by calling the \"addActions\" tool.\n- Operation: A change done to a document. It contains the action object plus additional metadata such as the index of the operation in the document history, the timestamp it was added, the hash of the resulting document data, the number of operations skipped, and the error message if the operation failed. Actions dispatched with \"addActions\" get converted into an operation.\n\nWhen planning to add multiple actions to a document, try to reduce the number of \"addActions\" calls to a minimum by adding multiple actions at once.\nUnless the user specifies otherwise, and a drive with slug \"vetra\" is available, create new documents inside it by passing its ID as the \"driveId\" parameter to \"createDocument\".\n\nExamples:\n<example>Context: User needs to create a new document model for their application. user: 'I need to create a user profile document model with fields for name, email, and preferences' assistant: 'I'll use the reactor-mcp-server to help you create this document model.' <commentary>Since the user is requesting document model creation, use the reactor-mcp-document-expert agent to ensure proper reactor-mcp tool usage.</commentary></example> <example>Context: User is building a content management system and needs create documents for certain types of document models. user: 'Can you help me create example documents for blog posts and categories document models?' assistant: 'Let me use the reactor-mcp-server to create these documents using the appropriate reactor-mcp tool calls.' <commentary>Document model creation requires the reactor-mcp-server tool calls to ensure compliance.</commentary></example>\n<example>Context: User needs to create a new document instance of a given document model. user: 'I need to create a demo user profile document' assistant: 'I'll use the reactor-mcp-server to help you create this document with example values.' <commentary>Since the user is requesting document model creation, use the reactor-mcp-document-expert agent to ensure proper reactor-mcp tool usage.</commentary></example> <example>Context: User is building a content management system and needs create documents for certain types of document models. user: 'Can you help me create example documents for blog posts and categories document models?' assistant: 'Let me use the reactor-mcp-server to create these documents using the appropriate reactor-mcp tool calls.' <commentary>Document creation requires the reactor-mcp-server tool calls to ensure compliance.</commentary></example>\n`;\n\nexport async function createServer(\n options: CreateServerOptions,\n): Promise<McpServer> {\n const { client, syncManager, subject } = options;\n const server = new McpServer(\n {\n name: \"reactor-mcp-server\",\n version: \"1.0.0\",\n description: ReactorMcpInstructions,\n },\n {\n capabilities: {\n tools: {},\n resources: {\n subscribe: true,\n listChanged: true,\n },\n prompts: {\n listChanged: true,\n },\n },\n },\n );\n\n server.registerResource(\n \"instructions\",\n \"reactor://instructions\",\n {\n title: \"Instructions\",\n description: \"General instructions on how to use the tools of this MCP\",\n mimeType: \"text/plain\",\n },\n (uri) => ({\n contents: [\n {\n uri: uri.href,\n text: ReactorMcpInstructions,\n },\n ],\n }),\n );\n\n const reactorProvider = await createReactorMcpProvider({\n client,\n syncManager,\n subject,\n });\n\n // const { callback, ...toolSchema } = reactorProvider.tools.getDocumentModels;\n // server.registerTool(\"getDocumentModels\", toolSchema, callback);\n Object.entries(reactorProvider.tools).forEach(\n ([toolName, { callback, ...schema }]) => {\n server.registerTool(toolName, schema as any, callback as any);\n },\n );\n\n return server;\n}\n"],"mappings":";;;;AAEA,MAAa,SAAkB,YAAY,CAAC,aAAa,CAAC;;;ACU1D,MAAa,yBAAyB;;;;;;;;;;;;;;;AAgBtC,eAAsB,aACpB,SACoB;CACpB,MAAM,EAAE,QAAQ,aAAa,YAAY;CACzC,MAAM,SAAS,IAAI,UACjB;EACE,MAAM;EACN,SAAS;EACT,aAAa;CACf,GACA,EACE,cAAc;EACZ,OAAO,CAAC;EACR,WAAW;GACT,WAAW;GACX,aAAa;EACf;EACA,SAAS,EACP,aAAa,KACf;CACF,EACF,CACF;CAEA,OAAO,iBACL,gBACA,0BACA;EACE,OAAO;EACP,aAAa;EACb,UAAU;CACZ,IACC,SAAS,EACR,UAAU,CACR;EACE,KAAK,IAAI;EACT,MAAM;CACR,CACF,EACF,EACF;CAEA,MAAM,kBAAkB,MAAM,yBAAyB;EACrD;EACA;EACA;CACF,CAAC;CAID,OAAO,QAAQ,gBAAgB,KAAK,CAAC,CAAC,SACnC,CAAC,UAAU,EAAE,UAAU,GAAG,cAAc;EACvC,OAAO,aAAa,UAAU,QAAe,QAAe;CAC9D,CACF;CAEA,OAAO;AACT"}
@@ -1,2 +1,3 @@
1
- import { _ as getDriveTool, a as ReactorMcpTools, c as addRemoteDriveTool, d as deleteDocumentTool, f as deleteDriveTool, g as getDocumentsTool, h as getDocumentTool, i as ReactorMcpProviderOptions, l as createDocumentTool, m as getDocumentModelsTool, n as toolWithCallback, o as addActionsTool, p as getDocumentModelSchemaTool, r as validateDocumentModelAction, s as addDriveTool, t as InvalidToolOutputError, u as createReactorMcpProvider, v as getDrivesTool } from "../index-DXl2_PJH.mjs";
2
- export { InvalidToolOutputError, ReactorMcpProviderOptions, ReactorMcpTools, addActionsTool, addDriveTool, addRemoteDriveTool, createDocumentTool, createReactorMcpProvider, deleteDocumentTool, deleteDriveTool, getDocumentModelSchemaTool, getDocumentModelsTool, getDocumentTool, getDocumentsTool, getDriveTool, getDrivesTool, toolWithCallback, validateDocumentModelAction };
1
+ import { _ as getDriveTool, a as ReactorMcpTools, c as addRemoteDriveTool, d as deleteDocumentTool, f as deleteDriveTool, g as getDocumentsTool, h as getDocumentTool, i as ReactorMcpProviderOptions, l as createDocumentTool, m as getDocumentModelsTool, n as toolWithCallback, o as addActionsTool, p as getDocumentModelSchemaTool, r as validateDocumentModelAction, s as addDriveTool, t as InvalidToolOutputError, u as createReactorMcpProvider, v as getDrivesTool } from "../index-CWO1xShX.mjs";
2
+ export { InvalidToolOutputError, ReactorMcpProviderOptions, ReactorMcpTools, addActionsTool, addDriveTool, addRemoteDriveTool, createDocumentTool, createReactorMcpProvider, deleteDocumentTool, deleteDriveTool, getDocumentModelSchemaTool, getDocumentModelsTool, getDocumentTool, getDocumentsTool, getDriveTool, getDrivesTool, toolWithCallback, validateDocumentModelAction };
3
+ export {};
@@ -1,2 +1,2 @@
1
- import { a as createReactorMcpProvider, c as getDocumentModelSchemaTool, d as getDocumentsTool, f as getDriveTool, g as validateDocumentModelAction, h as toolWithCallback, i as createDocumentTool, l as getDocumentModelsTool, m as InvalidToolOutputError, n as addDriveTool, o as deleteDocumentTool, p as getDrivesTool, r as addRemoteDriveTool, s as deleteDriveTool, t as addActionsTool, u as getDocumentTool } from "../reactor-BswnJgTi.mjs";
1
+ import { a as createReactorMcpProvider, c as getDocumentModelSchemaTool, d as getDocumentsTool, f as getDriveTool, g as validateDocumentModelAction, h as toolWithCallback, i as createDocumentTool, l as getDocumentModelsTool, m as InvalidToolOutputError, n as addDriveTool, o as deleteDocumentTool, p as getDrivesTool, r as addRemoteDriveTool, s as deleteDriveTool, t as addActionsTool, u as getDocumentTool } from "../reactor-CYKTrGtF.mjs";
2
2
  export { InvalidToolOutputError, addActionsTool, addDriveTool, addRemoteDriveTool, createDocumentTool, createReactorMcpProvider, deleteDocumentTool, deleteDriveTool, getDocumentModelSchemaTool, getDocumentModelsTool, getDocumentTool, getDocumentsTool, getDriveTool, getDrivesTool, toolWithCallback, validateDocumentModelAction };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/reactor-mcp",
3
- "version": "6.2.3-dev.24",
3
+ "version": "6.2.3-dev.26",
4
4
  "description": "MCP server for the Powerhouse reactor — exposes document model operations and drive management to AI coding assistants via the Model Context Protocol.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -50,19 +50,19 @@
50
50
  "@modelcontextprotocol/sdk": "1.29.0",
51
51
  "@openfeature/env-var-provider": "0.3.1",
52
52
  "@openfeature/server-sdk": "1.19.0",
53
- "@powerhousedao/reactor": "6.2.3-dev.24",
54
- "@powerhousedao/reactor-drive": "6.2.3-dev.24",
55
- "@powerhousedao/reactor-group": "6.2.3-dev.24",
56
- "@powerhousedao/shared": "6.2.3-dev.24",
53
+ "@powerhousedao/reactor": "6.2.3-dev.26",
54
+ "@powerhousedao/reactor-drive": "6.2.3-dev.26",
55
+ "@powerhousedao/reactor-group": "6.2.3-dev.26",
56
+ "@powerhousedao/shared": "6.2.3-dev.26",
57
57
  "change-case": "5.4.4",
58
- "document-model": "6.2.3-dev.24",
59
- "vite": "8.0.10",
58
+ "document-model": "6.2.3-dev.26",
59
+ "vite": "8.3.0",
60
60
  "zod": "4.3.6"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@openfeature/core": "1.9.1",
64
64
  "@types/node": "25.2.3",
65
- "tsdown": "0.21.1",
65
+ "tsdown": "0.23.0",
66
66
  "vitest": "4.1.1"
67
67
  },
68
68
  "homepage": "https://academy.vetra.io",
@@ -1 +0,0 @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9B,QAAA,EAAU,CAAA,CAAE,QAAA;AAAA;;AFH1B;;;;;;;iBEkBgB,gBAAA,WAA2B,UAAA,CAAA,CACzC,IAAA,EAAM,CAAA,EACN,YAAA,GACE,IAAA,EAAM,gBAAA,CAAiB,CAAA,qBAErB,gBAAA,CAAiB,CAAA,oBACjB,OAAA,CAAQ,gBAAA,CAAiB,CAAA,qBAAmB,CAAA;mBAGxC,gBAAA,CAAiB,CAAA,qBACtB,OAAA,CAAQ,cAAA;AAAA;AAAA,iBAgCG,2BAAA,CACd,mBAAA,EAAqB,mBAAA,EACrB,MAAA,EAAQ,MAAA;EACL,OAAA;EAAkB,MAAA;AAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reactor-BswnJgTi.mjs","names":[],"sources":["../src/tools/utils.ts","../src/tools/reactor.ts"],"sourcesContent":["import type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { camelCase } from \"change-case\";\nimport type {\n Action,\n DocumentModelModule,\n Operation,\n} from \"@powerhousedao/shared/document-model\";\nimport type { z } from \"zod\";\nimport type { ResolveZodSchema, ToolSchema } from \"./types.js\";\n\nexport class InvalidToolOutputError extends Error {\n constructor(zodError: z.ZodError) {\n super(\"Invalid tool output\\n\" + zodError.message);\n this.name = \"InvalidToolOutputError\";\n this.cause = zodError;\n }\n}\n\n/**\n * Creates a tool with a callback function that handles the tool execution,\n * ensuring the output is valid and errors are handled and returned correctly.\n * @param tool The tool schema to wrap.\n * @param toolCallback The callback function to execute when the tool is called.\n * @returns A CallToolResult with structuredContent if OutputSchema is defined or content if undefined. If the\n * callback throws an error, the result will have isError set to true and the error message in the content.\n */\nexport function toolWithCallback<T extends ToolSchema>(\n tool: T,\n toolCallback: (\n args: ResolveZodSchema<T[\"inputSchema\"]>,\n ) =>\n | ResolveZodSchema<T[\"outputSchema\"]>\n | Promise<ResolveZodSchema<T[\"outputSchema\"]>>,\n) {\n const wrappedCallback = async (\n args: ResolveZodSchema<T[\"inputSchema\"]>,\n ): Promise<CallToolResult> => {\n try {\n const result = await toolCallback(args);\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(result),\n },\n ],\n structuredContent: result,\n } as const satisfies CallToolResult;\n } catch (error) {\n const errorString =\n error instanceof Error ? error.message : String(error);\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Error: ${errorString}`,\n },\n ],\n } as const satisfies CallToolResult;\n }\n };\n return {\n ...tool,\n callback: wrappedCallback,\n };\n}\n\nexport function validateDocumentModelAction(\n documentModelModule: DocumentModelModule,\n action: Action,\n): { isValid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n const globalState = documentModelModule.documentModel.global;\n\n // Get the latest specification\n if (!globalState.specifications || globalState.specifications.length === 0) {\n errors.push(\"Document model has no specifications\");\n return { isValid: false, errors };\n }\n\n const latestSpec =\n globalState.specifications[globalState.specifications.length - 1];\n\n // Search through modules to find the operation that matches the action type (in SCREAMING_SNAKE_CASE)\n let operation: (Operation & { scope: string }) | null = null;\n\n for (const module of latestSpec.modules) {\n const unsafeOperationOrActionOrSomething = module.operations.find(\n (op) => op.name === action.type,\n ) as unknown as Operation & { scope: string };\n if (unsafeOperationOrActionOrSomething) {\n operation = unsafeOperationOrActionOrSomething;\n break;\n }\n }\n\n if (!operation) {\n errors.push(\n `Operation \"${action.type}\" is not defined in any module of the document model`,\n );\n return { isValid: false, errors };\n }\n\n // Convert action type from SCREAMING_SNAKE_CASE to camelCase to match action creators\n const camelCaseActionType = camelCase(action.type);\n\n // Check if action creator exists in documentModelModule.actions\n const actionCreator = documentModelModule.actions[camelCaseActionType];\n\n if (!actionCreator) {\n errors.push(\n `Action creator \"${camelCaseActionType}\" for action type \"${action.type}\" is not defined in documentModelDocumentModelModule.actions`,\n );\n return { isValid: false, errors };\n }\n\n // Validate the operation using the action creator. TODO: Use document model exported validators directly\n let inputError: Error | null = null;\n try {\n actionCreator(action.input);\n } catch (e) {\n inputError = e instanceof Error ? e : new Error(JSON.stringify(e));\n }\n\n if (inputError) {\n errors.push(`Input validation error: ${inputError.message}`);\n }\n\n // Validate scope if operation defines one\n if (operation.scope && action.scope !== operation.scope) {\n errors.push(\n `Action scope \"${action.scope}\" does not match operation scope \"${operation.scope}\"`,\n );\n }\n\n return {\n isValid: errors.length === 0,\n errors,\n };\n}\n","import type { IReactorClient, ISyncManager } from \"@powerhousedao/reactor\";\nimport { DriveCollectionId } from \"@powerhousedao/reactor\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport {\n setAvailableOffline,\n setDriveIcon,\n setSharingType,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n Action,\n DocumentModelModule,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n createAction,\n withSignaturePolicy,\n} from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport type { ToolSchema, ToolWithCallback } from \"./types.js\";\nimport { toolWithCallback, validateDocumentModelAction } from \"./utils.js\";\n\nconst DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\";\n\nexport type ReactorMcpProviderOptions = {\n client: IReactorClient;\n syncManager?: ISyncManager;\n};\n\nexport const createDocumentTool = {\n name: \"createDocument\",\n description: `Create a new document.\n Unless the user specifies otherwise, and a drive named \"vetra\" is available, add the document to that drive by providing the drive's ID in the \"driveId\" parameter.\n When \"driveId\" is provided, the document is created and added to the drive atomically — no separate \"addActions\" call with \"ADD_FILE\" is needed.`,\n inputSchema: {\n documentType: z.string().describe(\"Type of the document to create\"),\n name: z\n .string()\n .optional()\n .describe(\n \"Optional name for the document. Used as both the document name and the drive node name when driveId is provided.\",\n ),\n driveId: z\n .string()\n .optional()\n .describe(\n \"Optional drive ID or slug. When provided, the document is created and added to the drive atomically.\",\n ),\n parentFolder: z\n .string()\n .optional()\n .describe(\n \"Optional folder ID within the drive to place the document in. Only used when driveId is provided.\",\n ),\n },\n outputSchema: {\n documentId: z.string().describe(\"ID of the created document\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDocumentTool = {\n name: \"getDocument\",\n description: \"Retrieve a document by its ID\",\n inputSchema: {\n id: z.string().describe(\"ID of the document to retrieve\"),\n },\n outputSchema: {\n document: z.unknown().describe(\"The retrieved Document\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDocumentsTool = {\n name: \"getDocuments\",\n description: \"List documents in a drive\",\n inputSchema: {\n parentId: z.string().describe(\"ID of the drive\"),\n },\n outputSchema: {\n documentIds: z.array(z.string()).describe(\"Array of document IDs\"),\n },\n} as const satisfies ToolSchema;\n\nexport const deleteDocumentTool = {\n name: \"deleteDocument\",\n description: \"Delete a document\",\n inputSchema: {\n documentId: z.string().describe(\"ID of the document to delete\"),\n },\n outputSchema: {\n success: z.boolean().describe(\"Whether the deletion was successful\"),\n },\n} as const satisfies ToolSchema;\n\nexport const addActionsTool = {\n name: \"addActions\",\n description:\n \"Adds actions to a document. Prefer adding multiples actions at once to reduce the number of steps.\",\n inputSchema: {\n documentId: z.string().describe(\"ID of the document\"),\n actions: z\n .array(\n z\n .object({\n type: z.string().describe(\"The name of the action\"),\n input: z.unknown().describe(\"The payload of the action\"),\n scope: z.string().describe(\"The scope of the action\"),\n context: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Optional action context\"), // TODO: Define context schema\n })\n .strict(),\n )\n .describe(\"Action to add to the document\"),\n },\n outputSchema: {\n success: z.boolean().describe(\"Whether the actions were added\"),\n },\n} as const satisfies ToolSchema;\n\n// export const addOperationTool = {\n// name: \"addOperation\",\n// description: \"Add an operation to a document\",\n// inputSchema: {\n// documentId: z.string().describe(\"ID of the document\"),\n// operation: z\n// .object({\n// type: z.string().describe(\"The name of the action\"),\n// input: z.unknown().describe(\"The payload of the action\"),\n// scope: z.string().describe(\"The scope of the action\"),\n// index: z.number().describe(\"Position of the operation in the history\"),\n// timestampUtcMs: z\n// .string()\n// .describe(\"Timestamp of when the operation was added\"),\n// hash: z.string().describe(\"Hash of the resulting document data\"),\n// skip: z.number().describe(\"The number of operations skipped\"),\n// error: z\n// .string()\n// .optional()\n// .describe(\"Error message for a failed action\"),\n// id: z.string().optional().describe(\"Unique operation id\"),\n// context: z.object({}).optional().describe(\"Optional action context\"), // TODO: Define context schema\n// })\n// .strict()\n// .describe(\"Operation to add to the document\"),\n// },\n// outputSchema: {\n// result: z\n// .object({\n// status: z\n// .enum([\"SUCCESS\", \"CONFLICT\", \"MISSING\", \"ERROR\"])\n// .describe(\"Operation status\"),\n// error: z\n// .string()\n// .optional()\n// .describe(\"Error details if operation failed\"), // TODO: Define error schema\n// operations: z\n// .array(z.object({}))\n// .describe(\"Array of operations created\"), // TODO: Define operation schema\n// document: z.object({}).optional().describe(\"Updated document\"), // TODO: Define document schema\n// signals: z.array(z.object({})).describe(\"Array of signals generated\"), // TODO: Define signal schema\n// })\n// .describe(\"Operation result\"),\n// },\n// } as const satisfies ToolSchema;\n\n// Drive Operation Tools\n\nexport const getDrivesTool = {\n name: \"getDrives\",\n description: \"List all drives\",\n inputSchema: {},\n outputSchema: {\n driveIds: z.array(z.string()).describe(\"Array of drive IDs\"),\n },\n} as const satisfies ToolSchema;\n\nexport const addDriveTool = {\n name: \"addDrive\",\n description: \"Create a new drive\",\n inputSchema: {\n driveInput: z\n .object({\n global: z\n .object({\n name: z.string().describe(\"Name of the drive\"),\n icon: z\n .string()\n .nullable()\n .optional()\n .describe(\"Optional icon for the drive\"),\n })\n .describe(\"Global drive properties\"),\n preferredEditor: z\n .string()\n .optional()\n .describe(\n \"Optional app/editor module id recorded as the drive's preferred editor\",\n ),\n local: z\n .object({\n availableOffline: z\n .boolean()\n .optional()\n .describe(\"Whether drive is available offline\"),\n sharingType: z\n .string()\n .nullable()\n .optional()\n .describe(\"Sharing type\"),\n })\n .optional()\n .describe(\"Optional local state properties\"),\n })\n .describe(\"Drive configuration\"),\n },\n outputSchema: {\n driveId: z.string().describe(\"ID of the created drive\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDriveTool = {\n name: \"getDrive\",\n description: \"Get a specific drive\",\n inputSchema: {\n driveId: z.string().describe(\"ID of the drive to retrieve\"),\n options: z\n .object({\n revisions: z\n .record(z.string(), z.number())\n .optional()\n .describe(\"Optional revision filter\"),\n checkHashes: z.boolean().optional().describe(\"Whether to check hashes\"),\n // TODO: Add other ReducerOptions if needed\n })\n .optional()\n .describe(\"Optional get document options\"),\n },\n outputSchema: {\n drive: z.unknown().describe(\"Drive document\"), // TODO: Define DocumentDriveDocument schema\n },\n} as const satisfies ToolSchema;\n\nexport const deleteDriveTool = {\n name: \"deleteDrive\",\n description: \"Delete a drive\",\n inputSchema: {\n driveId: z.string().describe(\"ID of the drive to delete\"),\n },\n outputSchema: {\n success: z.boolean().describe(\"Whether the deletion was successful\"),\n },\n} as const satisfies ToolSchema;\n\nexport const addRemoteDriveTool = {\n name: \"addRemoteDrive\",\n description: \"Connect to a remote drive\",\n inputSchema: {\n url: z.string().describe(\"URL of the remote drive\"),\n options: z\n .object({\n availableOffline: z\n .boolean()\n .describe(\"Whether drive is available offline\"),\n sharingType: z.string().nullable().optional().describe(\"Sharing type\"),\n pullFilter: z\n .object({\n branch: z\n .array(z.string())\n .nullable()\n .optional()\n .describe(\"Branch filter\"),\n documentId: z\n .array(z.string())\n .nullable()\n .optional()\n .describe(\"Document ID filter\"),\n documentType: z\n .array(z.string())\n .nullable()\n .optional()\n .describe(\"Document type filter\"),\n scope: z\n .array(z.string())\n .nullable()\n .optional()\n .describe(\"Scope filter\"),\n })\n .optional()\n .describe(\"Optional pull filter\"),\n pullInterval: z\n .number()\n .optional()\n .describe(\"Pull interval in milliseconds\"),\n })\n .describe(\"Remote drive options\"),\n },\n outputSchema: {\n driveId: z.string().describe(\"ID of the added remote drive\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDocumentModelSchemaTool = {\n name: \"getDocumentModelSchema\",\n description: \"Get the schema of a document model\",\n inputSchema: {\n type: z.string().describe(\"Type of the document model\"),\n },\n outputSchema: {\n schema: z.unknown().describe(\"Schema of the document model\"),\n },\n} as const satisfies ToolSchema;\n\nexport const getDocumentModelsTool = {\n name: \"getDocumentModels\",\n description: \"Get the list of document models\",\n inputSchema: {},\n outputSchema: {\n documentModels: z\n .array(\n z.object({\n name: z.string().describe(\"Name of the document model\"),\n type: z.string().describe(\"Type of the document model\"),\n description: z.string().describe(\"Description of the document model\"),\n extension: z.string().describe(\"Extension of the document model\"),\n authorName: z.string().describe(\"Author name of the document model\"),\n authorWebsite: z\n .string()\n .describe(\"Author website of the document model\"),\n }),\n )\n .describe(\"List of available document models\"),\n },\n} as const satisfies ToolSchema;\n\ntype ToolRecord<T extends readonly ToolSchema[]> = {\n [K in T[number][\"name\"]]: ToolWithCallback<Extract<T[number], { name: K }>>;\n};\n\n// All tools array for type inference\nconst _allTools = [\n getDocumentTool,\n createDocumentTool,\n getDocumentsTool,\n deleteDocumentTool,\n addActionsTool,\n // addOperationTool,\n getDrivesTool,\n addDriveTool,\n getDriveTool,\n deleteDriveTool,\n addRemoteDriveTool,\n getDocumentModelSchemaTool,\n getDocumentModelsTool,\n] as const;\n\n// Inferred interface from tools\nexport type ReactorMcpTools = ToolRecord<typeof _allTools>;\n\nexport function createReactorMcpProvider(options: ReactorMcpProviderOptions) {\n const { client, syncManager } = options;\n // No initialization needed - client is already initialized\n\n function getDocumentModelModule(documentType: string) {\n return client.getDocumentModelModule(documentType);\n }\n\n const tools = {\n getDocument: toolWithCallback(getDocumentTool, async (params) => {\n const document = await client.get<PHDocument>(params.id);\n return { document: { header: document.header, state: document.state } };\n }),\n\n createDocument: toolWithCallback(createDocumentTool, async (params) => {\n if (params.driveId) {\n const module = await getDocumentModelModule(params.documentType);\n if (!module) {\n throw new Error(\n `Document model for type '${params.documentType}' not found`,\n );\n }\n const document = withSignaturePolicy(\n module.utils.createDocument(),\n await client.getCreateSignaturePolicy(),\n );\n if (params.name) {\n document.header.name = params.name;\n }\n const created = await client.drives.addFile(\n params.driveId,\n document,\n params.parentFolder,\n );\n return { documentId: created.header.id };\n }\n\n const created = await client.createEmpty(params.documentType, {});\n return { documentId: created.header.id };\n }),\n\n getDocuments: toolWithCallback(getDocumentsTool, async (params) => {\n const result = await client.getOutgoingRelationships(\n params.parentId,\n \"child\",\n );\n const documentIds = result.results.map((doc) => doc.header.id);\n return { documentIds };\n }),\n\n deleteDocument: toolWithCallback(deleteDocumentTool, async (params) => {\n try {\n const incoming = await client.getIncomingRelationships(\n params.documentId,\n \"child\",\n );\n const driveParent = incoming.results.find(\n (p) => p.header.documentType === DRIVE_DOCUMENT_TYPE,\n );\n if (driveParent) {\n await client.drives.removeNode(\n driveParent.header.id,\n params.documentId,\n );\n } else {\n await client.deleteDocument(params.documentId);\n }\n return { success: true };\n } catch {\n return { success: false };\n }\n }),\n\n addActions: toolWithCallback(addActionsTool, async (params) => {\n const document = await client.get<PHDocument>(params.documentId);\n const documentModel = await getDocumentModelModule(\n document.header.documentType,\n );\n if (!documentModel) {\n throw new Error(\n `Document model for document type '${document.header.documentType}' not found`,\n );\n }\n const actions: Action[] = params.actions.map((paramAction) => {\n const action: Action = createAction(\n paramAction.type,\n paramAction.input ?? {},\n undefined,\n undefined,\n paramAction.scope,\n );\n const actionValidation = validateDocumentModelAction(\n documentModel,\n action,\n );\n if (!actionValidation.isValid) {\n throw new Error(\n `Invalid action ${JSON.stringify(action)}: ${actionValidation.errors.join(\", \")}`,\n );\n }\n return action;\n });\n\n // Execute actions on the document using the \"main\" branch\n await client.execute(params.documentId, \"main\", actions);\n\n return {\n success: true,\n };\n }),\n\n // Drive operation implementations\n getDrives: toolWithCallback(getDrivesTool, async () => {\n // Find all documents of type \"powerhouse/document-drive\"\n const result = await client.find({ type: DRIVE_DOCUMENT_TYPE });\n const driveIds = result.results.map((doc: PHDocument) => doc.header.id);\n return { driveIds };\n }),\n\n addDrive: toolWithCallback(addDriveTool, async (params) => {\n const { driveInput } = params;\n const drive = await client.createEmpty<DocumentDriveDocument>(\n DRIVE_DOCUMENT_TYPE,\n {},\n );\n const driveId = drive.header.id;\n\n if (driveInput.global.name) {\n await client.rename(driveId, driveInput.global.name);\n }\n if (driveInput.preferredEditor) {\n await client.setPreferredEditor(driveId, driveInput.preferredEditor);\n }\n\n const actions: Action[] = [];\n if (driveInput.global.icon) {\n actions.push(setDriveIcon({ icon: driveInput.global.icon }));\n }\n if (driveInput.local?.sharingType) {\n actions.push(setSharingType({ type: driveInput.local.sharingType }));\n }\n if (driveInput.local?.availableOffline !== undefined) {\n actions.push(\n setAvailableOffline({\n availableOffline: driveInput.local.availableOffline,\n }),\n );\n }\n if (actions.length > 0) {\n await client.execute(driveId, \"main\", actions);\n }\n\n return { driveId };\n }),\n\n getDrive: toolWithCallback(getDriveTool, async (params) => {\n const drive = await client.get<DocumentDriveDocument>(params.driveId);\n return { drive: { header: drive.header, state: drive.state } };\n }),\n\n deleteDrive: toolWithCallback(deleteDriveTool, async (params) => {\n try {\n // Use CASCADE to delete the drive and all its contents\n await client.deleteDocument(params.driveId);\n return { success: true };\n } catch {\n return { success: false };\n }\n }),\n\n addRemoteDrive: toolWithCallback(addRemoteDriveTool, async (params) => {\n if (!syncManager) {\n throw new Error(\n \"Remote drive management is not available. \" +\n \"SyncManager was not configured for this MCP server.\",\n );\n }\n\n // Fetch drive info from the REST endpoint to get both id and graphqlEndpoint\n const response = await fetch(params.url);\n if (!response.ok) {\n throw new Error(`Failed to resolve drive info from ${params.url}`);\n }\n const driveInfo = (await response.json()) as {\n id: string;\n graphqlEndpoint: string;\n };\n\n const resolvedDriveId = driveInfo.id;\n const collectionId = DriveCollectionId.forDrive(resolvedDriveId);\n\n // Check if remote already exists\n const existingRemote = syncManager\n .list()\n .find((remote) => remote.meta.collectionId.equals(collectionId));\n if (existingRemote) {\n return { driveId: resolvedDriveId };\n }\n\n // Add the remote via SyncManager\n const remoteName = `mcp-remote-${crypto.randomUUID()}`;\n await syncManager.add(remoteName, collectionId, {\n type: \"gql\",\n parameters: {\n url: driveInfo.graphqlEndpoint,\n },\n });\n\n return { driveId: resolvedDriveId };\n }),\n\n getDocumentModels: toolWithCallback(getDocumentModelsTool, async () => {\n const result = await client.getDocumentModelModules();\n return {\n documentModels: result.results.map((model: DocumentModelModule) => {\n const schemaGlobal = model.documentModel.global;\n return {\n name: schemaGlobal.name,\n type: schemaGlobal.id,\n description: schemaGlobal.description,\n extension: schemaGlobal.extension,\n authorName: schemaGlobal.author.name,\n authorWebsite: schemaGlobal.author.website ?? \"\",\n };\n }),\n };\n }),\n\n getDocumentModelSchema: toolWithCallback(\n getDocumentModelSchemaTool,\n async (params) => {\n const documentModel = await getDocumentModelModule(params.type);\n const schema = documentModel?.documentModel.global;\n if (!schema) {\n throw new Error(`Document model '${params.type}' not found`);\n }\n return { schema };\n },\n ),\n } as const;\n\n const resources = {};\n\n const prompts = {};\n\n return Promise.resolve({\n tools,\n resources,\n prompts,\n } as const);\n}\n"],"mappings":";;;;;;AAUA,IAAa,yBAAb,cAA4C,MAAM;CAChD,YAAY,UAAsB;AAChC,QAAM,0BAA0B,SAAS,QAAQ;AACjD,OAAK,OAAO;AACZ,OAAK,QAAQ;;;;;;;;;;;AAYjB,SAAgB,iBACd,MACA,cAKA;CACA,MAAM,kBAAkB,OACtB,SAC4B;AAC5B,MAAI;GACF,MAAM,SAAS,MAAM,aAAa,KAAK;AACvC,UAAO;IACL,SAAS,CACP;KACE,MAAM;KACN,MAAM,KAAK,UAAU,OAAO;KAC7B,CACF;IACD,mBAAmB;IACpB;WACM,OAAO;AAGd,UAAO;IACL,SAAS;IACT,SAAS,CACP;KACE,MAAM;KACN,MAAM,UANV,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;KAOnD,CACF;IACF;;;AAGL,QAAO;EACL,GAAG;EACH,UAAU;EACX;;AAGH,SAAgB,4BACd,qBACA,QACwC;CACxC,MAAM,SAAmB,EAAE;CAE3B,MAAM,cAAc,oBAAoB,cAAc;AAGtD,KAAI,CAAC,YAAY,kBAAkB,YAAY,eAAe,WAAW,GAAG;AAC1E,SAAO,KAAK,uCAAuC;AACnD,SAAO;GAAE,SAAS;GAAO;GAAQ;;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AAiB,uBAAuB,YAAY;AAErE,UAAO,EACL,iBAFa,MAAM,OAAO,yBAAyB,EAE5B,QAAQ,KAAK,UAA+B;IACjE,MAAM,eAAe,MAAM,cAAc;AACzC,WAAO;KACL,MAAM,aAAa;KACnB,MAAM,aAAa;KACnB,aAAa,aAAa;KAC1B,WAAW,aAAa;KACxB,YAAY,aAAa,OAAO;KAChC,eAAe,aAAa,OAAO,WAAW;KAC/C;KACD,EACH;IACD;EAEF,wBAAwB,iBACtB,4BACA,OAAO,WAAW;GAEhB,MAAM,UADgB,MAAM,uBAAuB,OAAO,KAAK,GACjC,cAAc;AAC5C,OAAI,CAAC,OACH,OAAM,IAAI,MAAM,mBAAmB,OAAO,KAAK,aAAa;AAE9D,UAAO,EAAE,QAAQ;IAEpB;EACF;AAMD,QAAO,QAAQ,QAAQ;EACrB;EACA,WANgB,EAAE;EAOlB,SALc,EAAE;EAMjB,CAAU"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"server-Dtbb-8Dy.mjs","names":[],"sources":["../src/logger.ts","../src/server.ts"],"sourcesContent":["import { childLogger, type ILogger } from \"document-model\";\n\nexport const logger: ILogger = childLogger([\"reactor-mcp\"]);\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { IReactorClient, ISyncManager } from \"@powerhousedao/reactor\";\nimport { createReactorMcpProvider } from \"./tools/reactor.js\";\n\nexport interface CreateServerOptions {\n client: IReactorClient;\n syncManager?: ISyncManager;\n}\n\nexport const ReactorMcpInstructions = `MUST BE USED when handling documents or document-models for the Powerhouse/Vetra ecosystem.\nThere are 5 main concepts to know of: \n- Document Model: A template for creating documents. It defines the schema and allowed operations for a type of document.\n- Document: An instance of a document model. It contains actual data following the structure defined by the document model and can be changed using operations.\n- Drive: A document of type \"powerhouse/document-drive\" which represents a collection of documents and folders. To create a document inside a drive, use the \"createDocument\" tool with the \"driveId\" parameter — this handles everything atomically. Use \"addActions\" with \"ADD_FILE\" only when adding an existing document to a drive.\n- Action: A proposed change to a document. It is a JSON object with the action name and input that defines the action to be taken on the document. Should be dispatched by calling the \"addActions\" tool.\n- Operation: A change done to a document. It contains the action object plus additional metadata such as the index of the operation in the document history, the timestamp it was added, the hash of the resulting document data, the number of operations skipped, and the error message if the operation failed. Actions dispatched with \"addActions\" get converted into an operation.\n\nWhen planning to add multiple actions to a document, try to reduce the number of \"addActions\" calls to a minimum by adding multiple actions at once.\nUnless the user specifies otherwise, and a drive with slug \"vetra\" is available, create new documents inside it by passing its ID as the \"driveId\" parameter to \"createDocument\".\n\nExamples:\n<example>Context: User needs to create a new document model for their application. user: 'I need to create a user profile document model with fields for name, email, and preferences' assistant: 'I'll use the reactor-mcp-server to help you create this document model.' <commentary>Since the user is requesting document model creation, use the reactor-mcp-document-expert agent to ensure proper reactor-mcp tool usage.</commentary></example> <example>Context: User is building a content management system and needs create documents for certain types of document models. user: 'Can you help me create example documents for blog posts and categories document models?' assistant: 'Let me use the reactor-mcp-server to create these documents using the appropriate reactor-mcp tool calls.' <commentary>Document model creation requires the reactor-mcp-server tool calls to ensure compliance.</commentary></example>\n<example>Context: User needs to create a new document instance of a given document model. user: 'I need to create a demo user profile document' assistant: 'I'll use the reactor-mcp-server to help you create this document with example values.' <commentary>Since the user is requesting document model creation, use the reactor-mcp-document-expert agent to ensure proper reactor-mcp tool usage.</commentary></example> <example>Context: User is building a content management system and needs create documents for certain types of document models. user: 'Can you help me create example documents for blog posts and categories document models?' assistant: 'Let me use the reactor-mcp-server to create these documents using the appropriate reactor-mcp tool calls.' <commentary>Document creation requires the reactor-mcp-server tool calls to ensure compliance.</commentary></example>\n`;\n\nexport async function createServer(\n options: CreateServerOptions,\n): Promise<McpServer> {\n const { client, syncManager } = options;\n const server = new McpServer(\n {\n name: \"reactor-mcp-server\",\n version: \"1.0.0\",\n description: ReactorMcpInstructions,\n },\n {\n capabilities: {\n tools: {},\n resources: {\n subscribe: true,\n listChanged: true,\n },\n prompts: {\n listChanged: true,\n },\n },\n },\n );\n\n server.registerResource(\n \"instructions\",\n \"reactor://instructions\",\n {\n title: \"Instructions\",\n description: \"General instructions on how to use the tools of this MCP\",\n mimeType: \"text/plain\",\n },\n (uri) => ({\n contents: [\n {\n uri: uri.href,\n text: ReactorMcpInstructions,\n },\n ],\n }),\n );\n\n const reactorProvider = await createReactorMcpProvider({\n client,\n syncManager,\n });\n\n // const { callback, ...toolSchema } = reactorProvider.tools.getDocumentModels;\n // server.registerTool(\"getDocumentModels\", toolSchema, callback);\n Object.entries(reactorProvider.tools).forEach(\n ([toolName, { callback, ...schema }]) => {\n server.registerTool(toolName, schema as any, callback as any);\n },\n );\n\n return server;\n}\n"],"mappings":";;;;AAEA,MAAa,SAAkB,YAAY,CAAC,cAAc,CAAC;;;ACO3D,MAAa,yBAAyB;;;;;;;;;;;;;;;AAgBtC,eAAsB,aACpB,SACoB;CACpB,MAAM,EAAE,QAAQ,gBAAgB;CAChC,MAAM,SAAS,IAAI,UACjB;EACE,MAAM;EACN,SAAS;EACT,aAAa;EACd,EACD,EACE,cAAc;EACZ,OAAO,EAAE;EACT,WAAW;GACT,WAAW;GACX,aAAa;GACd;EACD,SAAS,EACP,aAAa,MACd;EACF,EACF,CACF;AAED,QAAO,iBACL,gBACA,0BACA;EACE,OAAO;EACP,aAAa;EACb,UAAU;EACX,GACA,SAAS,EACR,UAAU,CACR;EACE,KAAK,IAAI;EACT,MAAM;EACP,CACF,EACF,EACF;CAED,MAAM,kBAAkB,MAAM,yBAAyB;EACrD;EACA;EACD,CAAC;AAIF,QAAO,QAAQ,gBAAgB,MAAM,CAAC,SACnC,CAAC,UAAU,EAAE,UAAU,GAAG,cAAc;AACvC,SAAO,aAAa,UAAU,QAAe,SAAgB;GAEhE;AAED,QAAO"}