-
Notifications
You must be signed in to change notification settings - Fork 488
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
Changes from all commits
ebe828c
84c3b9c
5ca654a
c3ec498
48bc04b
4ae6a17
c46f349
9c96d08
422e6d6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -90,5 +90,8 @@ | |
}, | ||
"engines": { | ||
"node": ">=18.0.0 || >=20.0.0" | ||
}, | ||
"dependencies": { | ||
"@modelcontextprotocol/sdk": "^1.11.0" | ||
} | ||
} |
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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is that part of the protocol? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
}) | ||
); | ||
}); |
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() }, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Perhaps we add something to indicate this comes from MCP? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} | ||
}; | ||
} |
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>; | ||
}>; |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 asname
). 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.