Skip to content

The open alternative to Salesforce, designed for AI.

Dispatch MCP methods with a typed switch and wrap responses once (#28190)

Paul Rastoinae2d40fa44af
diff --git a/packages/twenty-server/src/engine/api/mcp/constants/mcp-methods.const.ts b/packages/twenty-server/src/engine/api/mcp/constants/mcp-methods.const.ts
new file mode 100644
index 00000000000..e4204636c18
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/constants/mcp-methods.const.ts
@@ -0,0 +1,8 @@
+export const MCP_METHODS = [
+ 'initialize',
+ 'ping',
+ 'prompts/list',
+ 'resources/list',
+ 'tools/list',
+ 'tools/call',
+] as const;
diff --git a/packages/twenty-server/src/engine/api/mcp/exceptions/mcp.exception.ts b/packages/twenty-server/src/engine/api/mcp/exceptions/mcp.exception.ts
new file mode 100644
index 00000000000..038fc3f245a
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/exceptions/mcp.exception.ts
@@ -0,0 +1,52 @@
+import { HttpStatus } from '@nestjs/common';
+
+import { msg } from '@lingui/core/macro';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { CustomException } from 'src/utils/custom-exception';
+
+export const McpExceptionCode = {
+ METHOD_NOT_FOUND: 'METHOD_NOT_FOUND',
+ INVALID_PARAMS: 'INVALID_PARAMS',
+ FORBIDDEN: 'FORBIDDEN',
+} as const;
+
+const getMcpExceptionUserFriendlyMessage = (
+ code: keyof typeof McpExceptionCode,
+) => {
+ switch (code) {
+ case McpExceptionCode.METHOD_NOT_FOUND:
+ return msg`This MCP method is not supported.`;
+ case McpExceptionCode.INVALID_PARAMS:
+ return msg`The MCP request parameters are invalid.`;
+ case McpExceptionCode.FORBIDDEN:
+ return msg`You are not allowed to use MCP.`;
+ default:
+ return assertUnreachable(code);
+ }
+};
+
+const getMcpExceptionStatusCode = (code: keyof typeof McpExceptionCode) => {
+ switch (code) {
+ case McpExceptionCode.METHOD_NOT_FOUND:
+ return HttpStatus.NOT_FOUND;
+ case McpExceptionCode.INVALID_PARAMS:
+ return HttpStatus.BAD_REQUEST;
+ case McpExceptionCode.FORBIDDEN:
+ return HttpStatus.FORBIDDEN;
+ default:
+ return assertUnreachable(code);
+ }
+};
+
+export class McpException extends CustomException<
+ keyof typeof McpExceptionCode
+> {
+ constructor(message: string, code: keyof typeof McpExceptionCode) {
+ super(message, code, {
+ userFriendlyMessage: getMcpExceptionUserFriendlyMessage(code),
+ // Never sent as an HTTP status: it keeps handleException from reporting these to Sentry
+ statusCode: getMcpExceptionStatusCode(code),
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts b/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
index 8f9bcb2ce5f..bc22a48807c 100644
--- a/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
+++ b/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
@@ -1,11 +1,10 @@
-import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
+import { Injectable } from '@nestjs/common';
import * as Sentry from '@sentry/node';
import { type ToolSet } from 'ai';
import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
+import { assertUnreachable, isDefined } from 'twenty-shared/utils';
-import { JSON_RPC_ERROR_CODE } from 'src/engine/api/mcp/constants/json-rpc-error-code.const';
import { MCP_CLOSED_WORLD_READ_ONLY_TOOL_ANNOTATIONS } from 'src/engine/api/mcp/constants/mcp-closed-world-read-only-tool-annotations.const';
import { MCP_EXCLUDED_TOOL_NAMES } from 'src/engine/api/mcp/constants/mcp-excluded-tool-names.const';
import { MCP_EXECUTE_TOOL_ANNOTATIONS } from 'src/engine/api/mcp/constants/mcp-execute-tool-annotations.const';
@@ -13,6 +12,10 @@ import { MCP_OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS } from 'src/engine/api/mcp/co
import { MCP_PROTOCOL_VERSION } from 'src/engine/api/mcp/constants/mcp-protocol-version.const';
import { MCP_SERVER_INFO } from 'src/engine/api/mcp/constants/mcp-server-info.const';
import { JsonRpc } from 'src/engine/api/mcp/dtos/json-rpc';
+import {
+ McpException,
+ McpExceptionCode,
+} from 'src/engine/api/mcp/exceptions/mcp.exception';
import { McpInstructionBuilderService } from 'src/engine/api/mcp/services/mcp-instruction-builder.service';
import { McpToolExecutorService } from 'src/engine/api/mcp/services/mcp-tool-executor.service';
import {
@@ -25,9 +28,16 @@ import {
} from 'src/engine/api/mcp/tools/list-skills.tool';
import { type McpAnnotatedTool } from 'src/engine/api/mcp/types/mcp-annotated-tool.type';
import { type McpCoreQueryContext } from 'src/engine/api/mcp/types/mcp-core-query-context.type';
+import { type McpInitializeResult } from 'src/engine/api/mcp/types/mcp-initialize-result.type';
+import { type McpMethod } from 'src/engine/api/mcp/types/mcp-method.type';
+import { type McpResult } from 'src/engine/api/mcp/types/mcp-result.type';
import { type McpToolAnnotations } from 'src/engine/api/mcp/types/mcp-tool-annotations.type';
+import { type McpToolCallResult } from 'src/engine/api/mcp/types/mcp-tool-call-result.type';
import { type McpToolSet } from 'src/engine/api/mcp/types/mcp-tool-set.type';
+import { type McpToolsListResult } from 'src/engine/api/mcp/types/mcp-tools-list-result.type';
+import { buildJsonRpcError } from 'src/engine/api/mcp/utils/build-json-rpc-error.util';
import { getMcpRegistryToolAnnotations } from 'src/engine/api/mcp/utils/get-mcp-registry-tool-annotations.util';
+import { isMcpMethod } from 'src/engine/api/mcp/utils/is-mcp-method.util';
import { parseMcpToolCallParams } from 'src/engine/api/mcp/utils/parse-mcp-tool-call-params.util';
import { wrapJsonRpcResponse } from 'src/engine/api/mcp/utils/wrap-jsonrpc-response.util';
import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
@@ -66,7 +76,6 @@ import { SkillService } from 'src/engine/metadata-modules/skill/skill.service';
import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role.service';
import { handleException } from 'src/engine/utils/global-exception-handler.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { CustomException } from 'src/utils/custom-exception';
const MCP_PRELOADED_TOOL_ANNOTATIONS: Record<string, McpToolAnnotations> = {
search_help_center: MCP_OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,
@@ -103,37 +112,34 @@ export class McpProtocolService {
private readonly exceptionHandlerService: ExceptionHandlerService,
) {}
- async handleInitialize(
- requestId: string | number,
- {
- workspaceId,
- rolePermissionConfig,
- isDirectMode,
- }: {
- workspaceId: string;
- rolePermissionConfig: RolePermissionConfig;
- isDirectMode: boolean;
- },
- ) {
+ private async handleInitialize(
+ context: McpCoreQueryContext,
+ ): Promise<McpInitializeResult> {
+ const { rolePermissionConfig } = await this.resolveCallerRoles({
+ workspaceId: context.workspace.id,
+ userWorkspaceId: context.userWorkspaceId,
+ apiKey: context.apiKey,
+ application: context.application,
+ agentId: context.agentId,
+ });
+
const instructions =
await this.mcpInstructionBuilderService.buildInstructions({
- workspaceId,
+ workspaceId: context.workspace.id,
rolePermissionConfig,
- isDirectMode,
+ isDirectMode: context.isDirectMode,
});
- return wrapJsonRpcResponse(requestId, {
- result: {
- protocolVersion: MCP_PROTOCOL_VERSION,
- capabilities: {
- tools: { listChanged: false },
- resources: { listChanged: false },
- prompts: { listChanged: false },
- },
- serverInfo: MCP_SERVER_INFO,
- instructions,
+ return {
+ protocolVersion: MCP_PROTOCOL_VERSION,
+ capabilities: {
+ tools: { listChanged: false },
+ resources: { listChanged: false },
+ prompts: { listChanged: false },
},
- });
+ serverInfo: MCP_SERVER_INFO,
+ instructions,
+ };
}
async resolveCallerRoles({
@@ -167,9 +173,9 @@ export class McpProtocolService {
if (!userWorkspaceId && isDefined(application)) {
if (!isDefined(application.defaultRoleId)) {
- throw new HttpException(
+ throw new McpException(
'Application has no role',
- HttpStatus.FORBIDDEN,
+ McpExceptionCode.FORBIDDEN,
);
}
@@ -184,9 +190,9 @@ export class McpProtocolService {
}
if (!userWorkspaceId) {
- throw new HttpException(
+ throw new McpException(
'User workspace ID missing',
- HttpStatus.FORBIDDEN,
+ McpExceptionCode.FORBIDDEN,
);
}
@@ -359,16 +365,7 @@ export class McpProtocolService {
// Returns null for JSON-RPC notifications (no id), which require no response body
async handleMCPCoreQuery(
{ id, method, params }: JsonRpc,
- {
- authContext,
- workspace,
- userId,
- userWorkspaceId,
- apiKey,
- application,
- agentId,
- isDirectMode,
- }: McpCoreQueryContext,
+ context: McpCoreQueryContext,
sseWriter?: (data: Record<string, unknown>) => void,
): Promise<Record<string, unknown> | null> {
// JSON-RPC notifications have no id and expect no response
@@ -378,181 +375,186 @@ export class McpProtocolService {
try {
// No tool runs without a workspace member, so a user still onboarding is refused upfront
- if (authContext.type === 'pendingActivationUser') {
- throw new HttpException(
+ if (context.authContext.type === 'pendingActivationUser') {
+ throw new McpException(
'Finish signing up before using MCP',
- HttpStatus.FORBIDDEN,
+ McpExceptionCode.FORBIDDEN,
);
}
- if (method === 'initialize') {
- const { rolePermissionConfig } = await this.resolveCallerRoles({
- workspaceId: workspace.id,
- userWorkspaceId,
- apiKey,
- application,
- agentId,
- });
-
- return this.handleInitialize(id, {
- workspaceId: workspace.id,
- rolePermissionConfig,
- isDirectMode,
- });
+ if (!isMcpMethod(method)) {
+ throw new McpException(
+ `Method '${method}' not found`,
+ McpExceptionCode.METHOD_NOT_FOUND,
+ );
}
- if (method === 'ping') {
- return wrapJsonRpcResponse(id, { result: {} });
- }
+ const result = await this.dispatchMcpMethod({
+ method,
+ params,
+ context,
+ sseWriter,
+ });
- if (method === 'prompts/list') {
- return wrapJsonRpcResponse(id, {
- result: { prompts: [] },
- });
- }
+ return wrapJsonRpcResponse(id, { result });
+ } catch (error) {
+ const exception =
+ error instanceof Error ? error : new Error(String(error));
- if (method === 'resources/list') {
- return wrapJsonRpcResponse(id, {
- result: { resources: [] },
- });
- }
+ handleException({
+ exception,
+ exceptionHandlerService: this.exceptionHandlerService,
+ user: isDefined(context.userId) ? { id: context.userId } : undefined,
+ workspace: { id: context.workspace.id },
+ });
- if (method !== 'tools/list' && method !== 'tools/call') {
- return wrapJsonRpcResponse(id, {
- error: {
- code: JSON_RPC_ERROR_CODE.METHOD_NOT_FOUND,
- message: `Method '${method}' not found`,
- },
- });
- }
+ return wrapJsonRpcResponse(id, { error: buildJsonRpcError(exception) });
+ }
+ }
- const { rolePermissionConfig } = await this.resolveCallerRoles({
- workspaceId: workspace.id,
- userWorkspaceId,
- apiKey,
- application,
- agentId,
- });
+ private async dispatchMcpMethod({
+ method,
+ params,
+ context,
+ sseWriter,
+ }: {
+ method: McpMethod;
+ params: Record<string, unknown> | undefined;
+ context: McpCoreQueryContext;
+ sseWriter?: (data: Record<string, unknown>) => void;
+ }): Promise<McpResult> {
+ switch (method) {
+ case 'initialize':
+ return this.handleInitialize(context);
+ case 'ping':
+ return {};
+ case 'prompts/list':
+ return { prompts: [] };
+ case 'resources/list':
+ return { resources: [] };
+ case 'tools/list':
+ return this.handleToolsList(context);
+ case 'tools/call':
+ return this.handleToolsCall({ params, context, sseWriter });
+ default:
+ return assertUnreachable(method);
+ }
+ }
- const { toolSet, toolContext } = await Sentry.startSpan(
- { name: 'mcp build tool set', op: 'mcp.tools', onlyIfParent: true },
- () =>
- this.buildMcpToolSet(workspace, rolePermissionConfig, {
- authContext,
- application,
- userId,
- userWorkspaceId,
- apiKey,
- agentId,
- }),
- );
+ private async handleToolsList(
+ context: McpCoreQueryContext,
+ ): Promise<McpToolsListResult> {
+ const { toolSet, toolContext } = await this.resolveMcpToolSet(context);
- if (method === 'tools/call') {
- const toolCallParams = parseMcpToolCallParams(params);
+ if (!context.isDirectMode) {
+ return this.mcpToolExecutorService.handleToolsListing(toolSet);
+ }
- if (!isDefined(toolCallParams)) {
- return wrapJsonRpcResponse(id, {
- error: {
- code: JSON_RPC_ERROR_CODE.INVALID_PARAMS,
- message: 'tools/call requires params with name and arguments',
- },
- });
- }
+ const {
+ [GET_TOOL_CATALOG_TOOL_NAME]: _getToolCatalogTool,
+ [LEARN_TOOLS_TOOL_NAME]: _learnToolsTool,
+ [EXECUTE_TOOL_TOOL_NAME]: _executeToolTool,
+ ...nativeTools
+ } = toolSet;
- const { toolName, toolArguments, progressToken } = toolCallParams;
-
- const shouldForwardToExecuteTool =
- isDirectMode && !isDefined(toolSet[toolName]);
-
- return await this.mcpToolExecutorService.handleToolCall({
- id,
- toolSet,
- ...(shouldForwardToExecuteTool
- ? {
- toolName: EXECUTE_TOOL_TOOL_NAME,
- toolArguments: { toolName, arguments: toolArguments ?? {} },
- }
- : { toolName, toolArguments }),
- progressToken,
- sseWriter,
- });
- }
+ const annotatedRegistryTools =
+ await this.buildAnnotatedRegistryTools(toolContext);
- if (isDirectMode) {
- const {
- [GET_TOOL_CATALOG_TOOL_NAME]: _getToolCatalogTool,
- [LEARN_TOOLS_TOOL_NAME]: _learnToolsTool,
- [EXECUTE_TOOL_TOOL_NAME]: _executeToolTool,
- ...nativeTools
- } = toolSet;
-
- const annotatedRegistryTools = await Sentry.startSpan(
- {
- name: 'mcp list registry tools',
- op: 'mcp.tools',
- onlyIfParent: true,
- },
- async () => {
- const descriptors =
- await this.toolRegistry.getDescriptorsByCategories(toolContext, {
- excludeTools: [...MCP_EXCLUDED_TOOL_NAMES],
- });
-
- const registryTools = this.toolRegistry.hydrateToolSet(
- descriptors,
- toolContext,
- );
+ return this.mcpToolExecutorService.handleToolsListing({
+ ...annotatedRegistryTools,
+ ...nativeTools,
+ });
+ }
- return Object.fromEntries(
- descriptors.map((descriptor): [string, McpAnnotatedTool] => [
- descriptor.name,
- {
- ...registryTools[descriptor.name],
- annotations: getMcpRegistryToolAnnotations(
- descriptor.executionRef,
- ),
- },
- ]),
- );
- },
- );
+ private async handleToolsCall({
+ params,
+ context,
+ sseWriter,
+ }: {
+ params: Record<string, unknown> | undefined;
+ context: McpCoreQueryContext;
+ sseWriter?: (data: Record<string, unknown>) => void;
+ }): Promise<McpToolCallResult> {
+ const toolCallParams = parseMcpToolCallParams(params);
+
+ if (!isDefined(toolCallParams)) {
+ throw new McpException(
+ 'tools/call requires params with name and arguments',
+ McpExceptionCode.INVALID_PARAMS,
+ );
+ }
- return await this.mcpToolExecutorService.handleToolsListing(id, {
- ...annotatedRegistryTools,
- ...nativeTools,
- });
- }
+ const { toolName, toolArguments, progressToken } = toolCallParams;
- return await this.mcpToolExecutorService.handleToolsListing(id, toolSet);
- } catch (error) {
- const exception =
- error instanceof Error ? error : new Error(String(error));
+ const { toolSet } = await this.resolveMcpToolSet(context);
- handleException({
- exception,
- exceptionHandlerService: this.exceptionHandlerService,
- user: isDefined(userId) ? { id: userId } : undefined,
- workspace: { id: workspace.id },
- });
+ const shouldForwardToExecuteTool =
+ context.isDirectMode && !isDefined(toolSet[toolName]);
- if (exception instanceof HttpException) {
- return wrapJsonRpcResponse(id, {
- error: {
- code: JSON_RPC_ERROR_CODE.SERVER_ERROR,
- message: exception.message || 'Request failed',
- },
- });
- }
+ return this.mcpToolExecutorService.handleToolCall({
+ toolSet,
+ ...(shouldForwardToExecuteTool
+ ? {
+ toolName: EXECUTE_TOOL_TOOL_NAME,
+ toolArguments: { toolName, arguments: toolArguments ?? {} },
+ }
+ : { toolName, toolArguments }),
+ progressToken,
+ sseWriter,
+ });
+ }
- return wrapJsonRpcResponse(id, {
- error: {
- code: JSON_RPC_ERROR_CODE.INTERNAL_ERROR,
- message:
- exception instanceof CustomException
- ? exception.message
- : 'Internal server error',
- },
- });
- }
+ private async resolveMcpToolSet(context: McpCoreQueryContext) {
+ const { rolePermissionConfig } = await this.resolveCallerRoles({
+ workspaceId: context.workspace.id,
+ userWorkspaceId: context.userWorkspaceId,
+ apiKey: context.apiKey,
+ application: context.application,
+ agentId: context.agentId,
+ });
+
+ return Sentry.startSpan(
+ { name: 'mcp build tool set', op: 'mcp.tools', onlyIfParent: true },
+ () =>
+ this.buildMcpToolSet(context.workspace, rolePermissionConfig, {
+ authContext: context.authContext,
+ application: context.application,
+ userId: context.userId,
+ userWorkspaceId: context.userWorkspaceId,
+ apiKey: context.apiKey,
+ agentId: context.agentId,
+ }),
+ );
+ }
+
+ private buildAnnotatedRegistryTools(
+ toolContext: ToolProviderContext,
+ ): Promise<McpToolSet> {
+ return Sentry.startSpan(
+ { name: 'mcp list registry tools', op: 'mcp.tools', onlyIfParent: true },
+ async () => {
+ const descriptors = await this.toolRegistry.getDescriptorsByCategories(
+ toolContext,
+ { excludeTools: [...MCP_EXCLUDED_TOOL_NAMES] },
+ );
+
+ const registryTools = this.toolRegistry.hydrateToolSet(
+ descriptors,
+ toolContext,
+ );
+
+ return Object.fromEntries(
+ descriptors.map((descriptor): [string, McpAnnotatedTool] => [
+ descriptor.name,
+ {
+ ...registryTools[descriptor.name],
+ annotations: getMcpRegistryToolAnnotations(
+ descriptor.executionRef,
+ ),
+ },
+ ]),
+ );
+ },
+ );
}
}
diff --git a/packages/twenty-server/src/engine/api/mcp/services/mcp-tool-executor.service.ts b/packages/twenty-server/src/engine/api/mcp/services/mcp-tool-executor.service.ts
index 7672938e69f..6bc789a9666 100644
--- a/packages/twenty-server/src/engine/api/mcp/services/mcp-tool-executor.service.ts
+++ b/packages/twenty-server/src/engine/api/mcp/services/mcp-tool-executor.service.ts
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
+import { isString } from '@sniptt/guards';
import { asSchema, type ToolExecuteFunction } from 'ai';
import { isDefined } from 'twenty-shared/utils';
@@ -12,39 +13,40 @@ import { getToolMetricName } from 'src/engine/core-modules/tool-provider/utils/g
import { isToolOutputSuccessful } from 'src/engine/core-modules/tool-provider/utils/is-tool-output-successful.util';
import { resolveToolName } from 'src/engine/core-modules/tool-provider/utils/resolve-tool-name.util';
-import { JSON_RPC_ERROR_CODE } from 'src/engine/api/mcp/constants/json-rpc-error-code.const';
import { MCP_PROGRESS_NOTIFICATION_METHOD } from 'src/engine/api/mcp/constants/mcp-progress-notification.const';
+import {
+ McpException,
+ McpExceptionCode,
+} from 'src/engine/api/mcp/exceptions/mcp.exception';
+import { type McpListedTool } from 'src/engine/api/mcp/types/mcp-listed-tool.type';
+import { type McpToolCallResult } from 'src/engine/api/mcp/types/mcp-tool-call-result.type';
import { type McpToolSet } from 'src/engine/api/mcp/types/mcp-tool-set.type';
-import { wrapJsonRpcResponse } from 'src/engine/api/mcp/utils/wrap-jsonrpc-response.util';
+import { type McpToolsListResult } from 'src/engine/api/mcp/types/mcp-tools-list-result.type';
@Injectable()
export class McpToolExecutorService {
constructor(private readonly metricsService: MetricsService) {}
async handleToolCall({
- id,
toolSet,
toolName,
toolArguments,
progressToken,
sseWriter,
}: {
- id: string | number;
toolSet: McpToolSet;
toolName: string;
toolArguments: Record<string, unknown> | undefined;
progressToken: string | number | undefined;
sseWriter?: (data: Record<string, unknown>) => void;
- }) {
+ }): Promise<McpToolCallResult> {
const tool = toolSet[toolName];
if (!isDefined(tool) || !isDefined(tool.execute)) {
- return wrapJsonRpcResponse(id, {
- error: {
- code: JSON_RPC_ERROR_CODE.INVALID_PARAMS,
- message: `Unknown tool: ${toolName}`,
- },
- });
+ throw new McpException(
+ `Unknown tool: ${toolName}`,
+ McpExceptionCode.INVALID_PARAMS,
+ );
}
if (isDefined(sseWriter) && isDefined(progressToken)) {
@@ -81,22 +83,12 @@ export class McpToolExecutorService {
context: undefined,
});
- this.metricsService.recordHistogram({
- key: MetricsKeys.McpToolExecutionDurationMs,
- value: performance.now() - executionStartedAt,
- unit: 'ms',
- attributes: { tool: metricToolName },
- bucketBoundaries: TOOL_EXECUTION_DURATION_MS_BUCKET_BOUNDARIES,
- });
-
const succeeded = isToolOutputSuccessful(result);
- this.metricsService.incrementCounterBy({
- key: succeeded
- ? MetricsKeys.McpToolExecutionSucceeded
- : MetricsKeys.McpToolExecutionFailed,
- amount: 1,
- attributes: { tool: metricToolName },
+ this.recordToolExecutionMetrics({
+ metricToolName,
+ executionStartedAt,
+ succeeded,
});
this.metricsService.recordHistogram({
@@ -107,51 +99,42 @@ export class McpToolExecutorService {
bucketBoundaries: TOOL_OUTPUT_TOKENS_BUCKET_BOUNDARIES,
});
- return wrapJsonRpcResponse(id, {
- result: {
- content: [{ type: 'text', text: JSON.stringify(result) }],
- isError: !succeeded,
- },
- });
+ return {
+ content: [{ type: 'text', text: JSON.stringify(result) }],
+ isError: !succeeded,
+ };
} catch (executionError) {
- this.metricsService.recordHistogram({
- key: MetricsKeys.McpToolExecutionDurationMs,
- value: performance.now() - executionStartedAt,
- unit: 'ms',
- attributes: { tool: metricToolName },
- bucketBoundaries: TOOL_EXECUTION_DURATION_MS_BUCKET_BOUNDARIES,
+ this.recordToolExecutionMetrics({
+ metricToolName,
+ executionStartedAt,
+ succeeded: false,
});
- this.metricsService.incrementCounterBy({
- key: MetricsKeys.McpToolExecutionFailed,
- amount: 1,
- attributes: { tool: metricToolName },
- });
-
- return wrapJsonRpcResponse(id, {
- result: {
- content: [
- {
- type: 'text',
- text:
- executionError instanceof Error
- ? executionError.message
- : 'Tool execution failed',
- },
- ],
- isError: true,
- },
- });
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ executionError instanceof Error
+ ? executionError.message
+ : 'Tool execution failed',
+ },
+ ],
+ isError: true,
+ };
}
}
- async handleToolsListing(id: string | number, toolSet: McpToolSet) {
+ async handleToolsListing(toolSet: McpToolSet): Promise<McpToolsListResult> {
const tools = await Promise.all(
Object.entries(toolSet)
.filter(([, tool]) => isDefined(tool.inputSchema))
- .map(async ([name, tool]) => ({
+ .map(async ([name, tool]): Promise<McpListedTool> => ({
name,
- description: tool.description,
+ // AI SDK v7 also allows a description resolver, which MCP clients cannot call
+ description: isString(tool.description)
+ ? tool.description
+ : undefined,
inputSchema: {
...(await asSchema(tool.inputSchema).jsonSchema),
type: 'object',
@@ -160,10 +143,32 @@ export class McpToolExecutorService {
})),
);
- return wrapJsonRpcResponse(id, {
- result: {
- tools,
- },
+ return { tools };
+ }
+
+ private recordToolExecutionMetrics({
+ metricToolName,
+ executionStartedAt,
+ succeeded,
+ }: {
+ metricToolName: string;
+ executionStartedAt: number;
+ succeeded: boolean;
+ }) {
+ this.metricsService.recordHistogram({
+ key: MetricsKeys.McpToolExecutionDurationMs,
+ value: performance.now() - executionStartedAt,
+ unit: 'ms',
+ attributes: { tool: metricToolName },
+ bucketBoundaries: TOOL_EXECUTION_DURATION_MS_BUCKET_BOUNDARIES,
+ });
+
+ this.metricsService.incrementCounterBy({
+ key: succeeded
+ ? MetricsKeys.McpToolExecutionSucceeded
+ : MetricsKeys.McpToolExecutionFailed,
+ amount: 1,
+ attributes: { tool: metricToolName },
});
}
}
diff --git a/packages/twenty-server/src/engine/api/mcp/types/json-rpc-error.type.ts b/packages/twenty-server/src/engine/api/mcp/types/json-rpc-error.type.ts
new file mode 100644
index 00000000000..99e4e9e95ea
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/types/json-rpc-error.type.ts
@@ -0,0 +1,4 @@
+export type JsonRpcError = {
+ code: number;
+ message: string;
+};
diff --git a/packages/twenty-server/src/engine/api/mcp/types/mcp-initialize-result.type.ts b/packages/twenty-server/src/engine/api/mcp/types/mcp-initialize-result.type.ts
new file mode 100644
index 00000000000..2a97a1308ba
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/types/mcp-initialize-result.type.ts
@@ -0,0 +1,11 @@
+import { type MCP_SERVER_INFO } from 'src/engine/api/mcp/constants/mcp-server-info.const';
+
+export type McpInitializeResult = {
+ protocolVersion: string;
+ capabilities: Record<
+ 'tools' | 'resources' | 'prompts',
+ { listChanged: boolean }
+ >;
+ serverInfo: typeof MCP_SERVER_INFO;
+ instructions: string;
+};
diff --git a/packages/twenty-server/src/engine/api/mcp/types/mcp-listed-tool.type.ts b/packages/twenty-server/src/engine/api/mcp/types/mcp-listed-tool.type.ts
new file mode 100644
index 00000000000..4f0fd474410
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/types/mcp-listed-tool.type.ts
@@ -0,0 +1,10 @@
+import { type JSONSchema7 } from 'json-schema';
+
+import { type McpToolAnnotations } from 'src/engine/api/mcp/types/mcp-tool-annotations.type';
+
+export type McpListedTool = {
+ name: string;
+ description: string | undefined;
+ inputSchema: JSONSchema7;
+ annotations: McpToolAnnotations;
+};
diff --git a/packages/twenty-server/src/engine/api/mcp/types/mcp-method.type.ts b/packages/twenty-server/src/engine/api/mcp/types/mcp-method.type.ts
new file mode 100644
index 00000000000..a8cd7f3b2a0
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/types/mcp-method.type.ts
@@ -0,0 +1,3 @@
+import { type MCP_METHODS } from 'src/engine/api/mcp/constants/mcp-methods.const';
+
+export type McpMethod = (typeof MCP_METHODS)[number];
diff --git a/packages/twenty-server/src/engine/api/mcp/types/mcp-result.type.ts b/packages/twenty-server/src/engine/api/mcp/types/mcp-result.type.ts
new file mode 100644
index 00000000000..33012ad2589
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/types/mcp-result.type.ts
@@ -0,0 +1,11 @@
+import { type McpInitializeResult } from 'src/engine/api/mcp/types/mcp-initialize-result.type';
+import { type McpToolCallResult } from 'src/engine/api/mcp/types/mcp-tool-call-result.type';
+import { type McpToolsListResult } from 'src/engine/api/mcp/types/mcp-tools-list-result.type';
+
+export type McpResult =
+ | McpInitializeResult
+ | McpToolCallResult
+ | McpToolsListResult
+ | { prompts: [] }
+ | { resources: [] }
+ | Record<string, never>;
diff --git a/packages/twenty-server/src/engine/api/mcp/types/mcp-tool-call-result.type.ts b/packages/twenty-server/src/engine/api/mcp/types/mcp-tool-call-result.type.ts
new file mode 100644
index 00000000000..eb52d722a8c
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/types/mcp-tool-call-result.type.ts
@@ -0,0 +1,4 @@
+export type McpToolCallResult = {
+ content: { type: 'text'; text: string }[];
+ isError: boolean;
+};
diff --git a/packages/twenty-server/src/engine/api/mcp/types/mcp-tools-list-result.type.ts b/packages/twenty-server/src/engine/api/mcp/types/mcp-tools-list-result.type.ts
new file mode 100644
index 00000000000..3f852fb4eb2
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/types/mcp-tools-list-result.type.ts
@@ -0,0 +1,5 @@
+import { type McpListedTool } from 'src/engine/api/mcp/types/mcp-listed-tool.type';
+
+export type McpToolsListResult = {
+ tools: McpListedTool[];
+};
diff --git a/packages/twenty-server/src/engine/api/mcp/utils/__tests__/build-json-rpc-error.util.spec.ts b/packages/twenty-server/src/engine/api/mcp/utils/__tests__/build-json-rpc-error.util.spec.ts
new file mode 100644
index 00000000000..02e614aa5fc
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/utils/__tests__/build-json-rpc-error.util.spec.ts
@@ -0,0 +1,47 @@
+import { ForbiddenException } from '@nestjs/common';
+
+import {
+ McpException,
+ McpExceptionCode,
+} from 'src/engine/api/mcp/exceptions/mcp.exception';
+import { buildJsonRpcError } from 'src/engine/api/mcp/utils/build-json-rpc-error.util';
+import {
+ PermissionsException,
+ PermissionsExceptionCode,
+} from 'src/engine/metadata-modules/permissions/permissions.exception';
+
+describe('buildJsonRpcError', () => {
+ it.each([
+ [McpExceptionCode.METHOD_NOT_FOUND, -32601],
+ [McpExceptionCode.INVALID_PARAMS, -32602],
+ [McpExceptionCode.FORBIDDEN, -32000],
+ ])('should map the %s MCP exception to code %p', (code, jsonRpcCode) => {
+ expect(buildJsonRpcError(new McpException('Refused', code))).toEqual({
+ code: jsonRpcCode,
+ message: 'Refused',
+ });
+ });
+
+ it('should return the message of an HTTP exception as a server error', () => {
+ expect(
+ buildJsonRpcError(new ForbiddenException('Workspace suspended')),
+ ).toEqual({ code: -32000, message: 'Workspace suspended' });
+ });
+
+ it('should return the message of a domain exception as an internal error', () => {
+ expect(
+ buildJsonRpcError(
+ new PermissionsException(
+ 'User workspace not found',
+ PermissionsExceptionCode.USER_WORKSPACE_NOT_FOUND,
+ ),
+ ),
+ ).toEqual({ code: -32603, message: 'User workspace not found' });
+ });
+
+ it('should hide the message of an unexpected error', () => {
+ expect(
+ buildJsonRpcError(new TypeError('Cannot read properties of undefined')),
+ ).toEqual({ code: -32603, message: 'Internal server error' });
+ });
+});
diff --git a/packages/twenty-server/src/engine/api/mcp/utils/build-json-rpc-error.util.ts b/packages/twenty-server/src/engine/api/mcp/utils/build-json-rpc-error.util.ts
new file mode 100644
index 00000000000..e0f2ea96299
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/utils/build-json-rpc-error.util.ts
@@ -0,0 +1,48 @@
+import { HttpException } from '@nestjs/common';
+
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { JSON_RPC_ERROR_CODE } from 'src/engine/api/mcp/constants/json-rpc-error-code.const';
+import {
+ McpException,
+ McpExceptionCode,
+} from 'src/engine/api/mcp/exceptions/mcp.exception';
+import { type JsonRpcError } from 'src/engine/api/mcp/types/json-rpc-error.type';
+import { CustomException } from 'src/utils/custom-exception';
+
+const getJsonRpcErrorCode = (code: keyof typeof McpExceptionCode) => {
+ switch (code) {
+ case McpExceptionCode.METHOD_NOT_FOUND:
+ return JSON_RPC_ERROR_CODE.METHOD_NOT_FOUND;
+ case McpExceptionCode.INVALID_PARAMS:
+ return JSON_RPC_ERROR_CODE.INVALID_PARAMS;
+ case McpExceptionCode.FORBIDDEN:
+ return JSON_RPC_ERROR_CODE.SERVER_ERROR;
+ default:
+ return assertUnreachable(code);
+ }
+};
+
+export const buildJsonRpcError = (exception: Error): JsonRpcError => {
+ if (exception instanceof McpException) {
+ return {
+ code: getJsonRpcErrorCode(exception.code),
+ message: exception.message,
+ };
+ }
+
+ if (exception instanceof HttpException) {
+ return {
+ code: JSON_RPC_ERROR_CODE.SERVER_ERROR,
+ message: exception.message || 'Request failed',
+ };
+ }
+
+ return {
+ code: JSON_RPC_ERROR_CODE.INTERNAL_ERROR,
+ message:
+ exception instanceof CustomException
+ ? exception.message
+ : 'Internal server error',
+ };
+};
diff --git a/packages/twenty-server/src/engine/api/mcp/utils/is-mcp-method.util.ts b/packages/twenty-server/src/engine/api/mcp/utils/is-mcp-method.util.ts
new file mode 100644
index 00000000000..4933935d28a
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/utils/is-mcp-method.util.ts
@@ -0,0 +1,5 @@
+import { MCP_METHODS } from 'src/engine/api/mcp/constants/mcp-methods.const';
+import { type McpMethod } from 'src/engine/api/mcp/types/mcp-method.type';
+
+export const isMcpMethod = (method: string): method is McpMethod =>
+ MCP_METHODS.some((mcpMethod) => mcpMethod === method);
diff --git a/packages/twenty-server/src/engine/api/mcp/utils/wrap-jsonrpc-response.util.ts b/packages/twenty-server/src/engine/api/mcp/utils/wrap-jsonrpc-response.util.ts
index 4eaea1f97f9..6e25284a76c 100644
--- a/packages/twenty-server/src/engine/api/mcp/utils/wrap-jsonrpc-response.util.ts
+++ b/packages/twenty-server/src/engine/api/mcp/utils/wrap-jsonrpc-response.util.ts
@@ -1,8 +1,9 @@
+import { type JsonRpcError } from 'src/engine/api/mcp/types/json-rpc-error.type';
+import { type McpResult } from 'src/engine/api/mcp/types/mcp-result.type';
+
export const wrapJsonRpcResponse = (
id: string | number,
- payload:
- | Record<'result', Record<string, unknown>>
- | Record<'error', Record<string, unknown>>,
+ payload: { result: McpResult } | { error: JsonRpcError },
) => {
return {
id,
diff --git a/packages/twenty-server/test/integration/ai/suites/mcp.controller.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/mcp.controller.integration-spec.ts
index 62be004a8d8..97b96997c97 100644
--- a/packages/twenty-server/test/integration/ai/suites/mcp.controller.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/mcp.controller.integration-spec.ts
@@ -58,6 +58,25 @@ describe('MCP Controller (integration)', () => {
});
});
+ it('should return method not found for an unsupported method', async () => {
+ await postMcp({
+ jsonrpc: '2.0',
+ method: 'sampling/createMessage',
+ id: 'unsupported-method',
+ })
+ .expect(200)
+ .expect((res) => {
+ expect(res.body).toEqual({
+ id: 'unsupported-method',
+ jsonrpc: '2.0',
+ error: {
+ code: -32601,
+ message: "Method 'sampling/createMessage' not found",
+ },
+ });
+ });
+ });
+
it('should respond to initialize with spec-compliant InitializeResult', async () => {
await postMcp({ jsonrpc: '2.0', method: 'initialize', id: 123 })
.expect(200)