diff --git a/tools/modelcontextprotocol/src/userAgent.ts b/tools/modelcontextprotocol/src/userAgent.ts index ac4d9bfc..5913ba48 100644 --- a/tools/modelcontextprotocol/src/userAgent.ts +++ b/tools/modelcontextprotocol/src/userAgent.ts @@ -25,12 +25,33 @@ export function extractClientName(message: { return undefined; } +const MAX_CLIENT_NAME_LENGTH = 128; +const CLIENT_NAME_ALLOWED = /[^a-zA-Z0-9 ._/-]/g; + /** * Build the User-Agent string, appending the MCP client name if available. */ +function sanitizeClientName(clientName: string): string | undefined { + const sanitized = clientName + .replace(/[\r\n]/g, '') + .replace(/[^\x20-\x7E]/g, '') + .replace(CLIENT_NAME_ALLOWED, '') + .trim() + .slice(0, MAX_CLIENT_NAME_LENGTH); + + if (!sanitized) { + return undefined; + } + + return sanitized; +} + export function buildUserAgent(clientName?: string): string { if (clientName) { - return `${BASE_USER_AGENT} (${clientName})`; + const sanitizedClientName = sanitizeClientName(clientName); + if (sanitizedClientName) { + return `${BASE_USER_AGENT} (${sanitizedClientName})`; + } } return BASE_USER_AGENT; }