@strapi/core 5.60.0 → 5.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/package.json.js +16 -20
- package/dist/package.json.js.map +1 -1
- package/dist/package.json.mjs +16 -20
- package/dist/package.json.mjs.map +1 -1
- package/dist/providers/webhooks.d.ts.map +1 -1
- package/dist/providers/webhooks.js +1 -0
- package/dist/providers/webhooks.js.map +1 -1
- package/dist/providers/webhooks.mjs +1 -0
- package/dist/providers/webhooks.mjs.map +1 -1
- package/dist/services/document-service/events.d.ts.map +1 -1
- package/dist/services/document-service/events.js +2 -1
- package/dist/services/document-service/events.js.map +1 -1
- package/dist/services/document-service/events.mjs +2 -1
- package/dist/services/document-service/events.mjs.map +1 -1
- package/dist/services/entity-validator/index.d.ts.map +1 -1
- package/dist/services/entity-validator/index.js +35 -4
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs +35 -4
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/mcp/handlers/handlePost.d.ts.map +1 -1
- package/dist/services/mcp/handlers/handlePost.js +2 -1
- package/dist/services/mcp/handlers/handlePost.js.map +1 -1
- package/dist/services/mcp/handlers/handlePost.mjs +2 -1
- package/dist/services/mcp/handlers/handlePost.mjs.map +1 -1
- package/dist/services/mcp/internal/McpConfiguration.d.ts +2 -0
- package/dist/services/mcp/internal/McpConfiguration.d.ts.map +1 -1
- package/dist/services/mcp/internal/McpConfiguration.js +17 -0
- package/dist/services/mcp/internal/McpConfiguration.js.map +1 -1
- package/dist/services/mcp/internal/McpConfiguration.mjs +17 -1
- package/dist/services/mcp/internal/McpConfiguration.mjs.map +1 -1
- package/dist/services/mcp/internal/McpServerFactory.d.ts +3 -1
- package/dist/services/mcp/internal/McpServerFactory.d.ts.map +1 -1
- package/dist/services/mcp/internal/McpServerFactory.js +4 -2
- package/dist/services/mcp/internal/McpServerFactory.js.map +1 -1
- package/dist/services/mcp/internal/McpServerFactory.mjs +4 -2
- package/dist/services/mcp/internal/McpServerFactory.mjs.map +1 -1
- package/dist/services/webhook-runner.d.ts +5 -6
- package/dist/services/webhook-runner.d.ts.map +1 -1
- package/dist/services/webhook-runner.js +23 -6
- package/dist/services/webhook-runner.js.map +1 -1
- package/dist/services/webhook-runner.mjs +23 -6
- package/dist/services/webhook-runner.mjs.map +1 -1
- package/package.json +16 -20
|
@@ -33,7 +33,8 @@ const createPostHandler = (deps)=>{
|
|
|
33
33
|
isDevMode: config.isDevMode(),
|
|
34
34
|
ability: authResult.ability,
|
|
35
35
|
user: authResult.user,
|
|
36
|
-
toolSchemaScope: resolveToolSchemaScope(requestBody)
|
|
36
|
+
toolSchemaScope: resolveToolSchemaScope(requestBody),
|
|
37
|
+
maxToolInputElements: config.maxToolInputElements
|
|
37
38
|
});
|
|
38
39
|
const transport = new NodeStreamableHTTPServerTransport({
|
|
39
40
|
sessionIdGenerator: undefined
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlePost.mjs","sources":["../../../../src/services/mcp/handlers/handlePost.ts"],"sourcesContent":["import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';\nimport type { Core } from '@strapi/types';\nimport {\n classifyMcpRequestFailure,\n sendDidNotAuthenticateMcpRequest,\n sendDidNotHandleMcpRequest,\n sendDidUseMcpServer,\n} from '../metrics/metrics';\nimport { sendJsonRpcError } from '../utils/sendJsonRpcError';\nimport { withTimeout } from '../utils/withTimeout';\nimport { resolveToolSchemaScope } from '../internal/resolveToolSchemaScope';\nimport type { McpHandlerDependencies } from './types';\n\nexport const createPostHandler = (deps: McpHandlerDependencies): Core.MiddlewareHandler => {\n const {\n strapi,\n authenticationStrategy,\n config,\n createServerWithRegistries,\n capabilityDefinitions,\n } = deps;\n\n return async (ctx) => {\n // Opt out of Koa's response phase — the MCP SDK writes directly to ctx.res\n // (via res.writeHead / res.end / SSE streaming). Without this, Koa's respond()\n // would also try to write ctx.body to the socket after the handler returns.\n ctx.respond = false;\n const req = ctx.req;\n const res = ctx.res;\n\n let hadAuthenticatedMcpRequest = false;\n\n try {\n const authResult = await authenticationStrategy.authenticate(ctx);\n if (authResult.authenticated === false) {\n sendDidNotAuthenticateMcpRequest(strapi, authResult.reason);\n sendJsonRpcError(res, 'AUTHENTICATION_REQUIRED');\n return;\n }\n\n hadAuthenticatedMcpRequest = true;\n sendDidUseMcpServer(strapi);\n\n // Let audit logs pick up MCP actions and tag their origin.\n ctx.state.user = authResult.user;\n ctx.state.auditSource = 'mcp';\n\n const requestBody = ctx.request.body ?? null;\n const { mcpServer } = createServerWithRegistries({\n strapi,\n definitions: capabilityDefinitions,\n isDevMode: config.isDevMode(),\n ability: authResult.ability,\n user: authResult.user,\n toolSchemaScope: resolveToolSchemaScope(requestBody),\n });\n\n const transport = new NodeStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n });\n\n try {\n await withTimeout(\n mcpServer.connect(transport),\n config.connectTimeoutMs,\n 'mcpServer.connect'\n );\n\n await withTimeout(\n transport.handleRequest(req, res, requestBody),\n config.requestTimeoutMs,\n 'transport.handleRequest'\n );\n } finally {\n await mcpServer.close();\n }\n } catch (error) {\n strapi.log.error('[MCP] Error handling POST request', {\n error: error instanceof Error ? error.message : 'Unknown error',\n stack: error instanceof Error ? error.stack : undefined,\n });\n\n sendJsonRpcError(res, 'INTERNAL_ERROR');\n\n if (hadAuthenticatedMcpRequest) {\n sendDidNotHandleMcpRequest(strapi, classifyMcpRequestFailure(error));\n }\n }\n };\n};\n"],"names":["createPostHandler","deps","strapi","authenticationStrategy","config","createServerWithRegistries","capabilityDefinitions","ctx","respond","req","res","hadAuthenticatedMcpRequest","authResult","authenticate","authenticated","sendDidNotAuthenticateMcpRequest","reason","sendJsonRpcError","sendDidUseMcpServer","state","user","auditSource","requestBody","request","body","mcpServer","definitions","isDevMode","ability","toolSchemaScope","resolveToolSchemaScope","transport","NodeStreamableHTTPServerTransport","sessionIdGenerator","undefined","withTimeout","connect","connectTimeoutMs","handleRequest","requestTimeoutMs","close","error","log","Error","message","stack","sendDidNotHandleMcpRequest","classifyMcpRequestFailure"],"mappings":";;;;;;AAaO,MAAMA,oBAAoB,CAACC,IAAAA,GAAAA;IAChC,MAAM,EACJC,MAAM,EACNC,sBAAsB,EACtBC,MAAM,EACNC,0BAA0B,EAC1BC,qBAAqB,EACtB,GAAGL,IAAAA;AAEJ,IAAA,OAAO,OAAOM,GAAAA,GAAAA;;;;AAIZA,QAAAA,GAAAA,CAAIC,OAAO,GAAG,KAAA;QACd,MAAMC,GAAAA,GAAMF,IAAIE,GAAG;QACnB,MAAMC,GAAAA,GAAMH,IAAIG,GAAG;AAEnB,QAAA,IAAIC,0BAAAA,GAA6B,KAAA;QAEjC,IAAI;AACF,YAAA,MAAMC,UAAAA,GAAa,MAAMT,sBAAAA,CAAuBU,YAAY,CAACN,GAAAA,CAAAA;YAC7D,IAAIK,UAAAA,CAAWE,aAAa,KAAK,KAAA,EAAO;gBACtCC,gCAAAA,CAAiCb,MAAAA,EAAQU,WAAWI,MAAM,CAAA;AAC1DC,gBAAAA,gBAAAA,CAAiBP,GAAAA,EAAK,yBAAA,CAAA;AACtB,gBAAA;AACF,YAAA;YAEAC,0BAAAA,GAA6B,IAAA;YAC7BO,mBAAAA,CAAoBhB,MAAAA,CAAAA;;AAGpBK,YAAAA,GAAAA,CAAIY,KAAK,CAACC,IAAI,GAAGR,WAAWQ,IAAI;YAChCb,GAAAA,CAAIY,KAAK,CAACE,WAAW,GAAG,KAAA;AAExB,YAAA,MAAMC,WAAAA,GAAcf,GAAAA,CAAIgB,OAAO,CAACC,IAAI,IAAI,IAAA;AACxC,YAAA,MAAM,EAAEC,SAAS,EAAE,GAAGpB,0BAAAA,CAA2B;AAC/CH,gBAAAA,MAAAA;gBACAwB,WAAAA,EAAapB,qBAAAA;AACbqB,gBAAAA,SAAAA,EAAWvB,OAAOuB,SAAS,EAAA;AAC3BC,gBAAAA,OAAAA,EAAShB,WAAWgB,OAAO;AAC3BR,gBAAAA,IAAAA,EAAMR,WAAWQ,IAAI;AACrBS,gBAAAA,eAAAA,EAAiBC,sBAAAA,CAAuBR,WAAAA;
|
|
1
|
+
{"version":3,"file":"handlePost.mjs","sources":["../../../../src/services/mcp/handlers/handlePost.ts"],"sourcesContent":["import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';\nimport type { Core } from '@strapi/types';\nimport {\n classifyMcpRequestFailure,\n sendDidNotAuthenticateMcpRequest,\n sendDidNotHandleMcpRequest,\n sendDidUseMcpServer,\n} from '../metrics/metrics';\nimport { sendJsonRpcError } from '../utils/sendJsonRpcError';\nimport { withTimeout } from '../utils/withTimeout';\nimport { resolveToolSchemaScope } from '../internal/resolveToolSchemaScope';\nimport type { McpHandlerDependencies } from './types';\n\nexport const createPostHandler = (deps: McpHandlerDependencies): Core.MiddlewareHandler => {\n const {\n strapi,\n authenticationStrategy,\n config,\n createServerWithRegistries,\n capabilityDefinitions,\n } = deps;\n\n return async (ctx) => {\n // Opt out of Koa's response phase — the MCP SDK writes directly to ctx.res\n // (via res.writeHead / res.end / SSE streaming). Without this, Koa's respond()\n // would also try to write ctx.body to the socket after the handler returns.\n ctx.respond = false;\n const req = ctx.req;\n const res = ctx.res;\n\n let hadAuthenticatedMcpRequest = false;\n\n try {\n const authResult = await authenticationStrategy.authenticate(ctx);\n if (authResult.authenticated === false) {\n sendDidNotAuthenticateMcpRequest(strapi, authResult.reason);\n sendJsonRpcError(res, 'AUTHENTICATION_REQUIRED');\n return;\n }\n\n hadAuthenticatedMcpRequest = true;\n sendDidUseMcpServer(strapi);\n\n // Let audit logs pick up MCP actions and tag their origin.\n ctx.state.user = authResult.user;\n ctx.state.auditSource = 'mcp';\n\n const requestBody = ctx.request.body ?? null;\n const { mcpServer } = createServerWithRegistries({\n strapi,\n definitions: capabilityDefinitions,\n isDevMode: config.isDevMode(),\n ability: authResult.ability,\n user: authResult.user,\n toolSchemaScope: resolveToolSchemaScope(requestBody),\n maxToolInputElements: config.maxToolInputElements,\n });\n\n const transport = new NodeStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n });\n\n try {\n await withTimeout(\n mcpServer.connect(transport),\n config.connectTimeoutMs,\n 'mcpServer.connect'\n );\n\n await withTimeout(\n transport.handleRequest(req, res, requestBody),\n config.requestTimeoutMs,\n 'transport.handleRequest'\n );\n } finally {\n await mcpServer.close();\n }\n } catch (error) {\n strapi.log.error('[MCP] Error handling POST request', {\n error: error instanceof Error ? error.message : 'Unknown error',\n stack: error instanceof Error ? error.stack : undefined,\n });\n\n sendJsonRpcError(res, 'INTERNAL_ERROR');\n\n if (hadAuthenticatedMcpRequest) {\n sendDidNotHandleMcpRequest(strapi, classifyMcpRequestFailure(error));\n }\n }\n };\n};\n"],"names":["createPostHandler","deps","strapi","authenticationStrategy","config","createServerWithRegistries","capabilityDefinitions","ctx","respond","req","res","hadAuthenticatedMcpRequest","authResult","authenticate","authenticated","sendDidNotAuthenticateMcpRequest","reason","sendJsonRpcError","sendDidUseMcpServer","state","user","auditSource","requestBody","request","body","mcpServer","definitions","isDevMode","ability","toolSchemaScope","resolveToolSchemaScope","maxToolInputElements","transport","NodeStreamableHTTPServerTransport","sessionIdGenerator","undefined","withTimeout","connect","connectTimeoutMs","handleRequest","requestTimeoutMs","close","error","log","Error","message","stack","sendDidNotHandleMcpRequest","classifyMcpRequestFailure"],"mappings":";;;;;;AAaO,MAAMA,oBAAoB,CAACC,IAAAA,GAAAA;IAChC,MAAM,EACJC,MAAM,EACNC,sBAAsB,EACtBC,MAAM,EACNC,0BAA0B,EAC1BC,qBAAqB,EACtB,GAAGL,IAAAA;AAEJ,IAAA,OAAO,OAAOM,GAAAA,GAAAA;;;;AAIZA,QAAAA,GAAAA,CAAIC,OAAO,GAAG,KAAA;QACd,MAAMC,GAAAA,GAAMF,IAAIE,GAAG;QACnB,MAAMC,GAAAA,GAAMH,IAAIG,GAAG;AAEnB,QAAA,IAAIC,0BAAAA,GAA6B,KAAA;QAEjC,IAAI;A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A,CAAAA,EAClClB,MAAAA,CAAOoC,gBAAgB,EACvB,yBAAA,CAAA;YAEJ,CAAA,QAAU;AACR,gBAAA,MAAMf,UAAUgB,KAAK,EAAA;AACvB,YAAA;AACF,QAAA,CAAA,CAAE,OAAOC,KAAAA,EAAO;AACdxC,YAAAA,MAAAA,CAAOyC,GAAG,CAACD,KAAK,CAAC,mCAAA,EAAqC;AACpDA,gBAAAA,KAAAA,EAAOA,KAAAA,YAAiBE,KAAAA,GAAQF,KAAAA,CAAMG,OAAO,GAAG,eAAA;AAChDC,gBAAAA,KAAAA,EAAOJ,KAAAA,YAAiBE,KAAAA,GAAQF,KAAAA,CAAMI,KAAK,GAAGX;AAChD,aAAA,CAAA;AAEAlB,YAAAA,gBAAAA,CAAiBP,GAAAA,EAAK,gBAAA,CAAA;AAEtB,YAAA,IAAIC,0BAAAA,EAA4B;AAC9BoC,gBAAAA,0BAAAA,CAA2B7C,QAAQ8C,yBAAAA,CAA0BN,KAAAA,CAAAA,CAAAA;AAC/D,YAAA;AACF,QAAA;AACF,IAAA,CAAA;AACF;;;;"}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { Core } from '@strapi/types';
|
|
2
|
+
export declare const DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10000;
|
|
2
3
|
export declare class McpConfiguration {
|
|
3
4
|
#private;
|
|
4
5
|
readonly path: string;
|
|
5
6
|
readonly connectTimeoutMs: number;
|
|
6
7
|
readonly requestTimeoutMs: number;
|
|
8
|
+
readonly maxToolInputElements: number;
|
|
7
9
|
constructor(strapi: Core.Strapi);
|
|
8
10
|
isEnabled(): boolean;
|
|
9
11
|
isDevMode(): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpConfiguration.d.ts","sourceRoot":"","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,qBAAa,gBAAgB;;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAElC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"McpConfiguration.d.ts","sourceRoot":"","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,eAAO,MAAM,+BAA+B,QAAS,CAAC;AAyBtD,qBAAa,gBAAgB;;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAElC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAElC,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;gBAI1B,MAAM,EAAE,IAAI,CAAC,MAAM;IAQ/B,SAAS,IAAI,OAAO;IAIpB,SAAS,IAAI,OAAO;CAGrB"}
|
|
@@ -10,6 +10,21 @@ var id = 0;
|
|
|
10
10
|
function _class_private_field_loose_key(name) {
|
|
11
11
|
return "__private_" + id++ + "_" + name;
|
|
12
12
|
}
|
|
13
|
+
const DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10000;
|
|
14
|
+
// The SDK throws on any value that is not a number >= 1, so only a valid value may reach it.
|
|
15
|
+
const resolveMaxToolInputElements = (strapi)=>{
|
|
16
|
+
const raw = strapi.config.get('server.mcp.maxToolInputElements');
|
|
17
|
+
if (raw === undefined) {
|
|
18
|
+
return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
19
|
+
}
|
|
20
|
+
// env() returns strings
|
|
21
|
+
const value = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;
|
|
22
|
+
if (value === Infinity || Number.isInteger(value) && value >= 1) {
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
strapi.log.warn(`[MCP] Invalid server.mcp.maxToolInputElements (${String(raw)}). ` + `Expected an integer >= 1 or Infinity. Using ${DEFAULT_MAX_TOOL_INPUT_ELEMENTS}.`);
|
|
26
|
+
return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
27
|
+
};
|
|
13
28
|
var _strapi = /*#__PURE__*/ _class_private_field_loose_key("_strapi");
|
|
14
29
|
class McpConfiguration {
|
|
15
30
|
isEnabled() {
|
|
@@ -27,8 +42,10 @@ class McpConfiguration {
|
|
|
27
42
|
this.path = '/mcp';
|
|
28
43
|
this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds
|
|
29
44
|
this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds
|
|
45
|
+
this.maxToolInputElements = resolveMaxToolInputElements(strapi);
|
|
30
46
|
}
|
|
31
47
|
}
|
|
32
48
|
|
|
49
|
+
exports.DEFAULT_MAX_TOOL_INPUT_ELEMENTS = DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
33
50
|
exports.McpConfiguration = McpConfiguration;
|
|
34
51
|
//# sourceMappingURL=McpConfiguration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpConfiguration.js","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport class McpConfiguration {\n readonly path: string;\n\n readonly connectTimeoutMs: number;\n\n readonly requestTimeoutMs: number;\n\n #strapi: Core.Strapi;\n\n constructor(strapi: Core.Strapi) {\n this.#strapi = strapi;\n this.path = '/mcp';\n this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds\n this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds\n }\n\n isEnabled(): boolean {\n return this.#strapi.config.get<boolean>('server.mcp.enabled', false) === true;\n }\n\n isDevMode(): boolean {\n return this.#strapi.config.get('autoReload', false);\n }\n}\n"],"names":["
|
|
1
|
+
{"version":3,"file":"McpConfiguration.js","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10_000;\n\n// The SDK throws on any value that is not a number >= 1, so only a valid value may reach it.\nconst resolveMaxToolInputElements = (strapi: Core.Strapi): number => {\n const raw = strapi.config.get<unknown>('server.mcp.maxToolInputElements');\n\n if (raw === undefined) {\n return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;\n }\n\n // env() returns strings\n const value = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;\n\n if (value === Infinity || (Number.isInteger(value) && (value as number) >= 1)) {\n return value as number;\n }\n\n strapi.log.warn(\n `[MCP] Invalid server.mcp.maxToolInputElements (${String(raw)}). ` +\n `Expected an integer >= 1 or Infinity. Using ${DEFAULT_MAX_TOOL_INPUT_ELEMENTS}.`\n );\n\n return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;\n};\n\nexport class McpConfiguration {\n readonly path: string;\n\n readonly connectTimeoutMs: number;\n\n readonly requestTimeoutMs: number;\n\n readonly maxToolInputElements: number;\n\n #strapi: Core.Strapi;\n\n constructor(strapi: Core.Strapi) {\n this.#strapi = strapi;\n this.path = '/mcp';\n this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds\n this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds\n this.maxToolInputElements = resolveMaxToolInputElements(strapi);\n }\n\n isEnabled(): boolean {\n return this.#strapi.config.get<boolean>('server.mcp.enabled', false) === true;\n }\n\n isDevMode(): boolean {\n return this.#strapi.config.get('autoReload', false);\n }\n}\n"],"names":["DEFAULT_MAX_TOOL_INPUT_ELEMENTS","resolveMaxToolInputElements","strapi","raw","config","get","undefined","value","trim","Number","Infinity","isInteger","log","warn","String","McpConfiguration","isEnabled","isDevMode","path","conn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AA,cAAA,CAAA,IAAA,EAAA,OAAA,EAAA;;mBAAA;;QAGE,+BAAA,CAAA,IAAI,EAAC,OAAA,CAAA,CAAA,OAAA,CAAA,GAAUA,MAAAA;QACf,IAAI,CAACgB,IAAI,GAAG,MAAA;QACZ,IAAI,CAACC,gBAAgB,GAAGjB,MAAAA,CAAOE,MAAM,CAACC,GAAG,CAAC,6BAAA,EAA+B,CAAA,GAAI,IAAA,CAAA,CAAA;QAC7E,IAAI,CAACe,gBAAgB,GAAGlB,MAAAA,CAAOE,MAAM,CAACC,GAAG,CAAC,6BAAA,EAA+B,EAAA,GAAK,IAAA,CAAA,CAAA;QAC9E,IAAI,CAACgB,oBAAoB,GAAGpB,2BAAAA,CAA4BC,MAAAA,CAAAA;AAC1D,IAAA;AASF;;;;;"}
|
|
@@ -8,6 +8,21 @@ var id = 0;
|
|
|
8
8
|
function _class_private_field_loose_key(name) {
|
|
9
9
|
return "__private_" + id++ + "_" + name;
|
|
10
10
|
}
|
|
11
|
+
const DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10000;
|
|
12
|
+
// The SDK throws on any value that is not a number >= 1, so only a valid value may reach it.
|
|
13
|
+
const resolveMaxToolInputElements = (strapi)=>{
|
|
14
|
+
const raw = strapi.config.get('server.mcp.maxToolInputElements');
|
|
15
|
+
if (raw === undefined) {
|
|
16
|
+
return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
17
|
+
}
|
|
18
|
+
// env() returns strings
|
|
19
|
+
const value = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;
|
|
20
|
+
if (value === Infinity || Number.isInteger(value) && value >= 1) {
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
strapi.log.warn(`[MCP] Invalid server.mcp.maxToolInputElements (${String(raw)}). ` + `Expected an integer >= 1 or Infinity. Using ${DEFAULT_MAX_TOOL_INPUT_ELEMENTS}.`);
|
|
24
|
+
return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
25
|
+
};
|
|
11
26
|
var _strapi = /*#__PURE__*/ _class_private_field_loose_key("_strapi");
|
|
12
27
|
class McpConfiguration {
|
|
13
28
|
isEnabled() {
|
|
@@ -25,8 +40,9 @@ class McpConfiguration {
|
|
|
25
40
|
this.path = '/mcp';
|
|
26
41
|
this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds
|
|
27
42
|
this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds
|
|
43
|
+
this.maxToolInputElements = resolveMaxToolInputElements(strapi);
|
|
28
44
|
}
|
|
29
45
|
}
|
|
30
46
|
|
|
31
|
-
export { McpConfiguration };
|
|
47
|
+
export { DEFAULT_MAX_TOOL_INPUT_ELEMENTS, McpConfiguration };
|
|
32
48
|
//# sourceMappingURL=McpConfiguration.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpConfiguration.mjs","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport class McpConfiguration {\n readonly path: string;\n\n readonly connectTimeoutMs: number;\n\n readonly requestTimeoutMs: number;\n\n #strapi: Core.Strapi;\n\n constructor(strapi: Core.Strapi) {\n this.#strapi = strapi;\n this.path = '/mcp';\n this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds\n this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds\n }\n\n isEnabled(): boolean {\n return this.#strapi.config.get<boolean>('server.mcp.enabled', false) === true;\n }\n\n isDevMode(): boolean {\n return this.#strapi.config.get('autoReload', false);\n }\n}\n"],"names":["
|
|
1
|
+
{"version":3,"file":"McpConfiguration.mjs","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10_000;\n\n// The SDK throws on any value that is not a number >= 1, so only a valid value may reach it.\nconst resolveMaxToolInputElements = (strapi: Core.Strapi): number => {\n const raw = strapi.config.get<unknown>('server.mcp.maxToolInputElements');\n\n if (raw === undefined) {\n return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;\n }\n\n // env() returns strings\n const value = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;\n\n if (value === Infinity || (Number.isInteger(value) && (value as number) >= 1)) {\n return value as number;\n }\n\n strapi.log.warn(\n `[MCP] Invalid server.mcp.maxToolInputElements (${String(raw)}). ` +\n `Expected an integer >= 1 or Infinity. Using ${DEFAULT_MAX_TOOL_INPUT_ELEMENTS}.`\n );\n\n return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;\n};\n\nexport class McpConfiguration {\n readonly path: string;\n\n readonly connectTimeoutMs: number;\n\n readonly requestTimeoutMs: number;\n\n readonly maxToolInputElements: number;\n\n #strapi: Core.Strapi;\n\n constructor(strapi: Core.Strapi) {\n this.#strapi = strapi;\n this.path = '/mcp';\n this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds\n this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds\n this.maxToolInputElements = resolveMaxToolInputElements(strapi);\n }\n\n isEnabled(): boolean {\n return this.#strapi.config.get<boolean>('server.mcp.enabled', false) === true;\n }\n\n isDevMode(): boolean {\n return this.#strapi.config.get('autoReload', false);\n }\n}\n"],"names":["DEFAULT_MAX_TOOL_INPUT_ELEMENTS","resolveMaxToolInputElements","strapi","raw","config","get","undefined","value","trim","Number","Infinity","isInteger","log","warn","String","McpConfiguration","isEnabled","isDevMode","path","connectTimeoutMs","requestTimeoutMs","maxToolInputElements"],"mappings":";;;;;;;;;;AAEO,MAAMA,kCAAkC;AAE/C;AACA,MAAMC,8BAA8B,CAACC,MAAAA,GAAAA;AACnC,IAAA,MAAMC,GAAAA,GAAMD,MAAAA,CAAOE,MAAM,CAACC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gB,GAAGjB,MAAAA,CAAOE,MAAM,CAACC,GAAG,CAAC,6BAAA,EAA+B,CAAA,GAAI,IAAA,CAAA,CAAA;QAC7E,IAAI,CAACe,gBAAgB,GAAGlB,MAAAA,CAAOE,MAAM,CAACC,GAAG,CAAC,6BAAA,EAA+B,EAAA,GAAK,IAAA,CAAA,CAAA;QAC9E,IAAI,CAACgB,oBAAoB,GAAGpB,2BAAAA,CAA4BC,MAAAA,CAAAA;AAC1D,IAAA;AASF;;;;"}
|
|
@@ -35,6 +35,8 @@ export type CreateMcpServerWithRegistriesParams = {
|
|
|
35
35
|
user: Modules.MCP.McpHandlerContext['user'];
|
|
36
36
|
/** Tools whose schemas the request needs. Defaults to `'all'`. */
|
|
37
37
|
toolSchemaScope?: McpToolSchemaScope;
|
|
38
|
+
/** Passed to the SDK as `maxToolInputElements`. */
|
|
39
|
+
maxToolInputElements?: number;
|
|
38
40
|
};
|
|
39
|
-
export declare const createMcpServerWithRegistries: ({ strapi, definitions, isDevMode, ability, user, toolSchemaScope, }: CreateMcpServerWithRegistriesParams) => McpServerWithRegistries;
|
|
41
|
+
export declare const createMcpServerWithRegistries: ({ strapi, definitions, isDevMode, ability, user, toolSchemaScope, maxToolInputElements, }: CreateMcpServerWithRegistriesParams) => McpServerWithRegistries;
|
|
40
42
|
//# sourceMappingURL=McpServerFactory.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpServerFactory.d.ts","sourceRoot":"","sources":["../../../../src/services/mcp/internal/McpServerFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA2B,MAAM,8BAA8B,CAAC;AAClF,OAAO,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB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G;IAClC,KAAK,EAAE,6BAA6B,CAAC;IACrC,OAAO,EAAE,6BAA6B,CAAC;IACvC,SAAS,EAAE,6BAA6B,CAAC;CAC1C,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,SAAS,EAAE,SAAS,CAAC;IACrB,UAAU,EAAE,qBAAqB,CAAC;CACnC,CAAC;AAEF,MAAM,MAAM,mCAAmC,GAAG;IAChD,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC;IACpB,WAAW,EAAE,wBAAwB,CAAC;IACtC,SAAS,EAAE,OAAO,CAAC;IACnB,OAAO,EAAE,oBAAoB,CAAC;IAC9B,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;IAC5C,kEAAkE;IAClE,eAAe,CAAC,EAAE,kBAAkB,CAAC;IACrC,mDAAmD;IACnD,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B,CAAC;AAEF,eAAO,MAAM,6BAA6B,GAAI,2FAQ3C,mCAAmC,KAAG,uBAuExC,CAAC"}
|
|
@@ -4,9 +4,10 @@ var server = require('@modelcontextprotocol/server');
|
|
|
4
4
|
var promptRegistry = require('../prompt-registry.js');
|
|
5
5
|
var resourceRegistry = require('../resource-registry.js');
|
|
6
6
|
var toolRegistry = require('../tool-registry.js');
|
|
7
|
+
var McpConfiguration = require('./McpConfiguration.js');
|
|
7
8
|
var syncMcpSessionCapabilities = require('./syncMcpSessionCapabilities.js');
|
|
8
9
|
|
|
9
|
-
const createMcpServerWithRegistries = ({ strapi, definitions, isDevMode, ability, user, toolSchemaScope = 'all' })=>{
|
|
10
|
+
const createMcpServerWithRegistries = ({ strapi, definitions, isDevMode, ability, user, toolSchemaScope = 'all', maxToolInputElements = McpConfiguration.DEFAULT_MAX_TOOL_INPUT_ELEMENTS })=>{
|
|
10
11
|
const capabilities = {
|
|
11
12
|
logging: {}
|
|
12
13
|
};
|
|
@@ -25,7 +26,8 @@ const createMcpServerWithRegistries = ({ strapi, definitions, isDevMode, ability
|
|
|
25
26
|
name: 'strapi-mcp-server',
|
|
26
27
|
version: '1.0.0'
|
|
27
28
|
}, {
|
|
28
|
-
capabilities
|
|
29
|
+
capabilities,
|
|
30
|
+
maxToolInputElements
|
|
29
31
|
});
|
|
30
32
|
// Bootstrap registries with current definitions
|
|
31
33
|
const tools = new toolRegistry.McpToolRegistry({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpServerFactory.js","sources":["../../../../src/services/mcp/internal/McpServerFactory.ts"],"sourcesContent":["import { McpServer, type ServerCapabilities } from '@modelcontextprotocol/server';\nimport type { Core, Modules } from '@strapi/types';\nimport { McpPromptRegistry } from '../prompt-registry';\nimport { McpResourceRegistry } from '../resource-registry';\nimport { McpToolRegistry } from '../tool-registry';\nimport type { McpAdminTokenAbility } from '../authentication';\nimport { McpCapabilityDefinitionRegistry } from './McpCapabilityDefinitionRegistry';\nimport type { McpCapabilityRegistryReadonly } from './McpCapabilityRegistry';\nimport { canUseMcpCapability, syncMcpSessionCapabilities } from './syncMcpSessionCapabilities';\nimport type { McpToolSchemaScope } from './resolveToolSchemaScope';\n\nexport type McpCapabilityDefinitions = {\n tools: McpCapabilityDefinitionRegistry<'tool', Modules.MCP.McpToolDefinition>;\n prompts: McpCapabilityDefinitionRegistry<'prompt', Modules.MCP.McpPromptDefinition>;\n resources: McpCapabilityDefinitionRegistry<'resource', Modules.MCP.McpResourceDefinition>;\n};\n\nexport type McpRegistries = {\n tools: McpToolRegistry;\n prompts: McpPromptRegistry;\n resources: McpResourceRegistry;\n};\n\n/** Read-only registry surface exposed on McpServerWithRegistries. */\nexport type McpRegistriesReadonly = {\n tools: McpCapabilityRegistryReadonly;\n prompts: McpCapabilityRegistryReadonly;\n resources: McpCapabilityRegistryReadonly;\n};\n\nexport type McpServerWithRegistries = {\n mcpServer: McpServer;\n registries: McpRegistriesReadonly;\n};\n\nexport type CreateMcpServerWithRegistriesParams = {\n strapi: Core.Strapi;\n definitions: McpCapabilityDefinitions;\n isDevMode: boolean;\n ability: McpAdminTokenAbility;\n user: Modules.MCP.McpHandlerContext['user'];\n /** Tools whose schemas the request needs. Defaults to `'all'`. */\n toolSchemaScope?: McpToolSchemaScope;\n};\n\nexport const createMcpServerWithRegistries = ({\n strapi,\n definitions,\n isDevMode,\n ability,\n user,\n toolSchemaScope = 'all',\n}: CreateMcpServerWithRegistriesParams): McpServerWithRegistries => {\n const capabilities: ServerCapabilities = {\n logging: {},\n };\n // Advertise capability categories when definitions exist (server-level), not per-user enabled\n // count. Clients discover the real set via tools/list, prompts/list, resources/list after sync.\n if (definitions.tools.size > 0) {\n capabilities.tools = {};\n }\n if (definitions.prompts.size > 0) {\n capabilities.prompts = {};\n }\n if (definitions.resources.size > 0) {\n capabilities.resources = {};\n }\n\n const mcpServer = new McpServer(\n {\n name: 'strapi-mcp-server',\n version: '1.0.0',\n },\n {\n capabilities,\n }\n );\n\n // Bootstrap registries with current definitions\n const tools = new McpToolRegistry({\n strapi,\n definitions: definitions.tools,\n ability,\n user,\n // A tool the token cannot use stays disabled, so its schemas are never advertised nor used.\n shouldResolveSchemas: (definition) =>\n (toolSchemaScope === 'all' || toolSchemaScope.has(definition.name)) &&\n canUseMcpCapability({ ability, definition, isDevMode }),\n });\n const prompts = new McpPromptRegistry({\n strapi,\n definitions: definitions.prompts,\n });\n const resources = new McpResourceRegistry({\n strapi,\n definitions: definitions.resources,\n });\n\n // Register capabilities (disabled by default)\n tools.bind(mcpServer);\n prompts.bind(mcpServer);\n resources.bind(mcpServer);\n\n syncMcpSessionCapabilities({\n registries: {\n tools,\n prompts,\n resources,\n },\n definitions,\n ability,\n isDevMode,\n });\n\n return {\n mcpServer,\n registries: {\n tools,\n prompts,\n resources,\n },\n };\n};\n"],"names":["createMcpServerWithRegistries","strapi","definitions","isDevMode","ability","user","toolSchemaScope","capabilities","logging","tools","size","prompts","resources","mcpServer","McpServer","name","version","McpToolRegistry","shouldResolveSchemas","definition","has","canUseMcpCapability","McpPromptRegistry","McpResourceRegistry","bind","syncMcpSessionCapabilities","registries"],"mappings":"
|
|
1
|
+
{"version":3,"file":"McpServerFactory.js","sources":["../../../../src/services/mcp/internal/McpServerFactory.ts"],"sourcesContent":["import { McpServer, type ServerCapabilities } from '@modelcontextprotocol/server';\nimport type { Core, Modules } from '@strapi/types';\nimport { McpPromptRegistry } from '../prompt-registry';\nimport { McpResourceRegistry } from '../resource-registry';\nimport { McpToolRegistry } from '../tool-registry';\nimport type { McpAdminTokenAbility } from '../authentication';\nimport { McpCapabilityDefinitionRegistry } from './McpCapabilityDefinitionRegistry';\nimport { DEFAULT_MAX_TOOL_INPUT_ELEMENTS } from './McpConfiguration';\nimport type { McpCapabilityRegistryReadonly } from './McpCapabilityRegistry';\nimport { canUseMcpCapability, syncMcpSessionCapabilities } from './syncMcpSessionCapabilities';\nimport type { McpToolSchemaScope } from './resolveToolSchemaScope';\n\nexport type McpCapabilityDefinitions = {\n tools: McpCapabilityDefinitionRegistry<'tool', Modules.MCP.McpToolDefinition>;\n prompts: McpCapabilityDefinitionRegistry<'prompt', Modules.MCP.McpPromptDefinition>;\n resources: McpCapabilityDefinitionRegistry<'resource', Modules.MCP.McpResourceDefinition>;\n};\n\nexport type McpRegistries = {\n tools: McpToolRegistry;\n prompts: McpPromptRegistry;\n resources: McpResourceRegistry;\n};\n\n/** Read-only registry surface exposed on McpServerWithRegistries. */\nexport type McpRegistriesReadonly = {\n tools: McpCapabilityRegistryReadonly;\n prompts: McpCapabilityRegistryReadonly;\n resources: McpCapabilityRegistryReadonly;\n};\n\nexport type McpServerWithRegistries = {\n mcpServer: McpServer;\n registries: McpRegistriesReadonly;\n};\n\nexport type CreateMcpServerWithRegistriesParams = {\n strapi: Core.Strapi;\n definitions: McpCapabilityDefinitions;\n isDevMode: boolean;\n ability: McpAdminTokenAbility;\n user: Modules.MCP.McpHandlerContext['user'];\n /** Tools whose schemas the request needs. Defaults to `'all'`. */\n toolSchemaScope?: McpToolSchemaScope;\n /** Passed to the SDK as `maxToolInputElements`. */\n maxToolInputElements?: number;\n};\n\nexport const createMcpServerWithRegistries = ({\n strapi,\n definitions,\n isDevMode,\n ability,\n user,\n toolSchemaScope = 'all',\n maxToolInputElements = DEFAULT_MAX_TOOL_INPUT_ELEMENTS,\n}: CreateMcpServerWithRegistriesParams): McpServerWithRegistries => {\n const capabilities: ServerCapabilities = {\n logging: {},\n };\n // Advertise capability categories when definitions exist (server-level), not per-user enabled\n // count. Clients discover the real set via tools/list, prompts/list, resources/list after sync.\n if (definitions.tools.size > 0) {\n capabilities.tools = {};\n }\n if (definitions.prompts.size > 0) {\n capabilities.prompts = {};\n }\n if (definitions.resources.size > 0) {\n capabilities.resources = {};\n }\n\n const mcpServer = new McpServer(\n {\n name: 'strapi-mcp-server',\n version: '1.0.0',\n },\n {\n capabilities,\n maxToolInputElements,\n }\n );\n\n // Bootstrap registries with current definitions\n const tools = new McpToolRegistry({\n strapi,\n definitions: definitions.tools,\n ability,\n user,\n // A tool the token cannot use stays disabled, so its schemas are never advertised nor used.\n shouldResolveSchemas: (definition) =>\n (toolSchemaScope === 'all' || toolSchemaScope.has(definition.name)) &&\n canUseMcpCapability({ ability, definition, isDevMode }),\n });\n const prompts = new McpPromptRegistry({\n strapi,\n definitions: definitions.prompts,\n });\n const resources = new McpResourceRegistry({\n strapi,\n definitions: definitions.resources,\n });\n\n // Register capabilities (disabled by default)\n tools.bind(mcpServer);\n prompts.bind(mcpServer);\n resources.bind(mcpServer);\n\n syncMcpSessionCapabilities({\n registries: {\n tools,\n prompts,\n resources,\n },\n definitions,\n ability,\n isDevMode,\n });\n\n return {\n mcpServer,\n registries: {\n tools,\n prompts,\n resources,\n },\n };\n};\n"],"names":["createMcpServerWithRegistries","strapi","definitions","isDevMode","ability","user","toolSchemaScope","maxToolInputElements","DEFAULT_MAX_TOOL_INPUT_ELEMENTS","capabilities","logging","tools","size","prompts","resources","mcpServer","McpServer","name","version","McpToolRegistry","shouldResolveSchemas","definition","has","canUseM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,KAAA,CAAA;IACA,MAAMU,OAAAA,GAAU,IAAIW,gCAAAA,CAAkB;AACpCvB,QAAAA,MAAAA;AACAC,QAAAA,WAAAA,EAAaA,YAAYW;AAC3B,KAAA,CAAA;IACA,MAAMC,SAAAA,GAAY,IAAIW,oCAAAA,CAAoB;AACxCxB,QAAAA,MAAAA;AACAC,QAAAA,WAAAA,EAAaA,YAAYY;AAC3B,KAAA,CAAA;;AAGAH,IAAAA,KAAAA,CAAMe,IAAI,CAACX,SAAAA,CAAAA;AACXF,IAAAA,OAAAA,CAAQa,IAAI,CAACX,SAAAA,CAAAA;AACbD,IAAAA,SAAAA,CAAUY,IAAI,CAACX,SAAAA,CAAAA;IAEfY,qDAAAA,CAA2B;QACzBC,UAAAA,EAAY;AACVjB,YAAAA,KAAAA;AACAE,YAAAA,OAAAA;AACAC,YAAAA;AACF,SAAA;AACAZ,QAAAA,WAAAA;AACAE,QAAAA,OAAAA;AACAD,QAAAA;AACF,KAAA,CAAA;IAEA,OAAO;AACLY,QAAAA,SAAAA;QACAa,UAAAA,EAAY;AACVjB,YAAAA,KAAAA;AACAE,YAAAA,OAAAA;AACAC,YAAAA;AACF;AACF,KAAA;AACF;;;;"}
|
|
@@ -2,9 +2,10 @@ import { McpServer } from '@modelcontextprotocol/server';
|
|
|
2
2
|
import { McpPromptRegistry } from '../prompt-registry.mjs';
|
|
3
3
|
import { McpResourceRegistry } from '../resource-registry.mjs';
|
|
4
4
|
import { McpToolRegistry } from '../tool-registry.mjs';
|
|
5
|
+
import { DEFAULT_MAX_TOOL_INPUT_ELEMENTS } from './McpConfiguration.mjs';
|
|
5
6
|
import { canUseMcpCapability, syncMcpSessionCapabilities } from './syncMcpSessionCapabilities.mjs';
|
|
6
7
|
|
|
7
|
-
const createMcpServerWithRegistries = ({ strapi, definitions, isDevMode, ability, user, toolSchemaScope = 'all' })=>{
|
|
8
|
+
const createMcpServerWithRegistries = ({ strapi, definitions, isDevMode, ability, user, toolSchemaScope = 'all', maxToolInputElements = DEFAULT_MAX_TOOL_INPUT_ELEMENTS })=>{
|
|
8
9
|
const capabilities = {
|
|
9
10
|
logging: {}
|
|
10
11
|
};
|
|
@@ -23,7 +24,8 @@ const createMcpServerWithRegistries = ({ strapi, definitions, isDevMode, ability
|
|
|
23
24
|
name: 'strapi-mcp-server',
|
|
24
25
|
version: '1.0.0'
|
|
25
26
|
}, {
|
|
26
|
-
capabilities
|
|
27
|
+
capabilities,
|
|
28
|
+
maxToolInputElements
|
|
27
29
|
});
|
|
28
30
|
// Bootstrap registries with current definitions
|
|
29
31
|
const tools = new McpToolRegistry({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpServerFactory.mjs","sources":["../../../../src/services/mcp/internal/McpServerFactory.ts"],"sourcesContent":["import { McpServer, type ServerCapabilities } from '@modelcontextprotocol/server';\nimport type { Core, Modules } from '@strapi/types';\nimport { McpPromptRegistry } from '../prompt-registry';\nimport { McpResourceRegistry } from '../resource-registry';\nimport { McpToolRegistry } from '../tool-registry';\nimport type { McpAdminTokenAbility } from '../authentication';\nimport { McpCapabilityDefinitionRegistry } from './McpCapabilityDefinitionRegistry';\nimport type { McpCapabilityRegistryReadonly } from './McpCapabilityRegistry';\nimport { canUseMcpCapability, syncMcpSessionCapabilities } from './syncMcpSessionCapabilities';\nimport type { McpToolSchemaScope } from './resolveToolSchemaScope';\n\nexport type McpCapabilityDefinitions = {\n tools: McpCapabilityDefinitionRegistry<'tool', Modules.MCP.McpToolDefinition>;\n prompts: McpCapabilityDefinitionRegistry<'prompt', Modules.MCP.McpPromptDefinition>;\n resources: McpCapabilityDefinitionRegistry<'resource', Modules.MCP.McpResourceDefinition>;\n};\n\nexport type McpRegistries = {\n tools: McpToolRegistry;\n prompts: McpPromptRegistry;\n resources: McpResourceRegistry;\n};\n\n/** Read-only registry surface exposed on McpServerWithRegistries. */\nexport type McpRegistriesReadonly = {\n tools: McpCapabilityRegistryReadonly;\n prompts: McpCapabilityRegistryReadonly;\n resources: McpCapabilityRegistryReadonly;\n};\n\nexport type McpServerWithRegistries = {\n mcpServer: McpServer;\n registries: McpRegistriesReadonly;\n};\n\nexport type CreateMcpServerWithRegistriesParams = {\n strapi: Core.Strapi;\n definitions: McpCapabilityDefinitions;\n isDevMode: boolean;\n ability: McpAdminTokenAbility;\n user: Modules.MCP.McpHandlerContext['user'];\n /** Tools whose schemas the request needs. Defaults to `'all'`. */\n toolSchemaScope?: McpToolSchemaScope;\n};\n\nexport const createMcpServerWithRegistries = ({\n strapi,\n definitions,\n isDevMode,\n ability,\n user,\n toolSchemaScope = 'all',\n}: CreateMcpServerWithRegistriesParams): McpServerWithRegistries => {\n const capabilities: ServerCapabilities = {\n logging: {},\n };\n // Advertise capability categories when definitions exist (server-level), not per-user enabled\n // count. Clients discover the real set via tools/list, prompts/list, resources/list after sync.\n if (definitions.tools.size > 0) {\n capabilities.tools = {};\n }\n if (definitions.prompts.size > 0) {\n capabilities.prompts = {};\n }\n if (definitions.resources.size > 0) {\n capabilities.resources = {};\n }\n\n const mcpServer = new McpServer(\n {\n name: 'strapi-mcp-server',\n version: '1.0.0',\n },\n {\n capabilities,\n }\n );\n\n // Bootstrap registries with current definitions\n const tools = new McpToolRegistry({\n strapi,\n definitions: definitions.tools,\n ability,\n user,\n // A tool the token cannot use stays disabled, so its schemas are never advertised nor used.\n shouldResolveSchemas: (definition) =>\n (toolSchemaScope === 'all' || toolSchemaScope.has(definition.name)) &&\n canUseMcpCapability({ ability, definition, isDevMode }),\n });\n const prompts = new McpPromptRegistry({\n strapi,\n definitions: definitions.prompts,\n });\n const resources = new McpResourceRegistry({\n strapi,\n definitions: definitions.resources,\n });\n\n // Register capabilities (disabled by default)\n tools.bind(mcpServer);\n prompts.bind(mcpServer);\n resources.bind(mcpServer);\n\n syncMcpSessionCapabilities({\n registries: {\n tools,\n prompts,\n resources,\n },\n definitions,\n ability,\n isDevMode,\n });\n\n return {\n mcpServer,\n registries: {\n tools,\n prompts,\n resources,\n },\n };\n};\n"],"names":["createMcpServerWithRegistries","strapi","definitions","isDevMode","ability","user","toolSchemaScope","capabilities","logging","tools","size","prompts","resources","mcpServer","McpServer","name","version","McpToolRegistry","shouldResolveSchemas","definition","has","canUseMcpCapability","McpPromptRegistry","McpResourceRegistry","bind","syncMcpSessionCapabilities","registries"],"mappings":"
|
|
1
|
+
{"version":3,"file":"McpServerFactory.mjs","sources":["../../../../src/services/mcp/internal/McpServerFactory.ts"],"sourcesContent":["import { McpServer, type ServerCapabilities } from '@modelcontextprotocol/server';\nimport type { Core, Modules } from '@strapi/types';\nimport { McpPromptRegistry } from '../prompt-registry';\nimport { McpResourceRegistry } from '../resource-registry';\nimport { McpToolRegistry } from '../tool-registry';\nimport type { McpAdminTokenAbility } from '../authentication';\nimport { McpCapabilityDefinitionRegistry } from './McpCapabilityDefinitionRegistry';\nimport { DEFAULT_MAX_TOOL_INPUT_ELEMENTS } from './McpConfiguration';\nimport type { McpCapabilityRegistryReadonly } from './McpCapabilityRegistry';\nimport { canUseMcpCapability, syncMcpSessionCapabilities } from './syncMcpSessionCapabilities';\nimport type { McpToolSchemaScope } from './resolveToolSchemaScope';\n\nexport type McpCapabilityDefinitions = {\n tools: McpCapabilityDefinitionRegistry<'tool', Modules.MCP.McpToolDefinition>;\n prompts: McpCapabilityDefinitionRegistry<'prompt', Modules.MCP.McpPromptDefinition>;\n resources: McpCapabilityDefinitionRegistry<'resource', Modules.MCP.McpResourceDefinition>;\n};\n\nexport type McpRegistries = {\n tools: McpToolRegistry;\n prompts: McpPromptRegistry;\n resources: McpResourceRegistry;\n};\n\n/** Read-only registry surface exposed on McpServerWithRegistries. */\nexport type McpRegistriesReadonly = {\n tools: McpCapabilityRegistryReadonly;\n prompts: McpCapabilityRegistryReadonly;\n resources: McpCapabilityRegistryReadonly;\n};\n\nexport type McpServerWithRegistries = {\n mcpServer: McpServer;\n registries: McpRegistriesReadonly;\n};\n\nexport type CreateMcpServerWithRegistriesParams = {\n strapi: Core.Strapi;\n definitions: McpCapabilityDefinitions;\n isDevMode: boolean;\n ability: McpAdminTokenAbility;\n user: Modules.MCP.McpHandlerContext['user'];\n /** Tools whose schemas the request needs. Defaults to `'all'`. */\n toolSchemaScope?: McpToolSchemaScope;\n /** Passed to the SDK as `maxToolInputElements`. */\n maxToolInputElements?: number;\n};\n\nexport const createMcpServerWithRegistries = ({\n strapi,\n definitions,\n isDevMode,\n ability,\n user,\n toolSchemaScope = 'all',\n maxToolInputElements = DEFAULT_MAX_TOOL_INPUT_ELEMENTS,\n}: CreateMcpServerWithRegistriesParams): McpServerWithRegistries => {\n const capabilities: ServerCapabilities = {\n logging: {},\n };\n // Advertise capability categories when definitions exist (server-level), not per-user enabled\n // count. Clients discover the real set via tools/list, prompts/list, resources/list after sync.\n if (definitions.tools.size > 0) {\n capabilities.tools = {};\n }\n if (definitions.prompts.size > 0) {\n capabilities.prompts = {};\n }\n if (definitions.resources.size > 0) {\n capabilities.resources = {};\n }\n\n const mcpServer = new McpServer(\n {\n name: 'strapi-mcp-server',\n version: '1.0.0',\n },\n {\n capabilities,\n maxToolInputElements,\n }\n );\n\n // Bootstrap registries with current definitions\n const tools = new McpToolRegistry({\n strapi,\n definitions: definitions.tools,\n ability,\n user,\n // A tool the token cannot use stays disabled, so its schemas are never advertised nor used.\n shouldResolveSchemas: (definition) =>\n (toolSchemaScope === 'all' || toolSchemaScope.has(definition.name)) &&\n canUseMcpCapability({ ability, definition, isDevMode }),\n });\n const prompts = new McpPromptRegistry({\n strapi,\n definitions: definitions.prompts,\n });\n const resources = new McpResourceRegistry({\n strapi,\n definitions: definitions.resources,\n });\n\n // Register capabilities (disabled by default)\n tools.bind(mcpServer);\n prompts.bind(mcpServer);\n resources.bind(mcpServer);\n\n syncMcpSessionCapabilities({\n registries: {\n tools,\n prompts,\n resources,\n },\n definitions,\n ability,\n isDevMode,\n });\n\n return {\n mcpServer,\n registries: {\n tools,\n prompts,\n resources,\n },\n };\n};\n"],"names":["createMcpServerWithRegistries","strapi","definitions","isDevMode","ability","user","toolSchemaScope","maxToolInputElements","DEFAULT_MAX_TOOL_INPUT_ELEMENTS","capabilities","logging","tools","size","prompts","resources","mcpServer","McpServer","name","version","McpToolRegistry","shouldResolveSchemas","definition","has","canUseMcpCapability","McpPromptRegistry","McpResourceRegistry","bind","syncMcpSessionCapabilities","registries"],"mappings":";;;;;;;MAgDaA,6BAAAA,GAAgC,CAAC,EAC5CC,MAAM,EACNC,WAAW,EACXC,SAAS,EACTC,OAAO,EACPC,IAAI,EACJC,eAAAA,GAAkB,KAAK,EACvBC,oBAAAA,GAAuBC,+BAA+B,EAClB,GAAA;AACpC,IAAA,MAAMC,YAAAA,GAAmC;AACvCC,QAAAA,OAAAA,EAAS;AACX,KAAA;;;AAGA,IAAA,IAAIR,WAAAA,CAAYS,KAAK,CAACC,IAAI,GAAG,CAAA,EAAG;QAC9BH,YAAAA,CAAaE,KAAK,GAAG,EAAC;AACxB,IAAA;AACA,IAAA,IAAIT,WAAAA,CAAYW,OAAO,CAACD,IAAI,GAAG,CAAA,EAAG;QAChCH,YAAAA,CAAaI,OAAO,GAAG,EAAC;AAC1B,IAAA;AACA,IAAA,IAAIX,WAAAA,CAAYY,SAAS,CAACF,IAAI,GAAG,CAAA,EAAG;QAClCH,YAAAA,CAAaK,SAAS,GAAG,EAAC;AAC5B,IAAA;IAEA,MAAMC,SAAAA,GAAY,IAAIC,SAAAA,CACpB;QACEC,IAAAA,EAAM,mBAAA;QACNC,OAAAA,EAAS;KACX,EACA;AACET,QAAAA,YAAAA;AACAF,QAAAA;AACF,KAAA,CAAA;;IAIF,MAAMI,KAAAA,GAAQ,IAAIQ,eAAAA,CAAgB;AAChClB,QAAAA,MAAAA;AACAC,QAAAA,WAAAA,EAAaA,YAAYS,KAAK;AAC9BP,QAAAA,OAAAA;AACAC,QAAAA,IAAAA;;AAEAe,QAAAA,oBAAAA,EAAsB,CAACC,UAAAA,GACrB,CAACf,eAAAA,KAAoB,KAAA,IAASA,eAAAA,CAAgBgB,GAAG,CAACD,UAAAA,CAAWJ,IAAI,CAAA,KACjEM,mBAAAA,CAAoB;AAAEnB,gBAAAA,OAAAA;AAASiB,gBAAAA,UAAAA;AAAYlB,gBAAAA;AAAU,aAAA;AACzD,KAAA,CAAA;IACA,MAAMU,OAAAA,GAAU,IAAIW,iBAAAA,CAAkB;AACpCvB,QAAAA,MAAAA;AACAC,QAAAA,WAAAA,EAAaA,YAAYW;AAC3B,KAAA,CAAA;IACA,MAAMC,SAAAA,GAAY,IAAIW,mBAAAA,CAAoB;AACxCxB,QAAAA,MAAAA;AACAC,QAAAA,WAAAA,EAAaA,YAAYY;AAC3B,KAAA,CAAA;;AAGAH,IAAAA,KAAAA,CAAMe,IAAI,CAACX,SAAAA,CAAAA;AACXF,IAAAA,OAAAA,CAAQa,IAAI,CAACX,SAAAA,CAAAA;AACbD,IAAAA,SAAAA,CAAUY,IAAI,CAACX,SAAAA,CAAAA;IAEfY,0BAAAA,CAA2B;QACzBC,UAAAA,EAAY;AACVjB,YAAAA,KAAAA;AACAE,YAAAA,OAAAA;AACAC,YAAAA;AACF,SAAA;AACAZ,QAAAA,WAAAA;AACAE,QAAAA,OAAAA;AACAD,QAAAA;AACF,KAAA,CAAA;IAEA,OAAO;AACLY,QAAAA,SAAAA;QACAa,UAAAA,EAAY;AACVjB,YAAAA,KAAAA;AACAE,YAAAA,OAAAA;AACAC,YAAAA;AACF;AACF,KAAA;AACF;;;;"}
|
|
@@ -6,28 +6,27 @@ import type { Modules } from '@strapi/types';
|
|
|
6
6
|
import type { EventHub } from './event-hub';
|
|
7
7
|
import type { Fetch } from '../utils/fetch';
|
|
8
8
|
type Webhook = Modules.WebhookStore.Webhook;
|
|
9
|
+
type Event = Modules.WebhookRunner.Event;
|
|
9
10
|
interface ConstructorParameters {
|
|
10
11
|
eventHub: EventHub;
|
|
12
|
+
requestContext: Modules.RequestContext.RequestContext;
|
|
11
13
|
logger: Logger;
|
|
12
14
|
configuration?: Record<string, unknown>;
|
|
13
15
|
fetch: Fetch;
|
|
14
16
|
}
|
|
15
|
-
interface Event {
|
|
16
|
-
event: string;
|
|
17
|
-
info: Record<string, unknown>;
|
|
18
|
-
}
|
|
19
17
|
declare class WebhookRunner {
|
|
20
18
|
private eventHub;
|
|
19
|
+
private requestContext;
|
|
21
20
|
private logger;
|
|
22
21
|
private config;
|
|
23
22
|
private webhooksMap;
|
|
24
23
|
private listeners;
|
|
25
24
|
private queue;
|
|
26
25
|
private fetch;
|
|
27
|
-
constructor({ eventHub, logger, configuration, fetch }: ConstructorParameters);
|
|
26
|
+
constructor({ eventHub, requestContext, logger, configuration, fetch, }: ConstructorParameters);
|
|
28
27
|
deleteListener(event: string): void;
|
|
29
28
|
createListener(event: string): void;
|
|
30
|
-
executeListener({ event, info }: Event): Promise<void>;
|
|
29
|
+
executeListener({ event, info, releaseId }: Event): Promise<void>;
|
|
31
30
|
run(webhook: Webhook, event: string, info?: {}): Promise<{
|
|
32
31
|
statusCode: number;
|
|
33
32
|
message?: undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webhook-runner.d.ts","sourceRoot":"","sources":["../../src/services/webhook-runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAE5C,KAAK,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"webhook-runner.d.ts","sourceRoot":"","sources":["../../src/services/webhook-runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAA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AU,mBAAmB,CAAC,IAAI,EAAE,qBAAqB,GAAG,aAAa,CAEtF;AAED,YAAY,EAAE,aAAa,EAAE,CAAC"}
|
|
@@ -11,7 +11,8 @@ var ___default = /*#__PURE__*/_interopDefault(_);
|
|
|
11
11
|
|
|
12
12
|
const debug = createDebug__default.default('strapi:webhook');
|
|
13
13
|
const defaultConfiguration = {
|
|
14
|
-
defaultHeaders: {}
|
|
14
|
+
defaultHeaders: {},
|
|
15
|
+
deduplicateReleaseWebhooks: false
|
|
15
16
|
};
|
|
16
17
|
/**
|
|
17
18
|
* Every event the webhook has to listen to, including the ones it only sends for some content types.
|
|
@@ -49,18 +50,33 @@ class WebhookRunner {
|
|
|
49
50
|
this.logger.error(`The webhook runner is already listening for the event '${event}'. Did you mean to call .register() ?`);
|
|
50
51
|
}
|
|
51
52
|
const listen = async (info)=>{
|
|
53
|
+
if (this.config.deduplicateReleaseWebhooks !== true) {
|
|
54
|
+
this.queue.enqueue({
|
|
55
|
+
event,
|
|
56
|
+
info
|
|
57
|
+
});
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const context = this.requestContext.get();
|
|
61
|
+
const releaseAction = context?.state?.releaseAction;
|
|
62
|
+
const isReleaseAction = releaseAction !== undefined && releaseAction.event === event && releaseAction.uid === info.uid && releaseAction.documentId === ___default.default.get(info, 'entry.documentId') && (releaseAction.locale ?? null) === (___default.default.get(info, 'entry.locale') ?? null);
|
|
63
|
+
const releaseId = isReleaseAction ? context?.state?.releaseId : undefined;
|
|
52
64
|
this.queue.enqueue({
|
|
53
65
|
event,
|
|
54
|
-
info
|
|
66
|
+
info,
|
|
67
|
+
releaseId
|
|
55
68
|
});
|
|
56
69
|
};
|
|
57
70
|
this.listeners.set(event, listen);
|
|
58
71
|
this.eventHub.on(event, listen);
|
|
59
72
|
}
|
|
60
|
-
async executeListener({ event, info }) {
|
|
73
|
+
async executeListener({ event, info, releaseId }) {
|
|
61
74
|
debug(`Executing webhook for event '${event}'`);
|
|
62
75
|
const webhooks = this.webhooksMap.get(event) || [];
|
|
63
|
-
const activeWebhooks = webhooks.filter((webhook)=>webhook.isEnabled === true && isTriggeredBy(webhook, event, info)
|
|
76
|
+
const activeWebhooks = webhooks.filter((webhook)=>webhook.isEnabled === true && isTriggeredBy(webhook, event, info) && !(this.config.deduplicateReleaseWebhooks === true && releaseId !== undefined && [
|
|
77
|
+
'entry.publish',
|
|
78
|
+
'entry.unpublish'
|
|
79
|
+
].includes(event) && webhook.events.includes('releases.publish')));
|
|
64
80
|
for (const webhook of activeWebhooks){
|
|
65
81
|
await this.run(webhook, event, info).catch((error)=>{
|
|
66
82
|
this.logger.error('Error running webhook');
|
|
@@ -132,17 +148,18 @@ class WebhookRunner {
|
|
|
132
148
|
}
|
|
133
149
|
});
|
|
134
150
|
}
|
|
135
|
-
constructor({ eventHub, logger, configuration = {}, fetch }){
|
|
151
|
+
constructor({ eventHub, requestContext, logger, configuration = {}, fetch }){
|
|
136
152
|
this.webhooksMap = new Map();
|
|
137
153
|
this.listeners = new Map();
|
|
138
154
|
debug('Initialized webhook runner');
|
|
139
155
|
this.eventHub = eventHub;
|
|
156
|
+
this.requestContext = requestContext;
|
|
140
157
|
this.logger = logger;
|
|
141
158
|
this.fetch = fetch;
|
|
142
159
|
if (typeof configuration !== 'object') {
|
|
143
160
|
throw new Error('Invalid configuration provided to the webhookRunner.\nCheck your server.json -> webhooks configuration');
|
|
144
161
|
}
|
|
145
|
-
this.config = ___default.default.merge(defaultConfiguration, configuration);
|
|
162
|
+
this.config = ___default.default.merge({}, defaultConfiguration, configuration);
|
|
146
163
|
this.queue = new workerQueue({
|
|
147
164
|
logger,
|
|
148
165
|
concurrency: 5
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webhook-runner.js","sources":["../../src/services/webhook-runner.ts"],"sourcesContent":["/**\n * The event hub is Strapi's event control center.\n */\n\nimport createdDebugger from 'debug';\nimport _ from 'lodash';\nimport type { Logger } from '@strapi/logger';\n\nimport type { Modules } from '@strapi/types';\nimport WorkerQueue from './worker-queue';\nimport type { EventHub } from './event-hub';\nimport type { Fetch } from '../utils/fetch';\n\ntype Webhook = Modules.WebhookStore.Webhook;\n\ninterface Config {\n defaultHeaders: Record<string, string>;\n}\n\ninterface ConstructorParameters {\n eventHub: EventHub;\n logger: Logger;\n configuration?: Record<string, unknown>;\n fetch: Fetch;\n}\n\ninterface Event {\n event: string;\n info: Record<string, unknown>;\n}\n\ntype Listener = (info: Record<string, unknown>) => Promise<void>;\n\nconst debug = createdDebugger('strapi:webhook');\n\nconst defaultConfiguration: Config = {\n defaultHeaders: {},\n};\n\n/**\n * Every event the webhook has to listen to, including the ones it only sends for some content types.\n */\nconst getEvents = ({ events, contentTypeEvents = {} }: Webhook) => {\n return [...new Set([...events, ...Object.values(contentTypeEvents).flat()])];\n};\n\n/**\n * A webhook is triggered by the events it listens to for every content type,\n * and by the events it listens to for the content type the event is about.\n */\nconst isTriggeredBy = (webhook: Webhook, event: string, info?: Event['info']) => {\n const { events, contentTypeEvents = {} } = webhook;\n const uid = info?.uid;\n\n if (events.includes(event)) {\n return true;\n }\n\n return (\n typeof uid === 'string' &&\n Object.hasOwn(contentTypeEvents, uid) &&\n contentTypeEvents[uid].includes(event)\n );\n};\n\nclass WebhookRunner {\n private eventHub: EventHub;\n\n private logger: Logger;\n\n private config: Config;\n\n private webhooksMap: Map<string, Webhook[]> = new Map();\n\n private listeners: Map<string, Listener> = new Map();\n\n private queue: WorkerQueue<Event, void>;\n\n private fetch: Fetch;\n\n constructor({ eventHub, logger, configuration = {}, fetch }: ConstructorParameters) {\n debug('Initialized webhook runner');\n this.eventHub = eventHub;\n this.logger = logger;\n this.fetch = fetch;\n\n if (typeof configuration !== 'object') {\n throw new Error(\n 'Invalid configuration provided to the webhookRunner.\\nCheck your server.json -> webhooks configuration'\n );\n }\n\n this.config = _.merge(defaultConfiguration, configuration);\n\n this.queue = new WorkerQueue({ logger, concurrency: 5 });\n\n this.queue.subscribe(this.executeListener.bind(this));\n }\n\n deleteListener(event: string) {\n debug(`Deleting listener for event '${event}'`);\n\n const fn = this.listeners.get(event);\n\n if (fn !== undefined) {\n this.eventHub.off(event, fn);\n this.listeners.delete(event);\n }\n }\n\n createListener(event: string) {\n debug(`Creating listener for event '${event}'`);\n if (this.listeners.has(event)) {\n this.logger.error(\n `The webhook runner is already listening for the event '${event}'. Did you mean to call .register() ?`\n );\n }\n\n const listen = async (info: Event['info']) => {\n this.queue.enqueue({ event, info });\n };\n\n this.listeners.set(event, listen);\n this.eventHub.on(event, listen);\n }\n\n async executeListener({ event, info }: Event) {\n debug(`Executing webhook for event '${event}'`);\n const webhooks = this.webhooksMap.get(event) || [];\n const activeWebhooks = webhooks.filter(\n (webhook) => webhook.isEnabled === true && isTriggeredBy(webhook, event, info)\n );\n\n for (const webhook of activeWebhooks) {\n await this.run(webhook, event, info).catch((error: unknown) => {\n this.logger.error('Error running webhook');\n this.logger.error(error);\n });\n }\n }\n\n run(webhook: Webhook, event: string, info = {}) {\n const { url, headers } = webhook;\n\n return this.fetch(url, {\n method: 'post',\n body: JSON.stringify({\n event,\n createdAt: new Date(),\n ...info,\n }),\n headers: {\n ...this.config.defaultHeaders,\n ...headers,\n 'X-Strapi-Event': event,\n 'Content-Type': 'application/json',\n },\n signal: AbortSignal.timeout(10000),\n })\n .then(async (res) => {\n if (res.ok) {\n return {\n statusCode: res.status,\n };\n }\n\n return {\n statusCode: res.status,\n message: await res.text(),\n };\n })\n .catch((err) => {\n return {\n statusCode: 500,\n message: err.message,\n };\n });\n }\n\n add(webhook: Webhook) {\n debug(`Registering webhook '${webhook.id}'`);\n getEvents(webhook).forEach((event) => {\n if (this.webhooksMap.has(event)) {\n this.webhooksMap.get(event)?.push(webhook);\n } else {\n this.webhooksMap.set(event, [webhook]);\n this.createListener(event);\n }\n });\n }\n\n update(webhook: Webhook) {\n debug(`Refreshing webhook '${webhook.id}'`);\n this.remove(webhook);\n this.add(webhook);\n }\n\n remove(webhook: Webhook) {\n debug(`Unregistering webhook '${webhook.id}'`);\n\n this.webhooksMap.forEach((webhooks, event) => {\n const filteredWebhooks = webhooks.filter((value) => value.id !== webhook.id);\n\n // Cleanup hanging listeners\n if (filteredWebhooks.length === 0) {\n this.webhooksMap.delete(event);\n this.deleteListener(event);\n } else {\n this.webhooksMap.set(event, filteredWebhooks);\n }\n });\n }\n}\n\n/**\n * Expose a factory function instead of the class\n */\nexport default function createWebhookRunner(opts: ConstructorParameters): WebhookRunner {\n return new WebhookRunner(opts);\n}\n\nexport type { WebhookRunner };\n"],"names":["debug","createdDebugger","defaultConfiguration","defaultHeaders","getEvents","events","contentTypeEvents","Set","Object","values","flat","isTriggeredBy","webhook","event","info","uid","includes","hasOwn","WebhookRunner","deleteListener","fn","listeners","get","undefined","eventHub","off","delete","createListener","has","logger","error","listen","queue","enqueue","set","on","executeListener","webhooks","webhooksMap","activeWebhooks","filter","isEnabled","run","catch","url","headers","fetch","method","body","JSON","stringify","createdAt","Date","config","signal","AbortSignal","timeout","then","res","ok","statusCode","status","message","text","err","add","id","forEach","push","update","remove","filteredWebhooks","value","length","configuration","Map","Error","_","merge","WorkerQueue","concurrency","subscribe","bind","createWebhookRunner","opts"],"mappings":";;;;;;;;;;;AAiCA,MAAMA,QAAQC,4BAAAA,CAAgB,gBAAA,CAAA;AAE9B,MAAMC,oBAAAA,GAA+B;AACnCC,IAAAA,cAAAA,EAAgB;AAClB,CAAA;AAEA;;IAGA,MAAMC,YAAY,CAAC,EAAEC,MAAM,EAAEC,iBAAAA,GAAoB,EAAE,EAAW,GAAA;IAC5D,OAAO;AAAI,QAAA,GAAA,IAAIC,GAAAA,CAAI;AAAIF,YAAAA,GAAAA,MAAAA;eAAWG,MAAAA,CAAOC,MAAM,CAACH,iBAAAA,CAAAA,CAAmBI,IAAI;AAAG,SAAA;AAAE,KAAA;AAC9E,CAAA;AAEA;;;AAGC,IACD,MAAMC,aAAAA,GAAgB,CAACC,OAAAA,EAAkBC,KAAAA,EAAeC,IAAAA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CAAE;AAR5ER,QAAAA,IAAAA,CAAAA,WAAAA,GAAsC,IAAIqC,GAAAA,EAAAA;AAE1CtD,QAAAA,IAAAA,CAAAA,SAAAA,GAAmC,IAAIsD,GAAAA,EAAAA;QAO7C3E,KAAAA,CAAM,4BAAA,CAAA;QACN,IAAI,CAACwB,QAAQ,GAAGA,QAAAA;QAChB,IAAI,CAACK,MAAM,GAAGA,MAAAA;QACd,IAAI,CAACiB,KAAK,GAAGA,KAAAA;QAEb,IAAI,OAAO4B,kBAAkB,QAAA,EAAU;AACrC,YAAA,MAAM,IAAIE,KAAAA,CACR,wGAAA,CAAA;AAEJ,QAAA;AAEA,QAAA,IAAI,CAACvB,MAAM,GAAGwB,kBAAAA,CAAEC,KAAK,CAAC5E,oBAAAA,EAAsBwE,aAAAA,CAAAA;AAE5C,QAAA,IAAI,CAAC1C,KAAK,GAAG,IAAI+C,WAAAA,CAAY;AAAElD,YAAAA,MAAAA;YAAQmD,WAAAA,EAAa;AAAE,SAAA,CAAA;QAEtD,IAAI,CAAChD,KAAK,CAACiD,SAAS,CAAC,IAAI,CAAC7C,eAAe,CAAC8C,IAAI,CAAC,IAAI,CAAA,CAAA;AACrD,IAAA;AAmHF;AAEA;;IAGe,SAASC,mBAAAA,CAAoBC,IAA2B,EAAA;AACrE,IAAA,OAAO,IAAIlE,aAAAA,CAAckE,IAAAA,CAAAA;AAC3B;;;;"}
|
|
1
|
+
{"version":3,"file":"webhook-runner.js","sources":["../../src/services/webhook-runner.ts"],"sourcesContent":["/**\n * The event hub is Strapi's event control center.\n */\n\nimport createdDebugger from 'debug';\nimport _ from 'lodash';\nimport type { Logger } from '@strapi/logger';\n\nimport type { Modules } from '@strapi/types';\nimport WorkerQueue from './worker-queue';\nimport type { EventHub } from './event-hub';\nimport type { Fetch } from '../utils/fetch';\n\ntype Webhook = Modules.WebhookStore.Webhook;\ntype Event = Modules.WebhookRunner.Event;\n\ninterface Config {\n defaultHeaders: Record<string, string>;\n deduplicateReleaseWebhooks: boolean;\n}\n\ninterface ConstructorParameters {\n eventHub: EventHub;\n requestContext: Modules.RequestContext.RequestContext;\n logger: Logger;\n configuration?: Record<string, unknown>;\n fetch: Fetch;\n}\n\ntype Listener = (info: Record<string, unknown>) => Promise<void>;\n\nconst debug = createdDebugger('strapi:webhook');\n\nconst defaultConfiguration: Config = {\n defaultHeaders: {},\n deduplicateReleaseWebhooks: false,\n};\n\n/**\n * Every event the webhook has to listen to, including the ones it only sends for some content types.\n */\nconst getEvents = ({ events, contentTypeEvents = {} }: Webhook) => {\n return [...new Set([...events, ...Object.values(contentTypeEvents).flat()])];\n};\n\n/**\n * A webhook is triggered by the events it listens to for every content type,\n * and by the events it listens to for the content type the event is about.\n */\nconst isTriggeredBy = (webhook: Webhook, event: string, info?: Event['info']) => {\n const { events, contentTypeEvents = {} } = webhook;\n const uid = info?.uid;\n\n if (events.includes(event)) {\n return true;\n }\n\n return (\n typeof uid === 'string' &&\n Object.hasOwn(contentTypeEvents, uid) &&\n contentTypeEvents[uid].includes(event)\n );\n};\n\nclass WebhookRunner {\n private eventHub: EventHub;\n\n private requestContext: Modules.RequestContext.RequestContext;\n\n private logger: Logger;\n\n private config: Config;\n\n private webhooksMap: Map<string, Webhook[]> = new Map();\n\n private listeners: Map<string, Listener> = new Map();\n\n private queue: WorkerQueue<Event, void>;\n\n private fetch: Fetch;\n\n constructor({\n eventHub,\n requestContext,\n logger,\n configuration = {},\n fetch,\n }: ConstructorParameters) {\n debug('Initialized webhook runner');\n this.eventHub = eventHub;\n this.requestContext = requestContext;\n this.logger = logger;\n this.fetch = fetch;\n\n if (typeof configuration !== 'object') {\n throw new Error(\n 'Invalid configuration provided to the webhookRunner.\\nCheck your server.json -> webhooks configuration'\n );\n }\n\n this.config = _.merge({}, defaultConfiguration, configuration);\n\n this.queue = new WorkerQueue({ logger, concurrency: 5 });\n\n this.queue.subscribe(this.executeListener.bind(this));\n }\n\n deleteListener(event: string) {\n debug(`Deleting listener for event '${event}'`);\n\n const fn = this.listeners.get(event);\n\n if (fn !== undefined) {\n this.eventHub.off(event, fn);\n this.listeners.delete(event);\n }\n }\n\n createListener(event: string) {\n debug(`Creating listener for event '${event}'`);\n if (this.listeners.has(event)) {\n this.logger.error(\n `The webhook runner is already listening for the event '${event}'. Did you mean to call .register() ?`\n );\n }\n\n const listen = async (info: Event['info']) => {\n if (this.config.deduplicateReleaseWebhooks !== true) {\n this.queue.enqueue({ event, info });\n return;\n }\n\n const context = this.requestContext.get();\n const releaseAction: Modules.WebhookRunner.ReleaseAction | undefined =\n context?.state?.releaseAction;\n const isReleaseAction =\n releaseAction !== undefined &&\n releaseAction.event === event &&\n releaseAction.uid === info.uid &&\n releaseAction.documentId === _.get(info, 'entry.documentId') &&\n (releaseAction.locale ?? null) === (_.get(info, 'entry.locale') ?? null);\n const releaseId: Event['releaseId'] = isReleaseAction ? context?.state?.releaseId : undefined;\n\n this.queue.enqueue({ event, info, releaseId });\n };\n\n this.listeners.set(event, listen);\n this.eventHub.on(event, listen);\n }\n\n async executeListener({ event, info, releaseId }: Event) {\n debug(`Executing webhook for event '${event}'`);\n const webhooks = this.webhooksMap.get(event) || [];\n const activeWebhooks = webhooks.filter(\n (webhook) =>\n webhook.isEnabled === true &&\n isTriggeredBy(webhook, event, info) &&\n !(\n this.config.deduplicateReleaseWebhooks === true &&\n releaseId !== undefined &&\n ['entry.publish', 'entry.unpublish'].includes(event) &&\n webhook.events.includes('releases.publish')\n )\n );\n\n for (const webhook of activeWebhooks) {\n await this.run(webhook, event, info).catch((error: unknown) => {\n this.logger.error('Error running webhook');\n this.logger.error(error);\n });\n }\n }\n\n run(webhook: Webhook, event: string, info = {}) {\n const { url, headers } = webhook;\n\n return this.fetch(url, {\n method: 'post',\n body: JSON.stringify({\n event,\n createdAt: new Date(),\n ...info,\n }),\n headers: {\n ...this.config.defaultHeaders,\n ...headers,\n 'X-Strapi-Event': event,\n 'Content-Type': 'application/json',\n },\n signal: AbortSignal.timeout(10000),\n })\n .then(async (res) => {\n if (res.ok) {\n return {\n statusCode: res.status,\n };\n }\n\n return {\n statusCode: res.status,\n message: await res.text(),\n };\n })\n .catch((err) => {\n return {\n statusCode: 500,\n message: err.message,\n };\n });\n }\n\n add(webhook: Webhook) {\n debug(`Registering webhook '${webhook.id}'`);\n getEvents(webhook).forEach((event) => {\n if (this.webhooksMap.has(event)) {\n this.webhooksMap.get(event)?.push(webhook);\n } else {\n this.webhooksMap.set(event, [webhook]);\n this.createListener(event);\n }\n });\n }\n\n update(webhook: Webhook) {\n debug(`Refreshing webhook '${webhook.id}'`);\n this.remove(webhook);\n this.add(webhook);\n }\n\n remove(webhook: Webhook) {\n debug(`Unregistering webhook '${webhook.id}'`);\n\n this.webhooksMap.forEach((webhooks, event) => {\n const filteredWebhooks = webhooks.filter((value) => value.id !== webhook.id);\n\n // Cleanup hanging listeners\n if (filteredWebhooks.length === 0) {\n this.webhooksMap.delete(event);\n this.deleteListener(event);\n } else {\n this.webhooksMap.set(event, filteredWebhooks);\n }\n });\n }\n}\n\n/**\n * Expose a factory function instead of the class\n */\nexport default function createWebhookRunner(opts: ConstructorParameters): WebhookRunner {\n return new WebhookRunner(opts);\n}\n\nexport type { WebhookRunner };\n"],"names":["debug","createdDebugger","defaultConfiguration","defaultHeaders","deduplicateReleaseWebhooks","getEvents","events","contentTypeEvents","Set","Object","values","flat","isTriggeredBy","webhook","event","info","uid","includes","hasOwn","WebhookRunner","deleteListener","fn","listeners","get","undefined","eventHub","off","delete","createListener","has","logger","error","listen","config","queue","enqueue","context","requestContext","releaseAction","state","isReleaseAction","documentId","_","locale","releaseId","set","on","executeListener","webhooks","webhooksMap","activeWebhooks","filter","isEnabled","run","catch","url","headers","fetch","method","body","JSON","stringify","createdAt","Date","signal","AbortSignal","timeout","then","res","ok","statusCode","status","message","text","err","add","id","forEach","push","update","remove","filteredWebhooks","value","length","configuration","Map","Error","merge","WorkerQueue","concurrency","subscribe","bind","createWebhookRunner","opts"],"mappings":";;;;;;;;;;;AA+BA,MAAM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;;;;"}
|
|
@@ -4,7 +4,8 @@ import WorkerQueue from './worker-queue.mjs';
|
|
|
4
4
|
|
|
5
5
|
const debug = createDebug('strapi:webhook');
|
|
6
6
|
const defaultConfiguration = {
|
|
7
|
-
defaultHeaders: {}
|
|
7
|
+
defaultHeaders: {},
|
|
8
|
+
deduplicateReleaseWebhooks: false
|
|
8
9
|
};
|
|
9
10
|
/**
|
|
10
11
|
* Every event the webhook has to listen to, including the ones it only sends for some content types.
|
|
@@ -42,18 +43,33 @@ class WebhookRunner {
|
|
|
42
43
|
this.logger.error(`The webhook runner is already listening for the event '${event}'. Did you mean to call .register() ?`);
|
|
43
44
|
}
|
|
44
45
|
const listen = async (info)=>{
|
|
46
|
+
if (this.config.deduplicateReleaseWebhooks !== true) {
|
|
47
|
+
this.queue.enqueue({
|
|
48
|
+
event,
|
|
49
|
+
info
|
|
50
|
+
});
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const context = this.requestContext.get();
|
|
54
|
+
const releaseAction = context?.state?.releaseAction;
|
|
55
|
+
const isReleaseAction = releaseAction !== undefined && releaseAction.event === event && releaseAction.uid === info.uid && releaseAction.documentId === _.get(info, 'entry.documentId') && (releaseAction.locale ?? null) === (_.get(info, 'entry.locale') ?? null);
|
|
56
|
+
const releaseId = isReleaseAction ? context?.state?.releaseId : undefined;
|
|
45
57
|
this.queue.enqueue({
|
|
46
58
|
event,
|
|
47
|
-
info
|
|
59
|
+
info,
|
|
60
|
+
releaseId
|
|
48
61
|
});
|
|
49
62
|
};
|
|
50
63
|
this.listeners.set(event, listen);
|
|
51
64
|
this.eventHub.on(event, listen);
|
|
52
65
|
}
|
|
53
|
-
async executeListener({ event, info }) {
|
|
66
|
+
async executeListener({ event, info, releaseId }) {
|
|
54
67
|
debug(`Executing webhook for event '${event}'`);
|
|
55
68
|
const webhooks = this.webhooksMap.get(event) || [];
|
|
56
|
-
const activeWebhooks = webhooks.filter((webhook)=>webhook.isEnabled === true && isTriggeredBy(webhook, event, info)
|
|
69
|
+
const activeWebhooks = webhooks.filter((webhook)=>webhook.isEnabled === true && isTriggeredBy(webhook, event, info) && !(this.config.deduplicateReleaseWebhooks === true && releaseId !== undefined && [
|
|
70
|
+
'entry.publish',
|
|
71
|
+
'entry.unpublish'
|
|
72
|
+
].includes(event) && webhook.events.includes('releases.publish')));
|
|
57
73
|
for (const webhook of activeWebhooks){
|
|
58
74
|
await this.run(webhook, event, info).catch((error)=>{
|
|
59
75
|
this.logger.error('Error running webhook');
|
|
@@ -125,17 +141,18 @@ class WebhookRunner {
|
|
|
125
141
|
}
|
|
126
142
|
});
|
|
127
143
|
}
|
|
128
|
-
constructor({ eventHub, logger, configuration = {}, fetch }){
|
|
144
|
+
constructor({ eventHub, requestContext, logger, configuration = {}, fetch }){
|
|
129
145
|
this.webhooksMap = new Map();
|
|
130
146
|
this.listeners = new Map();
|
|
131
147
|
debug('Initialized webhook runner');
|
|
132
148
|
this.eventHub = eventHub;
|
|
149
|
+
this.requestContext = requestContext;
|
|
133
150
|
this.logger = logger;
|
|
134
151
|
this.fetch = fetch;
|
|
135
152
|
if (typeof configuration !== 'object') {
|
|
136
153
|
throw new Error('Invalid configuration provided to the webhookRunner.\nCheck your server.json -> webhooks configuration');
|
|
137
154
|
}
|
|
138
|
-
this.config = _.merge(defaultConfiguration, configuration);
|
|
155
|
+
this.config = _.merge({}, defaultConfiguration, configuration);
|
|
139
156
|
this.queue = new WorkerQueue({
|
|
140
157
|
logger,
|
|
141
158
|
concurrency: 5
|