Skip to content

feat(server): MCP server with actions as tools #4012

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
440 changes: 440 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,8 @@
},
"engines": {
"node": ">=18.0.0 || >=20.0.0"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.11.0"
}
}
4 changes: 2 additions & 2 deletions packages/server/lib/controllers/config.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import {
connectionService,
errorManager,
flowService,
getActionsByProviderConfigKey,
getGlobalWebhookReceiveUrl,
getProvider,
getProviders,
getSimplifiedActionsByProviderConfigKey,
getSyncConfigsAsStandardConfig,
getUniqueSyncsByProviderConfig
} from '@nangohq/shared';
Expand Down Expand Up @@ -172,7 +172,7 @@ class ConfigController {
};
});

const actions = await getActionsByProviderConfigKey(environmentId, providerConfigKey);
const actions = await getSimplifiedActionsByProviderConfigKey(environmentId, providerConfigKey);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really follow why this change is about?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's an existing getActionsByProviderConfigKey which is exactly what I need, except it strips everything and just leaves the sync_name (renamed as name). I didn't want to modify it because it's used in some payloads and I want to avoiding breaking anything unrelated. But it's annoying because it takes exactly the function name that I needed.

I could name my function something else, but I would expect getActionsByProviderConfigKey to give me the full action, not a modified and stripped down version of it, so I decided to rename the existing function instead.

const hasWebhook = provider.webhook_routing_script;
let webhookUrl: string | null = null;
if (hasWebhook) {
Expand Down
76 changes: 76 additions & 0 deletions packages/server/lib/controllers/mcp/mcp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { z } from 'zod';

import { connectionService } from '@nangohq/shared';
import { zodErrorToHTTP } from '@nangohq/utils';

import { createMcpServerForConnection } from './server.js';
import { connectionIdSchema, providerConfigKeySchema } from '../../helpers/validation.js';
import { asyncWrapper } from '../../utils/asyncWrapper.js';

import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import type { GetMcp, PostMcp } from '@nangohq/types';

export const validationHeaders = z
.object({
'connection-id': connectionIdSchema,
'provider-config-key': providerConfigKeySchema
})
.strict();

export const postMcp = asyncWrapper<PostMcp>(async (req, res) => {
const valHeaders = validationHeaders.safeParse({ 'connection-id': req.get('connection-id'), 'provider-config-key': req.get('provider-config-key') });
if (!valHeaders.success) {
res.status(400).send({ error: { code: 'invalid_headers', errors: zodErrorToHTTP(valHeaders.error) } });
return;
}

const { environment, account } = res.locals;
const headers: PostMcp['Headers'] = valHeaders.data;

const connectionId = headers['connection-id'];
const providerConfigKey = headers['provider-config-key'];

const { error, response: connection } = await connectionService.getConnection(connectionId, providerConfigKey, environment.id);

if (error || !connection) {
res.status(400).send({
error: { code: 'unknown_connection', message: 'Provided connection-id and provider-config-key do not match a valid connection' }
});
return;
}

const result = await createMcpServerForConnection(account, environment, connection, providerConfigKey);
if (result.isErr()) {
res.status(500).send({ error: { code: 'Internal server error', message: result.error.message } });
return;
}

const server = result.value;
const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined
});

res.on('close', () => {
void transport.close();
void server.close();
});

// Casting because 'exactOptionalPropertyTypes: true' says `?: string` is not equal to `string | undefined`
await server.connect(transport as Transport);
await transport.handleRequest(req, res, req.body);
});

// We have to be explicit about not supporting SSE
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is that part of the protocol?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The client may attempt to open an SSE stream on this endpoint, and we have to respond.

export const getMcp = asyncWrapper<GetMcp>((_, res) => {
res.writeHead(405).end(
JSON.stringify({
jsonrpc: '2.0',
error: {
code: -32000,
message: 'Method not allowed.'
},
id: null
})
);
});
158 changes: 158 additions & 0 deletions packages/server/lib/controllers/mcp/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types';
import tracer from 'dd-trace';

import { OtlpSpan, defaultOperationExpiration, logContextGetter } from '@nangohq/logs';
import { configService, getActionsByProviderConfigKey } from '@nangohq/shared';
import { Err, Ok, truncateJson } from '@nangohq/utils';

import { getOrchestrator } from '../../utils/utils.js';

import type { CallToolRequest, CallToolResult, Tool } from '@modelcontextprotocol/sdk/types';
import type { Config } from '@nangohq/shared';
import type { DBConnectionDecrypted, DBEnvironment, DBSyncConfig, DBTeam, Result } from '@nangohq/types';
import type { Span } from 'dd-trace';
import type { JSONSchema7 } from 'json-schema';

export async function createMcpServerForConnection(
account: DBTeam,
environment: DBEnvironment,
connection: DBConnectionDecrypted,
providerConfigKey: string
): Promise<Result<Server>> {
const server = new Server(
{
name: 'Nango MCP server',
version: '1.0.0'
},
{
capabilities: {
tools: {}
}
}
);

const providerConfig = await configService.getProviderConfig(providerConfigKey, environment.id);

if (!providerConfig) {
return Err(new Error(`Provider config ${providerConfigKey} not found`));
}

const actions = await getActionsForProvider(environment, providerConfig);

server.setRequestHandler(ListToolsRequestSchema, () => {
return {
tools: actions.flatMap((action) => {
const tool = actionToTool(action);
return tool ? [tool] : [];
})
};
});

server.setRequestHandler(CallToolRequestSchema, callToolRequestHandler(actions, account, environment, connection, providerConfig));

return Ok(server);
}

async function getActionsForProvider(environment: DBEnvironment, providerConfig: Config): Promise<DBSyncConfig[]> {
return getActionsByProviderConfigKey(environment.id, providerConfig.unique_key);
}

function actionToTool(action: DBSyncConfig): Tool | null {
const inputSchema =
action.input && action.models_json_schema?.definitions && action.models_json_schema?.definitions?.[action.input]
? (action.models_json_schema.definitions[action.input] as JSONSchema7)
: ({ type: 'object' } as JSONSchema7);

if (inputSchema.type !== 'object') {
// Invalid input schema, skip this action
return null;
}

const description = action.metadata.description || action.sync_name;

return {
name: action.sync_name,
inputSchema: {
type: 'object',
properties: inputSchema.properties,
required: inputSchema.required
},
description
};
}

function callToolRequestHandler(
actions: DBSyncConfig[],
account: DBTeam,
environment: DBEnvironment,
connection: DBConnectionDecrypted,
providerConfig: Config
): (request: CallToolRequest) => Promise<CallToolResult> {
return async (request: CallToolRequest) => {
const active = tracer.scope().active();
const span = tracer.startSpan('server.mcp.triggerAction', {
childOf: active as Span
});

const { name, arguments: toolArguments } = request.params;

const action = actions.find((action) => action.sync_name === name);

if (!action) {
span.finish();
throw new Error(`Action ${name} not found`);
}

const input = toolArguments ?? {};

span.setTag('nango.actionName', action.sync_name)
.setTag('nango.connectionId', connection.id)
.setTag('nango.environmentId', environment.id)
.setTag('nango.providerConfigKey', providerConfig.unique_key);

const logCtx = await logContextGetter.create(
{ operation: { type: 'action', action: 'run' }, expiresAt: defaultOperationExpiration.action() },
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we add something to indicate this comes from MCP?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we'll probably need at some point. I think it is ok without it for now

{
account,
environment,
integration: { id: providerConfig.id!, name: providerConfig.unique_key, provider: providerConfig.provider },
connection: { id: connection.id, name: connection.connection_id },
syncConfig: { id: action.id, name: action.sync_name },
meta: truncateJson({ input })
}
);
logCtx.attachSpan(new OtlpSpan(logCtx.operation));

const actionResponse = await getOrchestrator().triggerAction({
accountId: account.id,
connection,
actionName: action.sync_name,
input,
async: false,
retryMax: 3,
logCtx
});

if (actionResponse.isOk()) {
if (!('data' in actionResponse.value)) {
// Shouldn't happen with sync actions.
return {
content: []
};
}

return {
content: [
{
type: 'text',
text: JSON.stringify(actionResponse.value.data, null, 2)
}
]
};
} else {
span.setTag('nango.error', actionResponse.error);
throw new Error(actionResponse.error.message);
}
};
}
7 changes: 6 additions & 1 deletion packages/server/lib/routes.public.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import multer from 'multer';

import { connectUrl, flagEnforceCLIVersion } from '@nangohq/utils';

import { getAsyncActionResult } from './controllers/action/getAsyncActionResult.js';
import appAuthController from './controllers/appAuth.controller.js';
import { postPublicApiKeyAuthorization } from './controllers/auth/postApiKey.js';
import { postPublicAppStoreAuthorization } from './controllers/auth/postAppStore.js';
Expand Down Expand Up @@ -37,6 +38,7 @@ import { postPublicIntegration } from './controllers/integrations/postIntegratio
import { deletePublicIntegration } from './controllers/integrations/uniqueKey/deleteIntegration.js';
import { getPublicIntegration } from './controllers/integrations/uniqueKey/getIntegration.js';
import { patchPublicIntegration } from './controllers/integrations/uniqueKey/patchIntegration.js';
import { getMcp, postMcp } from './controllers/mcp/mcp.js';
import oauthController from './controllers/oauth.controller.js';
import providerController from './controllers/provider.controller.js';
import { getPublicProvider } from './controllers/providers/getProvider.js';
Expand All @@ -61,7 +63,6 @@ import { resourceCapping } from './middleware/resource-capping.middleware.js';
import { isBinaryContentType } from './utils/utils.js';

import type { Request, RequestHandler } from 'express';
import { getAsyncActionResult } from './controllers/action/getAsyncActionResult.js';

const apiAuth: RequestHandler[] = [authMiddleware.secretKeyAuth.bind(authMiddleware), rateLimiterMiddleware];
const connectSessionAuth: RequestHandler[] = [authMiddleware.connectSessionAuth.bind(authMiddleware), rateLimiterMiddleware];
Expand Down Expand Up @@ -218,6 +219,10 @@ publicAPI.route('/sync/status').get(apiAuth, syncController.getSyncStatus.bind(s
publicAPI.route('/sync/:name/variant/:variant').post(apiAuth, postSyncVariant);
publicAPI.route('/sync/:name/variant/:variant').delete(apiAuth, deleteSyncVariant);

publicAPI.use('/mcp', jsonContentTypeMiddleware);
publicAPI.route('/mcp').post(apiAuth, postMcp);
publicAPI.route('/mcp').get(apiAuth, getMcp);

publicAPI.use('/flow', jsonContentTypeMiddleware);
publicAPI.route('/flow/attributes').get(apiAuth, syncController.getFlowAttributes.bind(syncController));
// @deprecated use /scripts/configs
Expand Down
3 changes: 2 additions & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
"npm": ">=6.14.11"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.11.2",
"@nangohq/billing": "file:../billing",
"@nangohq/database": "file:../database",
"@nangohq/fleet": "file:../fleet",
"@nangohq/keystore": "file:../keystore",
Expand All @@ -34,7 +36,6 @@
"@nangohq/shared": "file:../shared",
"@nangohq/utils": "file:../utils",
"@nangohq/webhooks": "file:../webhooks",
"@nangohq/billing": "file:../billing",
"@workos-inc/node": "6.2.0",
"axios": "1.9.0",
"body-parser": "1.20.3",
Expand Down
24 changes: 23 additions & 1 deletion packages/shared/lib/services/sync/config/config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,29 @@ export async function getActionConfigByNameAndProviderConfigKey(environment_id:
return false;
}

export async function getActionsByProviderConfigKey(environment_id: number, unique_key: string): Promise<Action[]> {
export async function getActionsByProviderConfigKey(environment_id: number, unique_key: string): Promise<DBSyncConfig[]> {
const nango_config_id = await configService.getIdByProviderConfigKey(environment_id, unique_key);

if (!nango_config_id) {
return [];
}

const result = await schema().from<DBSyncConfig>(TABLE).where({
environment_id,
nango_config_id,
deleted: false,
active: true,
type: 'action'
});

if (result) {
return result;
}

return [];
}

export async function getSimplifiedActionsByProviderConfigKey(environment_id: number, unique_key: string): Promise<Action[]> {
const nango_config_id = await configService.getIdByProviderConfigKey(environment_id, unique_key);

if (!nango_config_id) {
Expand Down
2 changes: 2 additions & 0 deletions packages/types/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,5 @@ export type * from './fleet/index.js';

export type * from './persist/api.js';
export type * from './jobs/api.js';

export type * from './mcp/api.js';
19 changes: 19 additions & 0 deletions packages/types/lib/mcp/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { ApiError, Endpoint } from '../api.js';

export type PostMcp = Endpoint<{
Method: 'POST';
Path: '/mcp';
Body: Record<string, unknown>;
Headers: {
'connection-id': string;
'provider-config-key': string;
};
Success: Record<string, unknown>;
Error: ApiError<'missing_connection_id' | 'unknown_connection'>;
}>;

export type GetMcp = Endpoint<{
Method: 'GET';
Path: '/mcp';
Success: Record<string, unknown>;
}>;
2 changes: 1 addition & 1 deletion packages/types/lib/syncConfigs/db.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { JSONSchema7 } from 'json-schema';
import type { TimestampsAndDeleted } from '../db';
import type { LegacySyncModelSchema, NangoConfigMetadata } from '../deploy/incomingFlow';
import type { NangoModel, ScriptTypeLiteral, SyncTypeLiteral } from '../nangoYaml';
import type { JSONSchema7 } from 'json-schema';

export interface DBSyncConfig extends TimestampsAndDeleted {
id: number;
Expand Down
Loading